<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-03-03T23:58:26.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-03-03T23:42:23.9860000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-03-03T23:57:49.3470000</UpdatedUtcDate>
    <ScriptId>HWENTITYEDIT</ScriptId>
    <Description>Entity Edit</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_EntityEdit
Option Explicit On
Option Strict On

' #################################################################
' Entity Edit form HTML Widget
'
' Version: 1.02 (04/03/2024)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  25/09/2023  ISS      J030253   Created
'    1.01  14/12/2023  ISS      J032511   Various tidy-ups
'    1.02  04/03/2024  ISS      J033018   Update obsoleted function
' #################################################################

' Constants
Private Const FORM_KEY As String = "Entities"

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

' Standard Parameters
Private mEntityId 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
    mEntityId = .GetString("EntityId") ' Always use Startup Parameters since the Entity 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 "RefreshCompanyFileList"
        ' Refresh Company File List
        Main = RefreshCompanyFileList(returnValue)
        
      Case "RefreshTenantList"
        ' Refresh Tenant List
        Main = RefreshTenantList(returnValue)  
        
      Case Else
        Main = False
        finBL.Error.ErrorBeginFormat("Unhandled event '{0}'", eventId)
    End Select
  End If

End Function

''' &lt;summary&gt;
'''  Load Entity.
''' &lt;/summary&gt;
Private Function GetEntity(ByRef entity As finEntity) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Create and Load Entity
  If Success Then
    ' Create Entity
    entity = finBL.CreateEntity()

    ' Load Entity
    If Len(mDuplicateRecordId) &lt;&gt; 0 Then
      ' New record (by duplicating existing)
      Success = entity.Load(mDuplicateRecordId)
      If Success Then 
        entity.Duplicate()
        entity.MainBranchId = ""
      End If
    ElseIf Len(mEntityId) = 0 Then
      ' New record
    Else
      Success = entity.Load(mEntityId)
    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 Entity As finEntity
  Dim EntityAccountType As finEntityAccountType
  Dim EntityBranch As finEntityBranch
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Get Entity
  If Success Then
    Success = GetEntity(Entity)
  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.Entities") Then
        .ReadOnly = True
      Else
        .ReadOnly = False
      End If

      ' Record
      .Pk = Entity.Pk
      .Timestamp = Entity.Timestamp

      ' Page Permissions (defined here since they are used below)
      .AllowPageGeneral = True
      .AllowPageCalendar = True
      .AllowPageOptions = True
      .AllowPageBranches = True
      .AllowPageAccountTypes = True
      .AllowPageAccounts = True
      .AllowPageCreditReporting = finBL.Settings.AddOns.CreditReporting
      .AllowPageGeneralLedger = finBL.Settings.UseGeneralLedger
      .AllowPageDocument = True
      .AllowPageMessaging = finBL.Settings.AddOns.Entity
      .AllowPageUserDefined = finBL.Settings.HasEntityUser

      ' General
      .EntityId = Entity.EntityId ' Always need to return Entity Id
      If .AllowPageGeneral Then
        .Active = Entity.Active
        .Name = Entity.Name

        .BusinessNumber = Entity.BusinessNumber
        .TaxNumber = Entity.TaxNumber
        .GstNumber = Entity.GstNumber
        .OrganisationNumber = Entity.OrganisationNumber
        
        .CostCentreId = Entity.CostCentreId
        
        .LicenceNumber = Entity.LicenceNumber
        .LicenceName = Entity.LicenceName
        
        .DisputeResolutionClientId = Entity.DisputeResolutionClientId
        
        .Notes = Entity.Notes
      End If

      ' Calendar
      If .AllowPageCalendar Then
        .FinancialYearStart = Entity.FinancialYearStart
        .TaxYearStart = Entity.TaxYearStart
        
        .CalendarBankingId = Entity.CalendarBankingId
        
        .CalendarWorkingId = Entity.CalendarWorkingId
        
        ' Convert to Friendly Mnemonics here so the 'is dirty' functionality works correctly Client-side
        .WithholdingTaxPeriod = finBL.Utilities.DateCycleGetMnemonicFriendly(False, Entity.WithholdingTaxPeriod)        
        .AccountingPeriod = finBL.Utilities.DateCycleGetMnemonicFriendly(False, Entity.AccountingPeriod)
      End If
      
      ' Options
      If .AllowPageOptions Then
        .DefaultState = Entity.DefaultState
        
        .SecuredPartyGroupId = Entity.SecuredPartyGroupId
        
        .PayIdPaymentMethodId = Entity.PayIdPaymentMethodId
        
        .LogoFileName = Entity.LogoFileName
        .LogoFileName2 = Entity.LogoFileName2
        
        .LogoResource1Id = Entity.LogoResource1Id
        .OtherResource1Id = Entity.OtherResource1Id
      End If

      ' Branches
      If .AllowPageBranches Then
        .MainBranchId = Entity.MainBranchId
        
        For Each EntityBranch In Entity.Branches
          .EntityBranches.Add(New EntityBranch(EntityBranch))
        Next   
      End If
      
      ' Account Types
      If .AllowPageAccountTypes Then
        .RestrictAccountTypes = Entity.RestrictAccountTypes
        
        For Each EntityAccountType In Entity.AccountTypes
          .EntityAccountTypes.Add(New EntityAccountType(EntityAccountType))
        Next 
        .EntityAccountTypes.Sort(AddressOf EntityAccountTypes_SortComparer)
      End If
      
      ' Accounts
      If .AllowPageAccounts Then
        .AccountNextId = Entity.AccountNextId
        .AccountLoanNextId = Entity.AccountLoanNextId
        .AccountDepositNextId = Entity.AccountDepositNextId
        
        .DateAccountOpenBegin = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(Entity.DateAccountOpenBegin)
        .DateAccountOpenEnd = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(Entity.DateAccountOpenEnd)
        
        .DateTransactionBegin = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(Entity.DateTransactionBegin)
        .DateTransactionBeginDisbursements = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(Entity.DateTransactionBeginDisbursements)
        .DateTransactionEnd = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(Entity.DateTransactionEnd)
      End If
      
      ' Credit Reporting
      If .AllowPageCreditReporting Then
        .CreditReportingExportType = Entity.CreditReportingExportTypeText
        .CreditReportingExportFilename = Entity.CreditReportingExportFilename
        .CreditReportingTestMode = Entity.CreditReportingTestMode
        
        .CreditReportingAllowBatchTypeInitial = Entity.CreditReportingAllowBatchTypeInitial
        .CreditReportingAllowBatchTypePeriodic = Entity.CreditReportingAllowBatchTypePeriodic
        .CreditReportingAllowBatchTypeCorrection = Entity.CreditReportingAllowBatchTypeCorrection
        
        .CreditReportingNotificationEmail = Entity.CreditReportingNotificationEmail
        
        .CreditReportingProviderName = Entity.CreditReportingProviderName
        .CreditReportingProviderReference = Entity.CreditReportingProviderReference
        .CreditReportingSignatoryId = Entity.CreditReportingSignatoryId
        .CreditReportingIndustryType = Entity.CreditReportingIndustryType
        .CreditReportingIsLicensee = Entity.CreditReportingIsLicensee
        
        .CreditReportingContactName = Entity.CreditReportingContactName
        .CreditReportingContactEmail = Entity.CreditReportingContactEmail
        .CreditReportingContactPhone = Entity.CreditReportingContactPhone
        
        .CreditReportingResponseDetail = Entity.CreditReportingResponseDetailText
      End If

      ' General Ledger
      If .AllowPageGeneralLedger Then
        .GlSource = Entity.GlSource
        
        .GlFileName = Entity.GlFileName
        .GlDatabaseName = Entity.GlDatabaseName
        .GlExternalUserId = Entity.GlExternalUserId
        .GlExternalUserPassword = Entity.GlExternalUserPassword
        .GlExportTransactionNarrative = Entity.GlExportTransactionNarrative
        .GlExportOverrideGlobalSettings = Entity.GlExportOverrideGlobalSettings
        .GlExportIncludeBranch = Entity.GlExportIncludeBranch
        .GlExportIncludeDepartment = Entity.GlExportIncludeDepartment
        
        .GlExportAccountStructure = Entity.GlExportAccountStructure
        
        .GlMyobOverrideGlobalCredentials = Entity.GlMyobOverrideGlobalCredentials
        .GlMyobApiKey = Entity.GlMyobApiKey
        .GlMyobApiSecret = Entity.GlMyobApiSecret
        .GlMyobOAuthData = Entity.GlMyobOAuthData
        .OriginalGlMyobOAuthData = Entity.GlMyobOAuthData
        .GlMyobCompanyFileId = Entity.GlMyobCompanyFileId
        
        .GlXeroOverrideGlobalCredentials = Entity.GlXeroOverrideGlobalCredentials
        .GlXeroClientId = Entity.GlXeroClientId
        .GlXeroClientSecret = Entity.GlXeroClientSecret
        .GlXeroOAuthData = Entity.GlXeroOAuthData
        .OriginalGlXeroOAuthData = Entity.GlXeroOAuthData
        .GlXeroTenantId = Entity.GlXeroTenantId
        .GlXeroDefaultContactId = Entity.GlXeroDefaultContactId
        
        .GlXeroTrackingCategoryAName = Entity.GlXeroTrackingCategoryAName
        .GlXeroTrackingCategoryABasis = Entity.GlXeroTrackingCategoryABasisText
        
        .GlXeroTrackingCategoryBName = Entity.GlXeroTrackingCategoryBName
        .GlXeroTrackingCategoryBBasis = Entity.GlXeroTrackingCategoryBBasisText
      End If
      
      ' Document
      If .AllowPageDocument Then
        .DocumentContent1 = Entity.DocumentContent1
        .DocumentContent2 = Entity.DocumentContent2
      End If
      
      ' Messaging
      If .AllowPageMessaging Then
        .EmailDisclaimer = Entity.EmailDisclaimer
      End If
      
      ' User Defined
      If .AllowPageUserDefined Then
        .UserDefinedParameters = finBL.CreateWsParameters(finBL.ParameterSets.CreateParameters(finBL.Settings.EntityUserDefinedParameterSetPk, False))
        .UserDataJson = Entity.UserData.ToSimpleJsonString()
      End If

      ' Other

      ' Permissions

      ' Lists
      .AddressStatesList = finBL.CurrentCountry.AddressStatesList.ToCsvString()
      .PayIdSqlWhere = finBL.HtmlWidgetUtilities.EncryptSql(finBL.PaymentMethods.GetDataViewFilter_PayId(Entity.Pk))
      .ResourceImageSqlWhere = finBL.HtmlWidgetUtilities.EncryptSql(finBL.Resources.GetDataViewFilter_EntityImages())
      .BranchesSqlWhere = finBL.HtmlWidgetUtilities.EncryptSql(finBL.Branches.GetDataViewFilter_Entity(Entity.Pk))    
      .CreditReportingExportTypeList = finBL.Enums.isefinCreditReportingExportType_ToCodeDescriptionList().ToJsonObject()
      .CreditReportingResponseOptionList = finBL.Enums.isefinCreditReportingResponseOption_GetList().ToCsvString()
      .XeroTrackingCategoryBasisList = finBL.Enums.isefinXeroTrackingCategoryBasis_ToCodeDescriptionList(True).ToJsonObject()
      
      ' Terminology 
      .Terminology_BusinessNumber = finBL.CurrentCountry.Terminology(isefinCountryTerminology.BusinessNumber)
      .Terminology_BusinessNumberTooltip = finBL.CurrentCountry.Terminology(isefinCountryTerminology.BusinessNumber, False)
      .Terminology_TaxNumber = finBL.CurrentCountry.Terminology(isefinCountryTerminology.TaxNumberOrganisation)
      .Terminology_TaxNumberTooltip = finBL.CurrentCountry.Terminology(isefinCountryTerminology.TaxNumberOrganisation, False)    
      .Terminology_GstNumber = finBL.CurrentCountry.Terminology(isefinCountryTerminology.GSTNumberOrganisation)
      .Terminology_GstNumberTooltip = finBL.CurrentCountry.Terminology(isefinCountryTerminology.GSTNumberOrganisation, False)
      .Terminology_CompanyNumber = finBL.CurrentCountry.Terminology(isefinCountryTerminology.CompanyNumber)
      .Terminology_CompanyNumberTooltip = finBL.CurrentCountry.Terminology(isefinCountryTerminology.CompanyNumber, False)
      If Len(finBL.CurrentCountry.Terminology(isefinCountryTerminology.LicenceNumber)) &lt;&gt; 0 Then
        .Terminology_LicenceNumber = finBL.CurrentCountry.Terminology(isefinCountryTerminology.LicenceNumber, False)
      End If      
      If Len(finBL.CurrentCountry.Terminology(isefinCountryTerminology.DisputeResolutionScheme)) &lt;&gt; 0 Then
        .Terminology_DisputeResolutionScheme = finBL.CurrentCountry.Terminology(isefinCountryTerminology.DisputeResolutionScheme, False)
      End If      
      
      ' Other
      .DateBoxMinValue = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(New DateTime(1980, 1, 1))
      .DateBoxMaxValue = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(New DateTime(2050, 12, 31))
      
      ' Configuration
      .AddonsCostCentre = finBL.Settings.AddOns.CostCentre      
      .AddonsDepositAccount = finBL.Settings.AddOns.DepositAccount
      .AddonsDisbursements = finBL.Settings.AddOns.Disbursements
      .AddonsSecurityRegister = finBL.Settings.AddOns.SecurityRegister
      .AddonsBankingAdvanced_Split = finBL.Settings.AddOns.BankingAdvanced_Split
      .AddonsLoansAny = finBL.Settings.AddOns.LoansAny
      .GlAllowUserToModifySettings = finBL.Settings.GlAllowUserToModifySettings
      .GlExportType = finBL.Settings.GlExportType.ToString()
      .GlMyobCompanyFileIdBlankTip = finBL.Settings.GlMyobCompanyFileId
      .GlExportAccountStructureBlankTip = finBL.Settings.GlExportAccountStructure
      .XeroTenantBlankTip = finBL.Settings.GlXeroTenantId
      .XeroDefaultContactIdBlankTip = finBL.Settings.GlXeroDefaultContactId
      .XeroTrackingCategoryANameBlankTip = finBL.Settings.GlXeroTrackingCategoryAName
      .XeroTrackingCategoryABasisBlankTip = finBL.Settings.GlXeroTrackingCategoryABasisText
      .XeroTrackingCategoryBNameBlankTip = finBL.Settings.GlXeroTrackingCategoryBName
      .XeroTrackingCategoryBBasisBlankTip = finBL.Settings.GlXeroTrackingCategoryBBasisText
      .UseAccountingPeriods = finBL.Settings.UseAccountingPeriods
      .HideOtherPages = mCombinedParameters.GetBoolean("HideOtherPages", False)
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
      .SecurityStmtDefaultSecuredPartyGroupId = finBL.Settings.SecurityStmtDefaultSecuredPartyGroupId
      .ShowDefaultState = finBL.CurrentCountry.AddressStatesList.Count &gt; 0
    End With
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Entity Account Types Sort Comparer.
''' &lt;/summary&gt;
Private Function EntityAccountTypes_SortComparer(x As EntityAccountType,
                                                 y As EntityAccountType) As Integer

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

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Save Entity.
''' &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 AccountType As EntityAccountType
  Dim Entity As finEntity
  Dim EntityAccountType As finEntityAccountType  
  Dim obj As Object
  Dim Record As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Entity
  If Success Then
    Success = GetEntity(Entity)
  End If

  ' Validate
  If Success Then
    If Record.Timestamp &lt;&gt; Entity.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 Entity
      With Entity
        ' General
        If Record.AllowPageGeneral Then
          .EntityId = Record.EntityId          
          .Active = Record.Active
          .Name = Record.Name

          .BusinessNumber = Record.BusinessNumber
          .TaxNumber = Record.TaxNumber
          .GstNumber = Record.GstNumber
          .OrganisationNumber = Record.OrganisationNumber

          .CostCentreId = Record.CostCentreId
          
          .LicenceNumber = Record.LicenceNumber
          .LicenceName = Record.LicenceName
          
          .DisputeResolutionClientId = Record.DisputeResolutionClientId
          
          .Notes = Record.Notes
        End If

        ' Calendar
        If Record.AllowPageCalendar Then
          .FinancialYearStart = Record.FinancialYearStart
          .TaxYearStart = Record.TaxYearStart
          
          .CalendarBankingId = Record.CalendarBankingId
          
          .CalendarWorkingId = Record.CalendarWorkingId
          
          .WithholdingTaxPeriod = Record.WithholdingTaxPeriod
          
          .AccountingPeriod = Record.AccountingPeriod
        End If
        
        ' Options
        If Record.AllowPageOptions Then
          .DefaultState = Record.DefaultState
          
          .SecuredPartyGroupId = Record.SecuredPartyGroupId
          
          .PayIdPaymentMethodId = Record.PayIdPaymentMethodId
          
          .LogoFileName = Record.LogoFileName
          .LogoFileName2 = Record.LogoFileName2
          
          .LogoResource1Id = Record.LogoResource1Id
          .OtherResource1Id = Record.OtherResource1Id
        End If

        ' Branches
        If Record.AllowPageBranches Then
          .MainBranchId = Record.MainBranchId
        End If
        
        ' Account Types
        If Record.AllowPageAccountTypes Then
          .RestrictAccountTypes = Record.RestrictAccountTypes
          
          For Each EntityAccountType In .AccountTypes
            For Each AccountType In Record.EntityAccountTypes
              If EntityAccountType.AccountTypePk = AccountType.AccountTypePk Then
                EntityAccountType.Available = AccountType.Available
                Exit For
              End If
            Next 
          Next 
        End If
        
        ' Accounts
        If Record.AllowPageAccounts Then
          .AccountNextId = Record.AccountNextId
          .AccountLoanNextId = Record.AccountLoanNextId
          .AccountDepositNextId = Record.AccountDepositNextId
          
          .DateAccountOpenBegin = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(Record.DateAccountOpenBegin)
          .DateAccountOpenEnd = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(Record.DateAccountOpenEnd)
          
          .DateTransactionBegin = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(Record.DateTransactionBegin)
          .DateTransactionBeginDisbursements = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(Record.DateTransactionBeginDisbursements)
          .DateTransactionEnd = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(Record.DateTransactionEnd)
        End If
        
        ' Credit Reporting
        If Record.AllowPageCreditReporting Then
          .CreditReportingExportTypeText = Record.CreditReportingExportType
          .CreditReportingExportFilename = Record.CreditReportingExportFilename
          .CreditReportingTestMode = Record.CreditReportingTestMode
          
          .CreditReportingAllowBatchTypeInitial = Record.CreditReportingAllowBatchTypeInitial
          .CreditReportingAllowBatchTypePeriodic = Record.CreditReportingAllowBatchTypePeriodic
          .CreditReportingAllowBatchTypeCorrection = Record.CreditReportingAllowBatchTypeCorrection
          
          .CreditReportingNotificationEmail = Record.CreditReportingNotificationEmail
          
          .CreditReportingProviderName = Record.CreditReportingProviderName
          .CreditReportingProviderReference = Record.CreditReportingProviderReference
          .CreditReportingSignatoryId = Record.CreditReportingSignatoryId
          .CreditReportingIndustryType = Record.CreditReportingIndustryType
          .CreditReportingIsLicensee = Record.CreditReportingIsLicensee
          
          .CreditReportingContactName = Record.CreditReportingContactName
          .CreditReportingContactEmail = Record.CreditReportingContactEmail
          .CreditReportingContactPhone = Record.CreditReportingContactPhone
          
          .CreditReportingResponseDetailText = Record.CreditReportingResponseDetail
        End If
        
        ' General Ledger
        If Record.AllowPageGeneralLedger Then
          .GlSource = Record.GlSource
          
          .GlFileName = Record.GlFileName
          .GlDatabaseName = Record.GlDatabaseName
          .GlExternalUserId = Record.GlExternalUserId
          .GlExternalUserPassword = Record.GlExternalUserPassword
          .GlExportTransactionNarrative = Record.GlExportTransactionNarrative
          .GlExportOverrideGlobalSettings = Record.GlExportOverrideGlobalSettings
          .GlExportIncludeBranch = Record.GlExportIncludeBranch
          .GlExportIncludeDepartment = Record.GlExportIncludeDepartment
          
          .GlExportAccountStructure = Record.GlExportAccountStructure
          
          .GlMyobOverrideGlobalCredentials = Record.GlMyobOverrideGlobalCredentials
          .GlMyobApiKey = Record.GlMyobApiKey
          .GlMyobApiSecret = Record.GlMyobApiSecret
          .GlMyobOAuthData = Record.GlMyobOAuthData          
          .GlMyobCompanyFileId = Record.GlMyobCompanyFileId
          
          .GlXeroOverrideGlobalCredentials = Record.GlXeroOverrideGlobalCredentials
          .GlXeroClientId = Record.GlXeroClientId
          .GlXeroClientSecret = Record.GlXeroClientSecret
          .GlXeroOAuthData = Record.GlXeroOAuthData
          .GlXeroTenantId = Record.GlXeroTenantId
          .GlXeroDefaultContactId = Record.GlXeroDefaultContactId
          
          .GlXeroTrackingCategoryAName = Record.GlXeroTrackingCategoryAName
          .GlXeroTrackingCategoryABasisText = Record.GlXeroTrackingCategoryABasis
          
          .GlXeroTrackingCategoryBName = Record.GlXeroTrackingCategoryBName
          .GlXeroTrackingCategoryBBasisText = Record.GlXeroTrackingCategoryBBasis
        End If
        
        ' Document
        If Record.AllowPageDocument Then
          .DocumentContent1 = Record.DocumentContent1
          .DocumentContent2 = Record.DocumentContent2
        End If                
        
        ' Messaging
        If Record.AllowPageMessaging Then
          .EmailDisclaimer = Record.EmailDisclaimer
        End If

        ' User Defined
        If Record.AllowPageUserDefined Then
          .UserData.FromHtmlWidgetParametersJsonString(Record.UserDataJson)
        End If
      End With

      ' Save
      If Success Then
        Success = Entity.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;
'''  Refresh Company File List.
''' &lt;/summary&gt;
Private Function RefreshCompanyFileList(ByRef returnValue As String) As Boolean
  
  Dim CodeDescriptionList As ISCodeDescriptionList
  Dim Entity As finEntity
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Get Entity
  Success = GetEntity(Entity)
  
  ' Switch to this Entity
  If Success Then
    Success = finBL.AccountingInterface.SwitchEntity(Entity.EntityId)
  End If
  
  ' Get List
  If Success Then
    Success = finBL.AccountingInterface.Service_Myob.GetCompaniesList(CodeDescriptionList)
  End If
  
  ' Return
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(CodeDescriptionList.ToJsonObject(), returnValue)
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Refresh Tenant List.
''' &lt;/summary&gt;
Private Function RefreshTenantList(ByRef returnValue As String) As Boolean
  
  Dim CodeDescriptionList As ISCodeDescriptionList
  Dim Entity As finEntity
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Get Entity
  Success = GetEntity(Entity)
  
  ' Switch to this Entity
  If Success Then
    Success = finBL.AccountingInterface.SwitchEntity(Entity.EntityId)
  End If
  
  ' Get List
  If Success Then
    Success = finBL.AccountingInterface.Service_Xero.GetTenantList(CodeDescriptionList)
  End If
  
  ' Return
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(CodeDescriptionList.ToJsonObject(), returnValue)
  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 EntityId As String
  Public Active As Boolean
  Public Name As String

  Public BusinessNumber As String
  Public TaxNumber As String
  Public GstNumber As String
  Public OrganisationNumber As String

  Public CostCentreId As String
  Public LicenceNumber As String
  Public LicenceName As String
  
  Public DisputeResolutionClientId As String
  
  Public Notes As String

  ' Calendar
  Public FinancialYearStart As Integer
  Public TaxYearStart As Integer
  
  Public CalendarBankingId As String
  
  Public CalendarWorkingId As String
  
  Public WithholdingTaxPeriod As String
  
  Public AccountingPeriod As String
  
  ' Options
  Public DefaultState As String

  Public SecuredPartyGroupId As String

  Public PayIdPaymentMethodId As String

  Public LogoFileName As String
  Public LogoFileName2 As String
  
  Public LogoResource1Id As String
  Public OtherResource1Id As String
  
  ' Branches
  Public MainBranchId As String
  
  ' Account Types
  Public RestrictAccountTypes As Boolean
  
  ' Accounts
  Public AccountNextId As String
  Public AccountLoanNextId As String
  Public AccountDepositNextId As String
  
  Public DateAccountOpenBegin As Date
  Public DateAccountOpenEnd As Date
  
  Public DateTransactionBegin As Date
  Public DateTransactionBeginDisbursements As Date
  Public DateTransactionEnd As Date

  ' Credit Reporting
  Public CreditReportingExportType As String
  Public CreditReportingExportFilename As String
  Public CreditReportingTestMode As Boolean
  
  Public CreditReportingAllowBatchTypeInitial As Boolean
  Public CreditReportingAllowBatchTypePeriodic As Boolean
  Public CreditReportingAllowBatchTypeCorrection As Boolean
  
  Public CreditReportingNotificationEmail As String
  
  Public CreditReportingProviderName As String
  Public CreditReportingProviderReference As String
  Public CreditReportingSignatoryId As String
  Public CreditReportingIndustryType As String
  Public CreditReportingIsLicensee As Boolean
  
  Public CreditReportingContactName As String
  Public CreditReportingContactEmail As String
  Public CreditReportingContactPhone As String
  
  Public CreditReportingResponseDetail As String
  
  ' General Ledger
  Public GlSource As String
  
  Public GlFileName As String
  Public GlDatabaseName As String
  Public GlExternalUserId As String
  Public GlExternalUserPassword As String
  Public GlExportTransactionNarrative As String
  Public GlExportOverrideGlobalSettings As Boolean
  Public GlExportIncludeBranch As Boolean
  Public GlExportIncludeDepartment As Boolean
  
  Public GlExportAccountStructure As String
  
  Public GlMyobOverrideGlobalCredentials As Boolean
  Public GlMyobApiKey As String
  Public GlMyobApiSecret As String
  Public GlMyobOAuthData As String
  Public OriginalGlMyobOAuthData As String
  Public GlMyobCompanyFileId As String
  
  Public GlXeroOverrideGlobalCredentials As Boolean
  Public GlXeroClientId As String
  Public GlXeroClientSecret As String
  Public GlXeroOAuthData As String
  Public OriginalGlXeroOAuthData As String
  Public GlXeroTenantId As String
  Public GlXeroDefaultContactId As String
  
  Public GlXeroTrackingCategoryAName As String
  Public GlXeroTrackingCategoryABasis As String
  
  Public GlXeroTrackingCategoryBName As String
  Public GlXeroTrackingCategoryBBasis As String
  
  ' Document
  Public DocumentContent1 As String
  Public DocumentContent2 As String
  
  ' Messaging
  Public EmailDisclaimer As String
  
  ' User Defined
  Public UserDefinedParameters As ISWsParameters
  Public UserDataJson As String

  ' Permissions
  Public AllowPageGeneral As Boolean
  Public AllowPageCalendar As Boolean
  Public AllowPageOptions As Boolean
  Public AllowPageBranches As Boolean
  Public AllowPageAccountTypes As Boolean
  Public AllowPageAccounts As Boolean
  Public AllowPageCreditReporting As Boolean
  Public AllowPageGeneralLedger As Boolean
  Public AllowPageDocument As Boolean
  Public AllowPageMessaging As Boolean
  Public AllowPageUserDefined As Boolean

  ' Lists
  Public AddressStatesList As String
  Public PayIdSqlWhere As String
  Public ResourceImageSqlWhere As String
  Public BranchesSqlWhere As String
  Public EntityBranches As New List(Of EntityBranch)
  Public EntityAccountTypes As New List(Of EntityAccountType)
  Public CreditReportingExportTypeList As Object
  Public CreditReportingResponseOptionList As String
  Public XeroTrackingCategoryBasisList As Object

  ' Terminology
  Public Terminology_BusinessNumber As String
  Public Terminology_BusinessNumberTooltip As String
  Public Terminology_TaxNumber As String
  Public Terminology_TaxNumberTooltip As String
  Public Terminology_GstNumber As String
  Public Terminology_GstNumberTooltip As String
  Public Terminology_CompanyNumber As String
  Public Terminology_CompanyNumberTooltip As String
  Public Terminology_LicenceNumber As String
  Public Terminology_DisputeResolutionScheme As String
  
  ' Other
  Public DateBoxMinValue As Date
  Public DateBoxMaxValue As Date
  
  ' Configuration
  Public AddonsCostCentre As Boolean
  Public AddonsDepositAccount As Boolean
  Public AddonsDisbursements As Boolean
  Public AddonsSecurityRegister As Boolean
  Public AddonsBankingAdvanced_Split As Boolean
  Public AddonsLoansAny As Boolean
  Public GlAllowUserToModifySettings As Boolean
  Public GlExportType As String
  Public GlMyobCompanyFileIdBlankTip As String
  Public GlExportAccountStructureBlankTip As String
  Public XeroTenantBlankTip As String
  Public XeroDefaultContactIdBlankTip As String
  Public XeroTrackingCategoryANameBlankTip As String
  Public XeroTrackingCategoryABasisBlankTip As String
  Public XeroTrackingCategoryBNameBlankTip As String
  Public XeroTrackingCategoryBBasisBlankTip As String
  Public UseAccountingPeriods As Boolean
  Public HideOtherPages As Boolean
  Public PromptOnSave As Boolean
  Public SecurityStmtDefaultSecuredPartyGroupId As String
  Public ShowDefaultState As Boolean      

End Class



''' &lt;summary&gt;
'''  Entity.
''' &lt;/summary&gt;
Public Class Entity

  Public EntityId As String
  Public PayIdPaymentMethodSqlWhere As String
  
  Public Sub New()
  End Sub
  
  Public Sub New(entityRO As finEntityRO)
    
    With entityRO
      Me.EntityId = .EntityId
      Me.PayIdPaymentMethodSqlWhere = finBLShared.HtmlWidgetUtilities.EncryptSql(finBLShared.PaymentMethods.GetDataViewFilter_PayId(.Pk))
    End With
    
  End Sub
  
End Class



''' &lt;summary&gt;
'''  Entity Branch.
''' &lt;/summary&gt;
Public Class EntityBranch
  
  Public Active As Boolean
  Public BranchId As String
  Public Description As String
  Public Name As String
  
  Public Sub New(entityBranch As finEntityBranch)
    
    With entityBranch
      Me.Active = .Active
      Me.BranchId = .BranchId
      Me.Description = .Description
      Me.Name = .Name
    End With
    
  End Sub
  
End Class



''' &lt;summary&gt;
'''  Entity Account Type.
''' &lt;/summary&gt;
Public Class EntityAccountType
  
  Public Available As Boolean
  Public Active As Boolean
  Public AccountTypeId As String
  Public AccountTypePk As Integer
  Public AccountClass As String
  Public Description As String
  
  Public Sub New()
  End Sub  
  
  Public Sub New(entityAccountType As finEntityAccountType)
    
    With entityAccountType
      Me.Available = .Available
      Me.Active = .Active
      Me.AccountTypeId = .AccountTypeId
      Me.AccountTypePk = .AccountTypePk
      Me.AccountClass = .AccountClassText
      Me.Description = .Description      
    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 Entity.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <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="Calendar"&gt;Calendar&lt;/li&gt;
        &lt;li tabId="Options"&gt;Options&lt;/li&gt;
        &lt;li tabId="Branches"&gt;Branches&lt;/li&gt;
        &lt;li tabId="AccountTypes"&gt;Account Types&lt;/li&gt;
        &lt;li tabId="Accounts"&gt;Accounts&lt;/li&gt;
        &lt;li tabId="CreditReporting"&gt;Credit Reporting&lt;/li&gt;
        &lt;li tabId="GeneralLedger"&gt;General Ledger&lt;/li&gt;
        &lt;li tabId="Document"&gt;Document&lt;/li&gt;
        &lt;li tabId="Messaging"&gt;Messaging&lt;/li&gt;
        &lt;li tabId="UserDefined"&gt;User Defined&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" style="height:100%"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:9em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCodeAndName"&gt;Code and Description&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtEntityId"&gt;Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtEntityId"/&gt; &lt;input id="chkActive" type="checkbox"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCompanyDetails"&gt;Company details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtBusinessNumber"&gt;Business No:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtBusinessNumber"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtTaxNumber"&gt;Tax Number:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtTaxNumber"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtGstNumber"&gt;GST Number:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGstNumber"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtOrganisationNumber"&gt;Organisation No:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtOrganisationNumber"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCostCentre"&gt;The Cost Centre that this Entity belongs to&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboCostCentre"&gt;Cost Centre:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboCostCentre"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblLicence"&gt;Licence details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtLicenceNumber"&gt;Number:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtLicenceNumber"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtLicenceName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtLicenceName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblDisputeResolution"&gt;Dispute Resolution Scheme details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboDisputeResolutionClientId"&gt;Client:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboDisputeResolutionClientId"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblNotes"&gt;Notes&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr style="height:100%"&gt;
          &lt;th colspan="2" style="height:100%"&gt;&lt;input id="txtNotes"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Calendar --&gt;
    &lt;div id="pageCalendar"&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="lblFinancialYear"&gt;Company's Financial Year and Tax Year&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboFinancialYearStart"&gt;Year Start:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboFinancialYearStart"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboTaxYearStart"&gt;Tax Year Start:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboTaxYearStart"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCalendarBanking"&gt;Business/ Banking Day Calendar for this Entity&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboCalendarBanking"&gt;Calendar:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboCalendarBanking"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCalendarWorking"&gt;Working Day Calendar for this Entity&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboCalendarWorking"&gt;Calendar:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboCalendarWorking"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblWithholdingTaxPeriod"&gt;Length of Withholding Tax Period&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboWithholdingTaxPeriod"&gt;Period:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboWithholdingTaxPeriod"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblAccountingPeriod"&gt;Length of Accounting Period&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountingPeriod"&gt;Period:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountingPeriod"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

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

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblDefaultState"&gt;Default State&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboDefaultState"&gt;State:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboDefaultState"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSecuredPartyGroup"&gt;Default Secured Party Group&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboSecuredPartyGroup"&gt;SPG:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboSecuredPartyGroup"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPayId"&gt;Zepto PayID options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboPayIdPaymentMethod"&gt;Payment&amp;nbsp;Method:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboPayIdPaymentMethod"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblLogoFileName"&gt;Logo image File Name or URL&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtLogoFileName"&gt;Logo File:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtLogoFileName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtLogoFileName2"&gt;Logo File 2:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtLogoFileName2"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblResources"&gt;Resources for this Entity&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboLogoResource1"&gt;Image:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboLogoResource1"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboOtherResource1"&gt;Other:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboOtherResource1"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Branches --&gt;
    &lt;div id="pageBranches"&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:5em" /&gt;
              &lt;col /&gt;
            &lt;/colgroup&gt;
    
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblBranches"&gt;Branches&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;   
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboMainBranch"&gt;Main:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboMainBranch"/&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="gridBranches" 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 /&gt;
            &lt;/colgroup&gt;
    
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblAccountTypes"&gt;Account Types&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;   
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkRestrictAccountTypes" type="checkbox" /&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; 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;!-- Accounts --&gt;
    &lt;div id="pageAccounts"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblAccountNextCodes"&gt;Define the Next Code for New Accounts&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtAccountNextId"&gt;General:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtAccountNextId"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtAccountLoanNextId"&gt;Loans:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtAccountLoanNextId"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtAccountDepositNextId"&gt;Deposits:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtAccountDepositNextId"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblAccountDates"&gt;Valid Account Opening date range&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateAccountBegin"&gt;Begin Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateAccountBegin"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateAccountEnd"&gt;End Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateAccountEnd"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblTransactionDates"&gt;Transactions must be dated between the begin and end dates&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateTransactionBegin"&gt;Begin Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateTransactionBegin"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateTransactionBeginDisbursements"&gt;Disbursements:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateTransactionBeginDisbursements"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateTransactionEnd"&gt;End Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateTransactionEnd"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
    
    
    &lt;!-- Credit Reporting --&gt;
    &lt;div id="pageCreditReporting"&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="lblCCRExportSettings"&gt;Comprehensive Credit Reporting Export Settings&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;    
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboCreditReportingExportType"&gt;Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboCreditReportingExportType"/&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCreditReportingExportFilename"&gt;File Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCreditReportingExportFilename"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkCreditReportingTestMode" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;  
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblBatchTypes"&gt;Available Batch Types&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;   
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkCreditReportingAllowBatchTypeInitial" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;   
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkCreditReportingAllowBatchTypePeriodic" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;  
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkCreditReportingAllowBatchTypeCorrection" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblNotificationDetails"&gt;Notification details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;   
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCreditReportingNotificationEmail"&gt;Email:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCreditReportingNotificationEmail"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblProviderDetails"&gt;Provider details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;  
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCreditReportingProviderName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCreditReportingProviderName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCreditReportingProviderReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCreditReportingProviderReference"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCreditReportingSignatoryId"&gt;Signatory Id:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCreditReportingSignatoryId"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboCreditReportingIndustryType"&gt;Industry Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboCreditReportingIndustryType"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkCreditReportingIsLicensee" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblContactDetails"&gt;Contact details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;  
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCreditReportingContactName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCreditReportingContactName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCreditReportingContactEmail"&gt;Email:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCreditReportingContactEmail"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtCreditReportingContactPhone"&gt;Phone:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtCreditReportingContactPhone"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblResponseOptions"&gt;Response options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;  
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboCreditReportingResponseDetail"&gt;Detail:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboCreditReportingResponseDetail"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
    
    
    &lt;!-- General Ledger --&gt;
    &lt;div id="pageGeneralLedger"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:10em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblGlExportOptions"&gt;General Ledger Export options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;     
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtGlSource"&gt;Source:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGlSource"/&gt;&lt;/td&gt;
        &lt;/tr&gt;   
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblGlExportOptionsOverride"&gt;Overriding General Ledger Export options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;   
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtGlFileName"&gt;File Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGlFileName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;  
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtGlDatabaseName"&gt;Database Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGlDatabaseName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;   
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboGlExternalUserId"&gt;User Id:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboGlExternalUserId"/&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtGlExternalUserPassword"&gt;Password:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGlExternalUserPassword"/&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtGlExportTransactionNarrative"&gt;Summ. Narrative:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGlExportTransactionNarrative"/&gt;&lt;/td&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkGlExportOverrideGlobalSettings" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkGlExportIncludeBranch" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkGlExportIncludeDepartment" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblGLMyobOAuthCredentials"&gt;MYOB OAuth Credentials&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;  
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkGlMyobOverrideGlobalCredentials" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="txtGlMyobApiKey"&gt;API Key:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGlMyobApiKey"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="txtGlMyobApiSecret"&gt;API Secret:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGlMyobApiSecret"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="txtGlMyobOAuthData"&gt;Token Data:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGlMyobOAuthData"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblGLXeroOAuthCredentials"&gt;Xero OAuth Credentials&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;  
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkGlXeroOverrideGlobalCredentials" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="txtGlXeroClientId"&gt;Client Id:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGlXeroClientId"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="txtGlXeroClientSecret"&gt;Client Secret:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGlXeroClientSecret"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="txtGlXeroOAuthData"&gt;Token Data:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGlXeroOAuthData"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblGlExportOptionsAPI"&gt;Enter overriding settings for General Ledger&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboGlMyobCompanyFileId"&gt;Company File Id:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboGlMyobCompanyFileId"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;/th&gt;
          &lt;td&gt;
            &lt;button id="cmdCompanyFileRefresh" class="is-button small icon" icon="Refresh"&gt;Refresh&lt;/button&gt;            
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboGlXeroTenant"&gt;Tenant:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboGlXeroTenant"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;/th&gt;
          &lt;td&gt;
            &lt;button id="cmdTenantRefresh" class="is-button small icon" icon="Refresh"&gt;Refresh&lt;/button&gt;            
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtGlExportAccountStructure"&gt;Account Structure:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGlExportAccountStructure"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;/th&gt;
          &lt;td&gt;&lt;div id="divGlExportAccountStructure" class="is-info-text info small"&gt;Define the Account code structure to send. Include 'A' for a GL Account, 'B' for Department and 'D' for Department. E.g. BB-DD-AAAAAA.&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtGLXeroDefaultContactId"&gt;Default Contact:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGLXeroDefaultContactId"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblGlXeroTrackingCategoryA"&gt;Tracking Category A&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboGlXeroTrackingCategoryABasis"&gt;Option Basis:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboGlXeroTrackingCategoryABasis"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtGlXeroTrackingCategoryAName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGlXeroTrackingCategoryAName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblGlXeroTrackingCategoryB"&gt;Tracking Category B&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt; 
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboGlXeroTrackingCategoryBBasis"&gt;Option Basis:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboGlXeroTrackingCategoryBBasis"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtGlXeroTrackingCategoryBName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtGlXeroTrackingCategoryBName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;    
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblGlVerification"&gt;Verify Connection&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="divGlVerification" class="is-info-text info"&gt;These details can be verified by clicking the 'Verify' button on the read-only version of this Entity&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;    
      &lt;/table&gt;
    &lt;/div&gt;
    
    
    &lt;!-- Document --&gt;
    &lt;div id="pageDocument"&gt;
      &lt;table class="is-form" style="height:100%"&gt;
        &lt;colgroup&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th&gt;&lt;label id="lblDocument"&gt;Text Content to appear Documents&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr style="height:50%"&gt;
          &lt;td&gt;&lt;input id="txtDocumentContent1"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr style="height:50%"&gt;
          &lt;td&gt;&lt;input id="txtDocumentContent2"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
    
    
    &lt;!-- Messaging --&gt;
    &lt;div id="pageMessaging"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th&gt;&lt;label id="lblEmailDisclaimer"&gt;Global Signature or Disclaimer to appear at the bottom of emails&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;input id="txtEmailDisclaimer"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
    
    
    &lt;!-- UserDefined --&gt;
    &lt;div id="pageUserDefined"&gt;
      &lt;div id="phUserDefined" style="display:block"&gt;&lt;/div&gt;
    &lt;/div&gt;

  &lt;/div&gt;


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

&lt;/div&gt;


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

var mOriginalJson;

// Controls
var C = {
  //   General
  lblCodeAndName: null,
  chkActive: null,
  txtEntityId: null,
  txtName: null,

  lblCompanyDetails: null,
  txtBusinessNumber: null,
  txtTaxNumber: null,
  txtGstNumber: null,
  txtOrganisationNumber: null,
  
  lblCostCentre: null,
  cboCostCentre: null,
  
  lblLicence: null,
  txtLicenceNumber: null,
  txtLicenceName: null,
  
  lblDisputeResolution: null,
  cboDisputeResolutionClientId: null,
  
  lblNotes: null,
  txtNotes: null,

  //   Calendar
  lblFinancialYear: null,
  cboFinancialYearStart: null,
  cboTaxYearStart: null,
  
  lblCalendarBanking: null,
  cboCalendarBanking: null,
  
  lblCalendarWorking: null,
  cboCalendarWorking: null,
  
  lblWithholdingTaxPeriod: null,
  cboWithholdingTaxPeriod: null,
  
  lblAccountingPeriod: null,
  cboAccountingPeriod: null,

  //   Options
  lblDefaultState: null,
  cboDefaultState: null,
  
  lblSecuredPartyGroup: null,
  cboSecuredPartyGroup: null,
  
  lblPayId: null,
  cboPayIdPaymentMethod: null,
  
  lblLogoFileName: null,
  txtLogoFileName: null,
  txtLogoFileName2: null,
  
  lblResources: null,
  cboLogoResource1: null,
  cboOtherResource1: null,

  //   Branches
  lblBranches: null,
  cboMainBranch: null,
  gridBranches: null,

  //   Account Types
  lblAccountTypes: null,
  chkRestrictAccountTypes: null,
  gridAccountTypes: null,

  //   Accounts
  lblAccountNextCodes: null,
  txtAccountNextId: null,
  txtAccountLoanNextId: null,
  txtAccountDepositNextId: null,
  
  lblAccountDates: null,
  dateAccountBegin: null,
  dateAccountEnd: null,
  
  lblTransactionDates: null,
  dateTransactionBegin: null,
  dateTransactionBeginDisbursements: null,
  dateTransactionEnd: null,

  //   Credit Reporting
  lblCCRExportSettings: null,
  cboCreditReportingExportType: null,
  txtCreditReportingExportFilename: null,
  chkCreditReportingTestMode: null,
  
  lblBatchTypes: null,
  chkCreditReportingAllowBatchTypeInitial: null,
  chkCreditReportingAllowBatchTypePeriodic: null,
  chkCreditReportingAllowBatchTypeCorrection: null,
  
  lblNotificationDetails: null,
  txtCreditReportingNotificationEmail: null,
  
  lblProviderDetails: null,
  txtCreditReportingProviderName: null,
  txtCreditReportingProviderReference: null,
  txtCreditReportingSignatoryId: null,
  cboCreditReportingIndustryType: null,
  chkCreditReportingIsLicensee: null,
  
  lblContactDetails: null,
  txtCreditReportingContactName: null,
  txtCreditReportingContactEmail: null,
  txtCreditReportingContactPhone: null,
  
  lblResponseOptions: null,
  cboCreditReportingResponseDetail: null,

  //   General Ledger
  lblGlExportOptions: null,
  txtGlSource: null,
  
  lblGlExportOptionsOverride: null,
  txtGlFileName: null,
  txtGlDatabaseName: null,
  cboGlExternalUserId: null,
  txtGlExternalUserPassword: null,
  txtGlExportTransactionNarrative: null,
  chkGlExportOverrideGlobalSettings: null,
  chkGlExportIncludeBranch: null,
  chkGlExportIncludeDepartment: null,
  
  lblGLMyobOAuthCredentials: null,
  chkGlMyobOverrideGlobalCredentials: null,
  txtGlMyobApiKey: null,
  txtGlMyobApiSecret: null,
  txtGlMyobOAuthData: null,
  
  lblGLXeroOAuthCredentials: null,
  chkGlXeroOverrideGlobalCredentials: null,
  txtGlXeroClientId: null,
  txtGlXeroClientSecret: null,
  txtGlXeroOAuthData: null,
  
  lblGlExportOptionsAPI: null,
  cboGlMyobCompanyFileId: null,
  cboGlXeroTenant: null,
  txtGlExportAccountStructure: null,
  divGlExportAccountStructure: null,
  txtGLXeroDefaultContactId: null,
  
  lblGlXeroTrackingCategoryA: null,
  cboGlXeroTrackingCategoryABasis: null,
  txtGlXeroTrackingCategoryAName: null,
  
  lblGlXeroTrackingCategoryB: null,
  cboGlXeroTrackingCategoryBBasis: null,
  txtGlXeroTrackingCategoryBName: null,
  
  lblGlVerification: null,
  divGlVerification: null,

  //   Document
  lblDocument: null,
  txtDocumentContent1: null,
  txtDocumentContent2: null,

  // Messaging
  lblEmailDisclaimer: null,
  txtEmailDisclaimer: null,

  //   User Defined
  phUserDefined: null,
}

// Form
var frmMain;
var tabDetails;

// Buttons
var cmdCancel;
var cmdFinish;

var cmdCompanyFileRefresh;
var cmdTenantRefresh;

// Other
var mShowGLTracking;
var mShowGLExportOverrideGlobalSettings;

// ==========
// Initialise
// ==========
$(function () {
  // --------
  // Controls
  // --------
  //   General
  C.lblCodeAndName = widget.UI.Label("lblCodeAndName", {});
  C.txtEntityId = widget.UI.TextBox("txtEntityId", {
    allowBlank: false,
    maxLength: 5,
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });
  C.chkActive = widget.UI.CheckBox("chkActive", {
    caption: "Active?",
  });
  C.txtName = widget.UI.TextBox("txtName", {
    allowBlank: false,
    maxLength: 50,
  });

  C.lblCompanyDetails = widget.UI.Label("lblCompanyDetails", {});
  C.txtBusinessNumber = widget.UI.TextBox("txtBusinessNumber", {
    maxLength: 20,
  });
  C.txtTaxNumber = widget.UI.TextBox("txtTaxNumber", {
    maxLength: 20,
  });
  C.txtGstNumber = widget.UI.TextBox("txtGstNumber", {
    maxLength: 20,
  });
  C.txtOrganisationNumber = widget.UI.TextBox("txtOrganisationNumber", {
    maxLength: 20,
  });
  
  C.lblCostCentre = widget.UI.Label("lblCostCentre", {});
  C.cboCostCentre = widget.UI.DBCombo("cboCostCentre", {
    limitToList: true,
  });
  
  C.lblLicence = widget.UI.Label("lblLicence", {});
  C.txtLicenceNumber = widget.UI.TextBox("txtLicenceNumber", {
    maxLength: 20,
  });
  C.txtLicenceName = widget.UI.TextBox("txtLicenceName", {
    maxLength: 100,
  });
  
  C.lblDisputeResolution = widget.UI.Label("lblDisputeResolution", {});
  C.cboDisputeResolutionClientId = widget.UI.DBCombo("cboDisputeResolutionClientId", {
    limitToList: true,
  });
  
  C.lblNotes = widget.UI.Label("lblNotes", {});
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
  });

  //   Calendar
  C.lblFinancialYear = widget.UI.Label("lblFinancialYear", {});
  C.cboFinancialYearStart = widget.UI.ComboBox("cboFinancialYearStart", {
    allowBlank: false,
    limitToList: true,
    listCsv: "January,February,March,April,May,June,July,August,September,October,November,December",
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.cboTaxYearStart = widget.UI.ComboBox("cboTaxYearStart", {
    allowBlank: false,
    limitToList: true,
    listCsv: "January,February,March,April,May,June,July,August,September,October,November,December",
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  
  C.lblCalendarBanking = widget.UI.Label("lblCalendarBanking", {
    tooltipText: "This calendar defines the days the Business can process Bank transactions.",
  });
  C.cboCalendarBanking = widget.UI.DBCombo("cboCalendarBanking", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });
  
  C.lblCalendarWorking = widget.UI.Label("lblCalendarWorking", {
    tooltipText: "This calendar defines the days the Business operates on.",
  });
  C.cboCalendarWorking = widget.UI.DBCombo("cboCalendarWorking", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });
  
  C.lblWithholdingTaxPeriod = widget.UI.Label("lblWithholdingTaxPeriod", {});
  C.cboWithholdingTaxPeriod = widget.UI.DateCycleComboBox("cboWithholdingTaxPeriod", {
    allowBlank: false,
  });
  
  C.lblAccountingPeriod = widget.UI.Label("lblAccountingPeriod", {});
  C.cboAccountingPeriod = widget.UI.DateCycleComboBox("cboAccountingPeriod", {
    allowBlank: false,
  });

  //   Options
  C.lblDefaultState = widget.UI.Label("lblDefaultState", {});
  C.cboDefaultState = widget.UI.ComboBox("cboDefaultState", {
    maxLength: 10,
  });
  
  C.lblSecuredPartyGroup = widget.UI.Label("lblSecuredPartyGroup", {
    tooltipText: "If left blank, the value defined under Global Settings will be used.",
  });
  C.cboSecuredPartyGroup = widget.UI.DBCombo("cboSecuredPartyGroup", {
    limitToList: true,
  });
  
  C.lblPayId = widget.UI.Label("lblPayId", {
    tooltipText: "The Payment Method to use when creating Zepto PayID payments. This can be overridden at the Branch level.",
  });
  C.cboPayIdPaymentMethod = widget.UI.DBCombo("cboPayIdPaymentMethod", {
    limitToList: true,
  });
  
  C.lblLogoFileName = widget.UI.Label("lblLogoFileName", {});
  C.txtLogoFileName = widget.UI.TextBox("txtLogoFileName", {});
  C.txtLogoFileName2 = widget.UI.TextBox("txtLogoFileName2", {});
  
  C.lblResources = widget.UI.Label("lblResources", {});
  C.cboLogoResource1 = widget.UI.DBCombo("cboLogoResource1", {
    limitToList: true,
  });
  C.cboOtherResource1 = widget.UI.DBCombo("cboOtherResource1", {
    limitToList: true,
  });

  //   Branches
  C.lblBranches = widget.UI.Label("lblBranches", {});
  C.cboMainBranch = widget.UI.DBCombo("cboMainBranch", {
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_5,
    
    onChange: cboMainBranch_Change,
  });

  //   Account Types
  C.lblAccountTypes = widget.UI.Label("lblAccountTypes", {});
  C.chkRestrictAccountTypes = widget.UI.CheckBox("chkRestrictAccountTypes", {
    caption: "Restrict Account Types for new Accounts?",
    captionWrap: true,
    
    onChange: chkRestrictAccountTypes_Change,
  });

  //   Accounts
  C.lblAccountNextCodes = widget.UI.Label("lblAccountNextCodes", {
    tooltipText: "The next Account code to use when generating an auto-sequence.\n\nIf no code is defined for each of the different types of Account, the 'General' sequence will be used.\n\nProduct and Account Types can override the Entity Next Codes.",
  });
  C.txtAccountNextId = widget.UI.TextBox("txtAccountNextId", {
    maxLength: 10,
  });
  C.txtAccountLoanNextId = widget.UI.TextBox("txtAccountLoanNextId", {
    maxLength: 10,
  });
  C.txtAccountDepositNextId = widget.UI.TextBox("txtAccountDepositNextId", {
    maxLength: 10,
  });
  
  C.lblAccountDates = widget.UI.Label("lblAccountDates", {
    tooltipText: "The 'Open' date of an Account must be on or after the 'Begin' date and on or before the 'End' date.",
  });
  C.dateAccountBegin = widget.UI.DateBox("dateAccountBegin", {
    allowBlank: false,
  });
  C.dateAccountEnd = widget.UI.DateBox("dateAccountEnd", {
    allowBlank: false,
  });
  
  C.lblTransactionDates = widget.UI.Label("lblTransactionDates", {});
  C.dateTransactionBegin = widget.UI.DateBox("dateTransactionBegin", {
    allowBlank: false,
  });
  C.dateTransactionBeginDisbursements = widget.UI.DateBox("dateTransactionBeginDisbursements", {
    allowBlank: false,
  });
  C.dateTransactionEnd = widget.UI.DateBox("dateTransactionEnd", {
    allowBlank: false,
  });

  //   Credit Reporting
  C.lblCCRExportSettings = widget.UI.Label("lblCCRExportSettings", {});
  C.cboCreditReportingExportType = widget.UI.ComboBox("cboCreditReportingExportType", {
    allowBlank: false,
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.txtCreditReportingExportFilename = widget.UI.TextBox("txtCreditReportingExportFilename", {
    maxLength: 255,
  });
  C.chkCreditReportingTestMode = widget.UI.CheckBox("chkCreditReportingTestMode", {
    caption: "Test Mode?",    
  });
  
  C.lblBatchTypes = widget.UI.Label("lblBatchTypes", {});
  C.chkCreditReportingAllowBatchTypeInitial = widget.UI.CheckBox("chkCreditReportingAllowBatchTypeInitial", {
    caption: "Initial?",
  });
  C.chkCreditReportingAllowBatchTypePeriodic = widget.UI.CheckBox("chkCreditReportingAllowBatchTypePeriodic", {
    caption: "Periodic?",
  });
  C.chkCreditReportingAllowBatchTypeCorrection = widget.UI.CheckBox("chkCreditReportingAllowBatchTypeCorrection", {
    caption: "Correction?",
  });
  
  C.lblNotificationDetails = widget.UI.Label("lblNotificationDetails", {});
  C.txtCreditReportingNotificationEmail = widget.UI.TextBox("txtCreditReportingNotificationEmail", {
    dataType: "email",
    maxLength: 60,
  });
  
  C.lblProviderDetails = widget.UI.Label("lblProviderDetails", {});
  C.txtCreditReportingProviderName = widget.UI.TextBox("txtCreditReportingProviderName", {
    maxLength: 50,
  });
  C.txtCreditReportingProviderReference = widget.UI.TextBox("txtCreditReportingProviderReference", {
    maxLength: 20,
  });
  C.txtCreditReportingSignatoryId = widget.UI.TextBox("txtCreditReportingSignatoryId", {
    maxLength: 12,
  });
  C.cboCreditReportingIndustryType = widget.UI.InformationListComboBox("cboCreditReportingIndustryType", {
    limitToList: true,
  });
  C.chkCreditReportingIsLicensee = widget.UI.CheckBox("chkCreditReportingIsLicensee", {
    caption: "Is Licensee?",
  });
  
  C.lblContactDetails = widget.UI.Label("lblContactDetails", {});
  C.txtCreditReportingContactName = widget.UI.TextBox("txtCreditReportingContactName", {
    maxLength: 40,
  });
  C.txtCreditReportingContactEmail = widget.UI.TextBox("txtCreditReportingContactEmail", {
    dataType: "email",
    maxLength: 60,
  });
  C.txtCreditReportingContactPhone = widget.UI.TextBox("txtCreditReportingContactPhone", {
    dataType: "phone",
    maxLength: 20,
  });
  
  C.lblResponseOptions = widget.UI.Label("lblResponseOptions", {});
  C.cboCreditReportingResponseDetail = widget.UI.ComboBox("cboCreditReportingResponseDetail", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  
  //   General Ledger
  C.lblGlExportOptions = widget.UI.Label("lblGlExportOptions", {});
  C.txtGlSource = widget.UI.TextBox("txtGlSource", {
    maxLength: 5,
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });
  
  C.lblGlExportOptionsOverride = widget.UI.Label("lblGlExportOptionsOverride", {});
  C.txtGlFileName = widget.UI.TextBox("txtGlFileName", {
    maxLength: 255,
  });
  C.txtGlDatabaseName = widget.UI.TextBox("txtGlDatabaseName", {
    maxLength: 255,
  });
  C.cboGlExternalUserId = widget.UI.ComboBox("cboGlExternalUserId", {
    maxLength: 60,
    listCsv: "[UserId]",
  });
  C.txtGlExternalUserPassword = widget.UI.TextBox("txtGlExternalUserPassword", {
    maxLength: 60,
    password: true,
    passwordRevealOnFocus: true,
  });
  C.txtGlExportTransactionNarrative = widget.UI.TextBox("txtGlExportTransactionNarrative", {
    maxLength: 60,
  });
  C.chkGlExportOverrideGlobalSettings = widget.UI.CheckBox("chkGlExportOverrideGlobalSettings", {
    caption: "Override Global Settings?",
    
    onChange: chkGlExportOverrideGlobalSettings_Change,
  });
  C.chkGlExportIncludeBranch = widget.UI.CheckBox("chkGlExportIncludeBranch", {
    caption: "Include Branch?",
  });
  C.chkGlExportIncludeDepartment = widget.UI.CheckBox("chkGlExportIncludeDepartment", {
    caption: "Include Department?",
  });
  
  C.lblGLMyobOAuthCredentials = widget.UI.Label("lblGLMyobOAuthCredentials", {});
  C.chkGlMyobOverrideGlobalCredentials = widget.UI.CheckBox("chkGlMyobOverrideGlobalCredentials", {
    caption: "Override Global Credentials?",
    
    onChange: chkGlMyobOverrideGlobalCredentials_Change,
  });
  C.txtGlMyobApiKey = widget.UI.TextBox("txtGlMyobApiKey", {
    maxLength: 100,
  });
  C.txtGlMyobApiSecret = widget.UI.TextBox("txtGlMyobApiSecret", {
    maxLength: 100,
  });
  C.txtGlMyobOAuthData = widget.UI.TextBox("txtGlMyobOAuthData", {});
  
  C.lblGLXeroOAuthCredentials = widget.UI.Label("lblGLXeroOAuthCredentials", {});
  C.chkGlXeroOverrideGlobalCredentials = widget.UI.CheckBox("chkGlXeroOverrideGlobalCredentials", {
    caption: "Override Global Credentials?",
    
    onChange: chkGlXeroOverrideGlobalCredentials_Change,
  });
  C.txtGlXeroClientId = widget.UI.TextBox("txtGlXeroClientId", {
    maxLength: 100,
  });
  C.txtGlXeroClientSecret = widget.UI.TextBox("txtGlXeroClientSecret", {
    maxLength: 100,
  });
  C.txtGlXeroOAuthData = widget.UI.TextBox("txtGlXeroOAuthData", {});
  
  C.lblGlExportOptionsAPI = widget.UI.Label("lblGlExportOptionsAPI", {
    tooltipText: "These options, if defined, override Global Settings.",
  });
  C.cboGlMyobCompanyFileId = widget.UI.DBCombo("cboGlMyobCompanyFileId", {
    maxLength: 100,
    width: "30em",
  });  
  C.cboGlXeroTenant = widget.UI.DBCombo("cboGlXeroTenant", {
    maxLength: 100,
    width: "30em",
  });
  C.txtGlExportAccountStructure = widget.UI.TextBox("txtGlExportAccountStructure", {
    maxLength: 60,    
  });
  C.divGlExportAccountStructure = $("#divGlExportAccountStructure");
  C.txtGLXeroDefaultContactId = widget.UI.TextBox("txtGLXeroDefaultContactId", {
    maxLength: 50,
  });
  
  C.lblGlXeroTrackingCategoryA = widget.UI.Label("lblGlXeroTrackingCategoryA", {});
  C.cboGlXeroTrackingCategoryABasis = widget.UI.ComboBox("cboGlXeroTrackingCategoryABasis", {
    allowBlank: false,
    limitToList: true,
    maxLength: 60,
    width: widget.UI.FIELD_WIDTH_CODE_15,
    
    onChange: cboGlXeroTrackingCategoryABasis_Change,
  });
  C.txtGlXeroTrackingCategoryAName = widget.UI.TextBox("txtGlXeroTrackingCategoryAName", {
    maxLength: 100,
  });
  
  C.lblGlXeroTrackingCategoryB = widget.UI.Label("lblGlXeroTrackingCategoryB", {});
  C.cboGlXeroTrackingCategoryBBasis = widget.UI.ComboBox("cboGlXeroTrackingCategoryBBasis", {
    allowBlank: false,
    limitToList: true,
    maxLength: 60,
    width: widget.UI.FIELD_WIDTH_CODE_15,
    
    onChange: cboGlXeroTrackingCategoryBBasis_Change,
  });
  C.txtGlXeroTrackingCategoryBName = widget.UI.TextBox("txtGlXeroTrackingCategoryBName", {
    maxLength: 100,
  });
  
  C.lblGlVerification = widget.UI.Label("lblGlVerification", {});
  C.divGlVerification = $("#divGlVerification");

  //   Document
  C.lblDocument = widget.UI.Label("lblDocument", {});
  C.txtDocumentContent1 = widget.UI.TextBox("txtDocumentContent1", {
    maxLength: 8192,
    multiLine: true,
  });
  C.txtDocumentContent2 = widget.UI.TextBox("txtDocumentContent2", {
    maxLength: 8192,
    multiLine: true,
  });

  //   Messaging
  C.lblEmailDisclaimer = widget.UI.Label("lblEmailDisclaimer", {
    tooltipText: "This will appear beneath the User Signature in emails and will replace the Disclaimer defined under Global Settings, Messaging, Email.\n\nSpecial tags can be inserted.",
  });
  C.txtEmailDisclaimer = widget.UI.TextBox("txtEmailDisclaimer", {
    maxLength: 8192,
    multiLine: true,    
    rows: 30,
  });

  var tagsList = [];
  tagsList.push({ caption: "Branch.BranchId", value: "[Branch.BranchId]" });
  tagsList.push({ caption: "Branch.Description", value: "[Branch.Description]" });
  tagsList.push({ caption: "Branch.Name", value: "[Branch.Name]" });
  tagsList.push({ caption: "Branch.Phone", value: "[Branch.Phone]" });
  tagsList.push({ caption: "Branch.Email", value: "[Branch.Email]" });
  tagsList.push({ caption: "Entity.EntityId", value: "[Entity.EntityId]" });
  tagsList.push({ caption: "Entity.Name", value: "[Entity.Name]" });
  tagsList.push({ caption: "User.UserId", value: "[User.UserId]" });
  tagsList.push({ caption: "User.Name", value: "[User.Name]" });
  tagsList.push({ caption: "User.JobTitle", value: "[User.JobTitle]" });
  tagsList.push({ caption: "User.Email", value: "[User.Email]" });
  tagsList.push({ caption: "User.Facsimile", value: "[User.Facsimile]" });
  tagsList.push({ caption: "User.Mobile", value: "[User.Mobile]" });
  tagsList.push({ caption: "User.Phone", value: "[User.Phone]" });
  C.txtEmailDisclaimer.TagsListDefine(tagsList);

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

  // Grids
  C.gridBranches = widget.UI.Grid("gridBranches", {
    allowGroupingsCollapse: true,
    docked: true,
    showRowSelectors: true,
    stickyHeader: true,

    onBeforeCellUpdate: gridBranches_BeforeCellUpdate,
    onInitialiseRow: gridBranches_InitialiseRow,
  });  

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

    onAction: gridAccountTypes_Action,
    onAfterRowActivate: gridAccountTypes_AfterRowActivate,
    onBeforeCellUpdate: gridAccountTypes_BeforeCellUpdate,
    onInitialiseRow: gridAccountTypes_InitialiseRow,
    onSelectedRowsChanged: gridAccountTypes_SelectedRowsChanged,
  }); 

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

  cmdCompanyFileRefresh = $("#cmdCompanyFileRefresh");
  cmdCompanyFileRefresh.click(function() { Form_ExecuteAction("RefreshCompanyFileList"); });

  cmdTenantRefresh = $("#cmdTenantRefresh");
  cmdTenantRefresh.click(function() { Form_ExecuteAction("RefreshTenantList"); });

  // 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.AllowPageCalendar) tabDetails.TabVisible("Calendar", false);
  if (!mRecord.AllowPageOptions) tabDetails.TabVisible("Options", false);
  if (!mRecord.AllowPageBranches) tabDetails.TabVisible("Branches", false);
  if (!mRecord.AllowPageAccountTypes) tabDetails.TabVisible("AccountTypes", false);
  if (!mRecord.AllowPageAccounts) tabDetails.TabVisible("Accounts", false);
  if (!mRecord.AllowPageCreditReporting) tabDetails.TabVisible("CreditReporting", false);
  if (!mRecord.AllowPageGeneralLedger) tabDetails.TabVisible("GeneralLedger", false);
  if (!mRecord.AllowPageDocument) tabDetails.TabVisible("Document", false);
  if (!mRecord.AllowPageMessaging) tabDetails.TabVisible("Messaging", false);
  if (!mRecord.AllowPageUserDefined) tabDetails.TabVisible("UserDefined", 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.txtEntityId.Text(mRecord.EntityId);
      C.chkActive.Value(mRecord.Active);
      C.txtName.Text(mRecord.Name);
      
      C.txtBusinessNumber.Text(mRecord.BusinessNumber);
      C.txtTaxNumber.Text(mRecord.TaxNumber);
      C.txtGstNumber.Text(mRecord.GstNumber);
      C.txtOrganisationNumber.Text(mRecord.OrganisationNumber);
      
      C.cboCostCentre.Text(mRecord.CostCentreId);
      
      C.txtLicenceNumber.Text(mRecord.LicenceNumber);
      C.txtLicenceName.Text(mRecord.LicenceName);
      
      C.cboDisputeResolutionClientId.Text(mRecord.DisputeResolutionClientId);
      
      C.txtNotes.Text(mRecord.Notes);
    }

    // Calendar
    if (mRecord.AllowPageCalendar) {
      C.cboFinancialYearStart.ListIndex(mRecord.FinancialYearStart - 1);
      C.cboTaxYearStart.ListIndex(mRecord.TaxYearStart - 1);
      
      C.cboCalendarBanking.Text(mRecord.CalendarBankingId);
      
      C.cboCalendarWorking.Text(mRecord.CalendarWorkingId);
      
      C.cboWithholdingTaxPeriod.Text(mRecord.WithholdingTaxPeriod);
      
      C.cboAccountingPeriod.Text(mRecord.AccountingPeriod);
    }

    // Options
    if (mRecord.AllowPageOptions) {
      C.cboDefaultState.Text(mRecord.DefaultState);
      
      C.cboSecuredPartyGroup.Text(mRecord.SecuredPartyGroupId);
      
      C.cboPayIdPaymentMethod.Text(mRecord.PayIdPaymentMethodId);
      
      C.txtLogoFileName.Text(mRecord.LogoFileName);
      C.txtLogoFileName2.Text(mRecord.LogoFileName2);
      
      C.cboLogoResource1.Text(mRecord.LogoResource1Id);
      C.cboOtherResource1.Text(mRecord.OtherResource1Id);
    }

    // Branches
    if (mRecord.AllowPageBranches) {
      C.cboMainBranch.Text(mRecord.MainBranchId);
    }

    // Account Types
    if (mRecord.AllowPageAccountTypes) {
      C.chkRestrictAccountTypes.Value(mRecord.RestrictAccountTypes);
    }

    // Accounts
    if (mRecord.AllowPageAccounts) {
      C.txtAccountNextId.Text(mRecord.AccountNextId);
      C.txtAccountLoanNextId.Text(mRecord.AccountLoanNextId);
      C.txtAccountDepositNextId.Text(mRecord.AccountDepositNextId);
      
      C.dateAccountBegin.Value(mRecord.DateAccountOpenBegin);
      C.dateAccountEnd.Value(mRecord.DateAccountOpenEnd);
      
      C.dateTransactionBegin.Value(mRecord.DateTransactionBegin);
      C.dateTransactionBeginDisbursements.Value(mRecord.DateTransactionBeginDisbursements);
      C.dateTransactionEnd.Value(mRecord.DateTransactionEnd);
    }

    // Credit Reporting
    if (mRecord.AllowPageCreditReporting) {      
      C.cboCreditReportingExportType.Text(mRecord.CreditReportingExportType);
      C.txtCreditReportingExportFilename.Text(mRecord.CreditReportingExportFilename);
      C.chkCreditReportingTestMode.Value(mRecord.CreditReportingTestMode);
      
      C.chkCreditReportingAllowBatchTypeInitial.Value(mRecord.CreditReportingAllowBatchTypeInitial);
      C.chkCreditReportingAllowBatchTypePeriodic.Value(mRecord.CreditReportingAllowBatchTypePeriodic);
      C.chkCreditReportingAllowBatchTypeCorrection.Value(mRecord.CreditReportingAllowBatchTypeCorrection);
      
      C.txtCreditReportingNotificationEmail.Text(mRecord.CreditReportingNotificationEmail);
      
      C.txtCreditReportingProviderName.Text(mRecord.CreditReportingProviderName);
      C.txtCreditReportingProviderReference.Text(mRecord.CreditReportingProviderReference);
      C.txtCreditReportingSignatoryId.Text(mRecord.CreditReportingSignatoryId);
      C.cboCreditReportingIndustryType.Text(mRecord.CreditReportingIndustryType);
      C.chkCreditReportingIsLicensee.Value(mRecord.CreditReportingIsLicensee);
      
      C.txtCreditReportingContactName.Text(mRecord.CreditReportingContactName);
      C.txtCreditReportingContactEmail.Text(mRecord.CreditReportingContactEmail);
      C.txtCreditReportingContactPhone.Text(mRecord.CreditReportingContactPhone);
      
      C.cboCreditReportingResponseDetail.Text(mRecord.CreditReportingResponseDetail);
    }

    // General Ledger
    if (mRecord.AllowPageGeneralLedger) {
      C.txtGlSource.Text(mRecord.GlSource);

      C.txtGlFileName.Text(mRecord.GlFileName);
      C.txtGlDatabaseName.Text(mRecord.GlDatabaseName);
      C.cboGlExternalUserId.Text(mRecord.GlExternalUserId);
      C.txtGlExternalUserPassword.Text(mRecord.GlExternalUserPassword);
      C.txtGlExportTransactionNarrative.Text(mRecord.GlExportTransactionNarrative);
      C.chkGlExportOverrideGlobalSettings.Value(mRecord.GlExportOverrideGlobalSettings);
      C.chkGlExportIncludeBranch.Value(mRecord.GlExportIncludeBranch);
      C.chkGlExportIncludeDepartment.Value(mRecord.GlExportIncludeDepartment);
      
      C.chkGlMyobOverrideGlobalCredentials.Value(mRecord.GlMyobOverrideGlobalCredentials);
      C.txtGlMyobApiKey.Text(mRecord.GlMyobApiKey);
      C.txtGlMyobApiSecret.Text(mRecord.GlMyobApiSecret);
      C.txtGlMyobOAuthData.Text(mRecord.GlMyobOAuthData);
      
      C.chkGlXeroOverrideGlobalCredentials.Value(mRecord.GlXeroOverrideGlobalCredentials);
      C.txtGlXeroClientId.Text(mRecord.GlXeroClientId);
      C.txtGlXeroClientSecret.Text(mRecord.GlXeroClientSecret);
      C.txtGlXeroOAuthData.Text(mRecord.GlXeroOAuthData);
      
      C.cboGlMyobCompanyFileId.Text(mRecord.GlMyobCompanyFileId);
      C.cboGlXeroTenant.Text(mRecord.GlXeroTenantId);
      C.txtGlExportAccountStructure.Text(mRecord.GlExportAccountStructure);
      C.txtGLXeroDefaultContactId.Text(mRecord.GlXeroDefaultContactId);
      
      C.cboGlXeroTrackingCategoryABasis.Text(mRecord.GlXeroTrackingCategoryABasis);
      C.txtGlXeroTrackingCategoryAName.Text(mRecord.GlXeroTrackingCategoryAName);
      
      C.cboGlXeroTrackingCategoryBBasis.Text(mRecord.GlXeroTrackingCategoryBBasis);
      C.txtGlXeroTrackingCategoryBName.Text(mRecord.GlXeroTrackingCategoryBName);
    }

    // Document
    if (mRecord.AllowPageDocument) {
      C.txtDocumentContent1.Text(mRecord.DocumentContent1);
      C.txtDocumentContent2.Text(mRecord.DocumentContent2);
    }

    // Messaging
    if (mRecord.AllowPageMessaging) {
      C.txtEmailDisclaimer.Text(mRecord.EmailDisclaimer);
    }

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

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

  // Update Controls

  // Update fields
  Fields_Update();

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

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // General
  if (mRecord.AllowPageGeneral) {
    mRecord.EntityId = C.txtEntityId.Text();
    mRecord.Active = C.chkActive.Value();
    mRecord.Name = C.txtName.Text();
    
    mRecord.BusinessNumber = C.txtBusinessNumber.Text();
    mRecord.TaxNumber = C.txtTaxNumber.Text();
    mRecord.GstNumber = C.txtGstNumber.Text();
    mRecord.OrganisationNumber = C.txtOrganisationNumber.Text();
    
    mRecord.CostCentreId = C.cboCostCentre.Text();
    
    mRecord.LicenceNumber = C.txtLicenceNumber.Text();
    mRecord.LicenceName = C.txtLicenceName.Text();
    
    mRecord.DisputeResolutionClientId = C.cboDisputeResolutionClientId.Text();
    
    mRecord.Notes = C.txtNotes.Text();
  }

  // Calendar
  if (mRecord.AllowPageCalendar) {
    mRecord.FinancialYearStart = C.cboFinancialYearStart.ListIndex() + 1;
    mRecord.TaxYearStart = C.cboTaxYearStart.ListIndex() + 1;
    
    mRecord.CalendarBankingId = C.cboCalendarBanking.Text();
    
    mRecord.CalendarWorkingId = C.cboCalendarWorking.Text();
    
    mRecord.WithholdingTaxPeriod = C.cboWithholdingTaxPeriod.Text();
    
    mRecord.AccountingPeriod = C.cboAccountingPeriod.Text();
  }

  // Options
  if (mRecord.AllowPageOptions) {
    mRecord.DefaultState = C.cboDefaultState.Text();
    
    mRecord.SecuredPartyGroupId = C.cboSecuredPartyGroup.Text();
    
    mRecord.PayIdPaymentMethodId = C.cboPayIdPaymentMethod.Text();
    
    mRecord.LogoFileName = C.txtLogoFileName.Text();
    mRecord.LogoFileName2 = C.txtLogoFileName2.Text();
    
    mRecord.LogoResource1Id = C.cboLogoResource1.Text();
    mRecord.OtherResource1Id = C.cboOtherResource1.Text();
  }

  // Branches
  if (mRecord.AllowPageBranches) {
    mRecord.MainBranchId = C.cboMainBranch.Text();
  }

  // Account Types
  if (mRecord.AllowPageAccountTypes) {
    mRecord.RestrictAccountTypes = C.chkRestrictAccountTypes.Value();
  }

  // Accounts
  if (mRecord.AllowPageAccounts) {
    mRecord.AccountNextId = C.txtAccountNextId.Text();
    mRecord.AccountLoanNextId = C.txtAccountLoanNextId.Text();
    mRecord.AccountDepositNextId = C.txtAccountDepositNextId.Text();
    
    mRecord.DateAccountOpenBegin = C.dateAccountBegin.Value();
    mRecord.DateAccountOpenEnd = C.dateAccountEnd.Value();
    
    mRecord.DateTransactionBegin = C.dateTransactionBegin.Value();
    mRecord.DateTransactionBeginDisbursements = C.dateTransactionBeginDisbursements.Value();
    mRecord.DateTransactionEnd = C.dateTransactionEnd.Value();
  }

  // Credit Reporting
  if (mRecord.AllowPageCreditReporting) {      
    mRecord.CreditReportingExportType = C.cboCreditReportingExportType.Text();
    mRecord.CreditReportingExportFilename = C.txtCreditReportingExportFilename.Text();
    mRecord.CreditReportingTestMode = C.chkCreditReportingTestMode.Value();
    
    mRecord.CreditReportingAllowBatchTypeInitial = C.chkCreditReportingAllowBatchTypeInitial.Value();
    mRecord.CreditReportingAllowBatchTypePeriodic = C.chkCreditReportingAllowBatchTypePeriodic.Value();
    mRecord.CreditReportingAllowBatchTypeCorrection = C.chkCreditReportingAllowBatchTypeCorrection.Value();
    
    mRecord.CreditReportingNotificationEmail = C.txtCreditReportingNotificationEmail.Text();
    
    mRecord.CreditReportingProviderName = C.txtCreditReportingProviderName.Text();
    mRecord.CreditReportingProviderReference = C.txtCreditReportingProviderReference.Text();
    mRecord.CreditReportingSignatoryId = C.txtCreditReportingSignatoryId.Text();
    mRecord.CreditReportingIndustryType = C.cboCreditReportingIndustryType.Text();
    mRecord.CreditReportingIsLicensee = C.chkCreditReportingIsLicensee.Value();
    
    mRecord.CreditReportingContactName = C.txtCreditReportingContactName.Text();
    mRecord.CreditReportingContactEmail = C.txtCreditReportingContactEmail.Text();
    mRecord.CreditReportingContactPhone = C.txtCreditReportingContactPhone.Text();
    
    mRecord.CreditReportingResponseDetail = C.cboCreditReportingResponseDetail.Text();
  }

  // General Ledger
  if (mRecord.AllowPageGeneralLedger) {
    mRecord.GlSource = C.txtGlSource.Text();

    mRecord.GlFileName = C.txtGlFileName.Text();
    mRecord.GlDatabaseName = C.txtGlDatabaseName.Text();
    mRecord.GlExternalUserId = C.cboGlExternalUserId.Text();
    mRecord.GlExternalUserPassword = C.txtGlExternalUserPassword.Text();
    mRecord.GlExportTransactionNarrative = C.txtGlExportTransactionNarrative.Text();
    mRecord.GlExportOverrideGlobalSettings = C.chkGlExportOverrideGlobalSettings.Value();
    mRecord.GlExportIncludeBranch = C.chkGlExportIncludeBranch.Value();
    mRecord.GlExportIncludeDepartment = C.chkGlExportIncludeDepartment.Value();
    
    mRecord.GlMyobOverrideGlobalCredentials = C.chkGlMyobOverrideGlobalCredentials.Value();
    mRecord.GlMyobApiKey = C.txtGlMyobApiKey.Text();
    mRecord.GlMyobApiSecret = C.txtGlMyobApiSecret.Text();
    mRecord.GlMyobOAuthData = C.txtGlMyobOAuthData.Text();
    
    mRecord.GlXeroOverrideGlobalCredentials = C.chkGlXeroOverrideGlobalCredentials.Value();
    mRecord.GlXeroClientId = C.txtGlXeroClientId.Text();
    mRecord.GlXeroClientSecret = C.txtGlXeroClientSecret.Text();
    mRecord.GlXeroOAuthData = C.txtGlXeroOAuthData.Text();
    
    mRecord.GlMyobCompanyFileId = C.cboGlMyobCompanyFileId.Text();
    mRecord.GlXeroTenantId = C.cboGlXeroTenant.Text();
    mRecord.GlExportAccountStructure = C.txtGlExportAccountStructure.Text();
    mRecord.GlXeroDefaultContactId = C.txtGLXeroDefaultContactId.Text();
    
    mRecord.GlXeroTrackingCategoryABasis = C.cboGlXeroTrackingCategoryABasis.Text();
    mRecord.GlXeroTrackingCategoryAName = C.txtGlXeroTrackingCategoryAName.Text();
    
    mRecord.GlXeroTrackingCategoryBBasis = C.cboGlXeroTrackingCategoryBBasis.Text();
    mRecord.GlXeroTrackingCategoryBName = C.txtGlXeroTrackingCategoryBName.Text();
  }

  // Document
  if (mRecord.AllowPageDocument) {
    mRecord.DocumentContent1 = C.txtDocumentContent1.Text();
    mRecord.DocumentContent2 = C.txtDocumentContent2.Text();
  }

  // Messaging
  if (mRecord.AllowPageMessaging) {
    mRecord.EmailDisclaimer = C.txtEmailDisclaimer.Text();
  }

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

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    if (mRecord.EntityId) {
      widget.SetHeading("Entity (" + mRecord.EntityId + ")");
    }
    else {
      widget.SetHeading("New Entity");    
      C.divGlVerification.html("These details can be verified by clicking the 'Verify' button on the read-only version of this Entity once saved");  
    }
  }

  // Lists
  if (mRecord) {
    // General
    C.cboCostCentre.RefreshFromStandardRange("CostCentres", "", false, mRecord.CostCentreId);
    C.cboDisputeResolutionClientId.RefreshFromStandardRange("Clients", "", false, mRecord.DisputeResolutionClientId);
    
    C.cboCalendarBanking.RefreshFromStandardRange("Calendars", "", false, mRecord.CalendarBankingId);
    C.cboCalendarWorking.RefreshFromStandardRange("Calendars", "", false, mRecord.CalendarWorkingId);
    C.cboWithholdingTaxPeriod.ListFromCsvString("1 Month,6 Months");
    C.cboAccountingPeriod.ListFromCsvString("1 Month,2 Months,3 Months,4 Months,6 Months,12 Months");
    
    // Options
    C.cboDefaultState.ListFromCsvString(mRecord.AddressStatesList);
    
    C.cboSecuredPartyGroup.RefreshFromStandardRange("SecuredPartyGroups", "", false, mRecord.SecuredPartyGroupId);
    
    C.cboPayIdPaymentMethod.RefreshFromStandardRange("PaymentMethods", mRecord.PayIdSqlWhere, false, mRecord.PayIdPaymentMethodId);
    
    C.cboLogoResource1.RefreshFromStandardRange("Resources", mRecord.ResourceImageSqlWhere, false, mRecord.LogoResource1Id);
    C.cboOtherResource1.RefreshFromStandardRange("Resources", "", false, mRecord.OtherResource1Id);
    
    // Branches
    C.cboMainBranch.RefreshFromStandardRange("Branches", mRecord.BranchesSqlWhere, false, mRecord.MainBranchId);      
    
    // Credit Reporting
    C.cboCreditReportingExportType.ListFromCodeDescriptionList(mRecord.CreditReportingExportTypeList);
    C.cboCreditReportingIndustryType.SetComboFromInformationList("CreditReportIndustryTypes");    
    C.cboCreditReportingResponseDetail.ListFromCsvString(mRecord.CreditReportingResponseOptionList);
    
    // General Ledger
    if (mRecord.GlAllowUserToModifySettings) {
      C.lblGlExportOptionsOverride.TooltipText("These options, if defined, override Global Settings - but may be amended by the User when exporting to General Ledger.");
    }
    else {
      C.lblGlExportOptionsOverride.TooltipText("These options, if defined, override Global Settings.");
    }
    C.cboGlXeroTrackingCategoryABasis.ListFromCodeDescriptionList(mRecord.XeroTrackingCategoryBasisList);
    C.cboGlXeroTrackingCategoryBBasis.ListFromCodeDescriptionList(mRecord.XeroTrackingCategoryBasisList);
  }

  // Controls
  if (mRecord) {
    // General
    if (mRecord.Terminology_BusinessNumber) {
      C.txtBusinessNumber.Caption(mRecord.Terminology_BusinessNumber + ":");
    }
    else {
      C.txtBusinessNumber.VisibleRow(false);
    }    
    
    if (mRecord.Terminology_TaxNumber) {
      C.txtTaxNumber.Caption(mRecord.Terminology_TaxNumber + ":");
    }
    else {
      C.txtTaxNumber.VisibleRow(false);
    }
    
    if (mRecord.Terminology_GstNumber) {
      C.txtGstNumber.Caption(mRecord.Terminology_GstNumber + ":");
    }
    else {
      C.txtGstNumber.VisibleRow(false);
    }
    
    if (mRecord.Terminology_CompanyNumber) {
      C.txtOrganisationNumber.Caption(mRecord.Terminology_CompanyNumber + ":");
    }
    else {
      C.txtOrganisationNumber.VisibleRow(false);
    }
    
    if (mRecord.Terminology_LicenceNumber) {
      C.lblLicence.Text(mRecord.Terminology_LicenceNumber + " details");
    }
    else {
      C.lblLicence.VisibleRow(false);
      C.txtLicenceNumber.VisibleRow(false);
      C.txtLicenceName.VisibleRow(false);
    }
    
    if (mRecord.Terminology_DisputeResolutionScheme) {
      C.lblDisputeResolution.Text(mRecord.Terminology_DisputeResolutionScheme + " details");
    }
    else {
      C.lblDisputeResolution.VisibleRow(false);
      C.cboDisputeResolutionClientId.VisibleRow(false);
    }
    
    // Calendar
    if (!mRecord.UseAccountingPeriods) {
      C.lblAccountingPeriod.VisibleRow(false);
      C.cboAccountingPeriod.VisibleRow(false);
    }
    
    // Options
    if (!mRecord.ShowDefaultState) {
      C.lblDefaultState.VisibleRow(false);
      C.cboDefaultState.VisibleRow(false);
    }
    
    C.cboSecuredPartyGroup.BlankTip(mRecord.SecurityStmtDefaultSecuredPartyGroupId);
    if (!mRecord.AddonsSecurityRegister) {
      C.lblSecuredPartyGroup.VisibleRow(false);
      C.cboSecuredPartyGroup.VisibleRow(false);
    }
    
    if (!mRecord.AddonsBankingAdvanced_Split) {
      C.lblPayId.VisibleRow(false);
      C.cboPayIdPaymentMethod.VisibleRow(false);
    }
    
    // Accounts
    if (!mRecord.AddonsLoansAny) {
      C.txtAccountLoanNextId.VisibleRow(false);
    }
    
    if (!mRecord.AddonsDepositAccount) {
      C.txtAccountDepositNextId.VisibleRow(false);
    }
    
    var disbursementTooltip = "Transactions must be dated on or after the 'Begin' date and on or before the 'End' date.";
    if (mRecord.AddonsDisbursements) {
      disbursementTooltip += "\n\nDisbursements: The begin date for Disbursement and Commission transactions.";
    }
    else {
      C.dateTransactionBeginDisbursements.VisibleRow(false);
    }
    C.lblTransactionDates.TooltipText(disbursementTooltip);
    
    C.dateAccountBegin.MinValue(mRecord.DateBoxMinValue);
    C.dateAccountBegin.MaxValue(mRecord.DateBoxMaxValue);
    C.dateAccountEnd.MinValue(mRecord.DateBoxMinValue);
    C.dateAccountEnd.MaxValue(mRecord.DateBoxMaxValue);    
    C.dateTransactionBegin.MinValue(mRecord.DateBoxMinValue);
    C.dateTransactionBegin.MaxValue(mRecord.DateBoxMaxValue);
    C.dateTransactionBeginDisbursements.MinValue(mRecord.DateBoxMinValue);
    C.dateTransactionBeginDisbursements.MaxValue(mRecord.DateBoxMaxValue);
    C.dateTransactionEnd.MinValue(mRecord.DateBoxMinValue);
    C.dateTransactionEnd.MaxValue(mRecord.DateBoxMaxValue);
  }

  // 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();
    pageBranches_Refresh();
    pageAccountTypes_Refresh();
    pageCreditReporting_Refresh();
    pageGeneralLedger_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();

    console.log(mOriginalJson);
    console.log(JSON.stringify(mRecord));

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

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

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

// ==========
// Resize Tab
// ==========
function tabDetails_Resize() {
  switch (tabDetails.SelectedTabId()) {
    case "General":
      // General
      C.txtNotes.ResizeFromParent();
      break;
      
    case "GeneralLedger":
      // General Ledger
      C.cboGlMyobCompanyFileId.WidthResizeFromParent();
      C.cboGlXeroTenant.WidthResizeFromParent();
      break;
      
    case "Document":
      // Document
      C.txtDocumentContent1.ResizeFromParent();
      C.txtDocumentContent2.ResizeFromParent();
      break;    
  }
}

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

    case "Branches":
      pageBranches_Refresh();
      break;

    case "AccountTypes":
      pageAccountTypes_Refresh();
      break;

    case "CreditReporting":
      pageCreditReporting_Refresh();
      break;

    case "GeneralLedger":
      pageGeneralLedger_Refresh();
      break;

    case "UserDefined":
      pageUserDefined_Refresh();
      break;

    default:
      break;
  }

  // Resize
  tabDetails_Resize();

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

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId, data) {
  switch(actionId) {
    case "RefreshCompanyFileList":
      // Refresh Company File List Action
      Form_ExecuteAction_RefreshCompanyFileList();
      break;
  
    case "RefreshTenantList":
      // Refresh Tenant List
      Form_ExecuteAction_RefreshTenantList();
      break;
  
    default:
      window.alert("Unhandled action '" + actionId + "'");
  }
}

// ================================
// Refresh Company File List Action
// ================================
function Form_ExecuteAction_RefreshCompanyFileList() {
  // Block UI
  widget.UI.Block("Initialising, please wait...");
  
  // Get List
  widget.GetString("RefreshCompanyFileList", {}, Form_ExecuteAction_RefreshCompanyFileList_Done, function(errorMessage) {
    // Unblock UI
    widget.UI.Unblock();
    
    // Error Message
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

function Form_ExecuteAction_RefreshCompanyFileList_Done(data) {
  // Parse
  if (data) data = JSON.parse(data);
  
  // Update List
  C.cboGlMyobCompanyFileId.RefreshFromCodeDescriptionList(data, "Id", "Name");

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

// ================================
// Refresh Company File List Action
// ================================
function Form_ExecuteAction_RefreshTenantList() {
  // Block UI
  widget.UI.Block("Initialising, please wait...");
  
  // Get List
  widget.GetString("RefreshTenantList", {}, Form_ExecuteAction_RefreshTenantList_Done, function(errorMessage) {
    // Unblock UI
    widget.UI.Unblock();
    
    // Error Message
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

function Form_ExecuteAction_RefreshTenantList_Done(data) {
  // Parse
  if (data) data = JSON.parse(data);
  
  // Update List
  C.cboGlXeroTenant.RefreshFromCodeDescriptionList(data, "Id", "Name");

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

// =============
// 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.EntityBranches = 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.txtEntityId.Text());
    },

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

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

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

  // Controls
}

// ============
// pageBranches
// ============
function pageBranches_Refresh() {
  if (!mRecord) return;

  // Grids
  gridBranches_Refresh();
}

// ================
// pageAccountTypes
// ================
function pageAccountTypes_Refresh() {
  if (!mRecord) return;

  // Grids
  gridAccountTypes_Refresh();
  
  // Update Controls
  chkRestrictAccountTypes_Change();
}

// ===============
// pageUserDefined
// ===============
function pageUserDefined_Refresh() {
  if (!mRecord) return;

  // Controls
}

// ===================
// pageCreditReporting
// ===================
function pageCreditReporting_Refresh() {
  if (!mRecord) return;
  
  // Re-validate controls
  C.txtCreditReportingNotificationEmail.DataTypeValidate(C.txtCreditReportingNotificationEmail.DataTypeReformat());
  C.txtCreditReportingContactEmail.DataTypeValidate(C.txtCreditReportingContactEmail.DataTypeReformat());
  C.txtCreditReportingContactPhone.DataTypeValidate(C.txtCreditReportingContactPhone.DataTypeReformat());
}

// =================
// pageGeneralLedger
// =================
function pageGeneralLedger_Refresh() {
  if (!mRecord) return;
  if (!mRecord.AllowPageGeneralLedger) return;
  
  // Assume GL Tracking is displayed
  mShowGLTracking = true;
  mShowGLExportOverrideGlobalSettings = true;
  
  // Hide Controls (this is controlled in Global Settings, so does not need to be dynamic)
  switch (mRecord.GlExportType) {
    case "MyobApi":
      C.lblGlExportOptions.VisibleRow(false);
      C.txtGlSource.VisibleRow(false);
      C.txtGlFileName.VisibleRow(false);
      C.txtGlDatabaseName.VisibleRow(false);
      C.cboGlExternalUserId.VisibleRow(false);
      C.txtGlExternalUserPassword.VisibleRow(false);
      C.txtGlExportTransactionNarrative.VisibleRow(false);
      
      C.lblGlExportOptionsOverride.VisibleRow(false);
      mShowGLExportOverrideGlobalSettings = false;
      C.chkGlExportOverrideGlobalSettings.VisibleRow(false);
      C.chkGlExportIncludeBranch.VisibleRow(false);
      C.chkGlExportIncludeDepartment.VisibleRow(false);

      C.lblGLXeroOAuthCredentials.VisibleRow(false);
      C.chkGlXeroOverrideGlobalCredentials.VisibleRow(false);
      C.txtGlXeroClientId.VisibleRow(false);
      C.txtGlXeroClientSecret.VisibleRow(false);
      C.txtGlXeroOAuthData.VisibleRow(false);
      C.cboGlXeroTenant.VisibleRow(false);
      cmdTenantRefresh.hide();
      C.txtGlExportAccountStructure.VisibleRow(false);
      C.divGlExportAccountStructure.hide();
      C.txtGLXeroDefaultContactId.VisibleRow(false);
      
      mShowGLTracking = false;
      C.lblGlXeroTrackingCategoryA.VisibleRow(false);
      C.txtGlXeroTrackingCategoryAName.VisibleRow(false);
      C.cboGlXeroTrackingCategoryABasis.VisibleRow(false);
      
      C.lblGlXeroTrackingCategoryB.VisibleRow(false);
      C.txtGlXeroTrackingCategoryBName.VisibleRow(false);
      C.cboGlXeroTrackingCategoryBBasis.VisibleRow(false);
      
      // Blank Tips
      C.cboGlMyobCompanyFileId.BlankTip(mRecord.GlMyobCompanyFileIdBlankTip);
      C.txtGlExportAccountStructure.BlankTip(mRecord.GlExportAccountStructureBlankTip);
      break;  
      
    case "Xero":
      C.lblGlExportOptions.VisibleRow(false);
      C.txtGlSource.VisibleRow(false);
      C.txtGlFileName.VisibleRow(false);
      C.txtGlDatabaseName.VisibleRow(false);
      C.cboGlExternalUserId.VisibleRow(false);
      C.txtGlExternalUserPassword.VisibleRow(false);
      C.txtGlExportTransactionNarrative.VisibleRow(false);
      
      C.lblGlExportOptionsOverride.VisibleRow(false);
      mShowGLExportOverrideGlobalSettings = false;
      C.chkGlExportOverrideGlobalSettings.VisibleRow(false);
      C.chkGlExportIncludeBranch.VisibleRow(false);
      C.chkGlExportIncludeDepartment.VisibleRow(false);

      C.lblGLMyobOAuthCredentials.VisibleRow(false);
      C.chkGlMyobOverrideGlobalCredentials.VisibleRow(false);
      C.txtGlMyobApiKey.VisibleRow(false);
      C.txtGlMyobApiSecret.VisibleRow(false);
      C.txtGlMyobOAuthData.VisibleRow(false);
      C.cboGlMyobCompanyFileId.VisibleRow(false);
      cmdCompanyFileRefresh.hide();
      
      // Blank Tips
      C.cboGlXeroTenant.BlankTip(mRecord.XeroTenantBlankTip);
      C.txtGlExportAccountStructure.BlankTip(mRecord.GlExportAccountStructureBlankTip);
      C.txtGLXeroDefaultContactId.BlankTip(mRecord.XeroDefaultContactIdBlankTip);
      C.txtGlXeroTrackingCategoryAName.BlankTip(mRecord.XeroTrackingCategoryANameBlankTip);
      C.cboGlXeroTrackingCategoryABasis.BlankTip(mRecord.XeroTrackingCategoryABasisBlankTip);
      C.txtGlXeroTrackingCategoryBName.BlankTip(mRecord.XeroTrackingCategoryBNameBlankTip);
      C.cboGlXeroTrackingCategoryBBasis.BlankTip(mRecord.XeroTrackingCategoryBBasisBlankTip);
      break;
      
    default:
      // Other
      C.lblGLMyobOAuthCredentials.VisibleRow(false);
      C.chkGlMyobOverrideGlobalCredentials.VisibleRow(false);
      C.txtGlMyobApiKey.VisibleRow(false);
      C.txtGlMyobApiSecret.VisibleRow(false);
      C.txtGlMyobOAuthData.VisibleRow(false);
      C.cboGlMyobCompanyFileId.VisibleRow(false);
      cmdCompanyFileRefresh.hide();

      C.lblGLXeroOAuthCredentials.VisibleRow(false);
      C.chkGlXeroOverrideGlobalCredentials.VisibleRow(false);
      C.txtGlXeroClientId.VisibleRow(false);
      C.txtGlXeroClientSecret.VisibleRow(false);
      C.txtGlXeroOAuthData.VisibleRow(false);
      
      C.lblGlExportOptionsAPI.VisibleRow(false);
      C.cboGlXeroTenant.VisibleRow(false);
      cmdTenantRefresh.hide();
      C.txtGlExportAccountStructure.VisibleRow(false);
      C.divGlExportAccountStructure.hide();
      C.txtGLXeroDefaultContactId.VisibleRow(false);
      
      mShowGLTracking = false;
      C.lblGlXeroTrackingCategoryA.VisibleRow(false);
      C.txtGlXeroTrackingCategoryAName.VisibleRow(false);
      C.cboGlXeroTrackingCategoryABasis.VisibleRow(false);
      
      C.lblGlXeroTrackingCategoryB.VisibleRow(false);
      C.txtGlXeroTrackingCategoryBName.VisibleRow(false);
      C.cboGlXeroTrackingCategoryBBasis.VisibleRow(false);
      
      C.lblGlVerification.VisibleRow(false);
      C.divGlVerification.hide();
      break;
  }
  
  // Update Controls
  chkGlExportOverrideGlobalSettings_Change();
  chkGlMyobOverrideGlobalCredentials_Change();
  chkGlXeroOverrideGlobalCredentials_Change();
  cboGlXeroTrackingCategoryABasis_Change();
  cboGlXeroTrackingCategoryBBasis_Change();
}

// =============
// cboMainBranch
// =============
function cboMainBranch_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Refresh Grid
  C.gridBranches.VirtualDataRefresh(mRecord.EntityBranches, true);
}

// =======================
// chkRestrictAccountTypes
// =======================
function chkRestrictAccountTypes_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  C.gridAccountTypes.Visible(C.chkRestrictAccountTypes.Value());
}

// =================================
// chkGlExportOverrideGlobalSettings
// =================================
function chkGlExportOverrideGlobalSettings_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  C.chkGlExportIncludeBranch.VisibleRow(mShowGLExportOverrideGlobalSettings &amp;&amp; C.chkGlExportOverrideGlobalSettings.Value());
  C.chkGlExportIncludeDepartment.VisibleRow(mShowGLExportOverrideGlobalSettings &amp;&amp; C.chkGlExportOverrideGlobalSettings.Value());
}

// =================================
// chkGlMyobOverrideGlobalCredentials
// ==================================
function chkGlMyobOverrideGlobalCredentials_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  C.txtGlMyobApiKey.ReadOnly(!C.chkGlMyobOverrideGlobalCredentials.Value());
  C.txtGlMyobApiSecret.ReadOnly(!C.chkGlMyobOverrideGlobalCredentials.Value());
  C.txtGlMyobOAuthData.ReadOnly(!C.chkGlMyobOverrideGlobalCredentials.Value());
}

// ==================================
// chkGlXeroOverrideGlobalCredentials
// ==================================
function chkGlXeroOverrideGlobalCredentials_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  C.txtGlXeroClientId.ReadOnly(!C.chkGlXeroOverrideGlobalCredentials.Value());
  C.txtGlXeroClientSecret.ReadOnly(!C.chkGlXeroOverrideGlobalCredentials.Value());
  C.txtGlXeroOAuthData.ReadOnly(!C.chkGlXeroOverrideGlobalCredentials.Value());
}

// ===============================
// cboGlXeroTrackingCategoryABasis
// ===============================
function cboGlXeroTrackingCategoryABasis_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  if (mShowGLTracking &amp;&amp; C.cboGlXeroTrackingCategoryABasis.Text()) {
    // Default
    C.txtGlXeroTrackingCategoryAName.VisibleRow(true);
  
    // Update
    for (var i = 0; i &lt; mRecord.XeroTrackingCategoryBasisList.length; i++) {
      var item = mRecord.XeroTrackingCategoryBasisList[i];
      
      if (item.Description == C.cboGlXeroTrackingCategoryABasis.Text()) {
        switch (item.Code) {
          case "Global":
          case "None":
            C.txtGlXeroTrackingCategoryAName.VisibleRow(false);
            break;
        }
      }
    }
  }
  else {
    C.txtGlXeroTrackingCategoryAName.VisibleRow(false);
  }  
}

// ===============================
// cboGlXeroTrackingCategoryBBasis
// ===============================
function cboGlXeroTrackingCategoryBBasis_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  if (mShowGLTracking &amp;&amp; C.cboGlXeroTrackingCategoryBBasis.Text()) {
    // Default
    C.txtGlXeroTrackingCategoryBName.VisibleRow(true);
  
    // Update
    for (var i = 0; i &lt; mRecord.XeroTrackingCategoryBasisList.length; i++) {
      var item = mRecord.XeroTrackingCategoryBasisList[i];
      
      if (item.Description == C.cboGlXeroTrackingCategoryBBasis.Text()) {
        switch (item.Code) {
          case "Global":
          case "None":
            C.txtGlXeroTrackingCategoryBName.VisibleRow(false);
            break;
        }
      }
    }
  }
  else {
    C.txtGlXeroTrackingCategoryBName.VisibleRow(false);
  } 
}

// ============
// gridBranches
// ============
function gridBranches_Refresh() {
  // Add Columns
  C.gridBranches.ClearColumns();
  C.gridBranches.AddColumnBoolean("Main", { caption: "Main", allowEdit: !mRecord.ReadOnly });
  C.gridBranches.AddColumnBoolean("Active", { caption: "Active" });
  C.gridBranches.AddColumnCode("BranchId", { caption: "Branch", width: "10em" });
  C.gridBranches.AddColumnString("Name", { caption: "Name" });
  C.gridBranches.AddColumnString("Description", { caption: "Description" });

  // Refresh
  C.gridBranches.VirtualDataRefresh(mRecord.EntityBranches);

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

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

function gridBranches_BeforeCellUpdate(e) {
  var item = mRecord.EntityBranches[e.row.listIndex];
  
  switch(e.columnKey) {      
    case "Main":
      if (item.BranchId == C.cboMainBranch.Text()) {
        C.cboMainBranch.Text("");     
      }
      else {
        C.cboMainBranch.Text(item.BranchId);
      }       
      cboMainBranch_Change();
      break;
  }
}

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

    // Actions
  if (!mRecord.ReadOnly) {
    C.gridAccountTypes.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: "SelectChecked", tooltipText:"Select all rows that are checked", icon: "Select_Checked" },
                                         { actionId: "SelectUnchecked", tooltipText:"Select all rows that are not checked", icon: "Select_Unchecked" },
                                         { 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.gridAccountTypes.VirtualDataRefresh(mRecord.EntityAccountTypes);

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

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

      for(var i = 0; i &lt; mRecord.EntityAccountTypes.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.gridAccountTypes.SetSelectedRowIndexes(indexes, true);
      break;

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

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

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

    case "SELECTCHECKED":
    case "SELECTUNCHECKED":
      var indexes = [];
      
      for (var i = 0; i &lt; mRecord.EntityAccountTypes.length; i++) {
        var item = mRecord.EntityAccountTypes[i];
        
        if ((item.Available &amp;&amp; actionId.toUpperCase() == "SELECTCHECKED") || (!item.Available &amp;&amp; actionId.toUpperCase() == "SELECTUNCHECKED")) {
          indexes.push(i);
        }
      }
      C.gridAccountTypes.SetSelectedRowIndexes(indexes, true);
      break;

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

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

function gridAccountTypes_AfterRowActivate(e) {
  // Refresh Buttons
  gridAccountTypes_RefreshButtons();
}

function gridAccountTypes_SelectedRowsChanged(e) {
  // Refresh Buttons
  gridAccountTypes_RefreshButtons();
}

function gridAccountTypes_RefreshButtons() {
  var rows = C.gridAccountTypes.GetSelectedRowIndexes(true, true);

  if (rows.length == 0) {
    C.gridAccountTypes.Actions().SetEnabled("SelectUp", false);
    C.gridAccountTypes.Actions().SetEnabled("SelectDown", false);
    C.gridAccountTypes.Actions().SetEnabled("SelectGroup", false);
    C.gridAccountTypes.Actions().SetEnabled("Check", false);
    C.gridAccountTypes.Actions().SetEnabled("Uncheck", false);
  }
  else {
    C.gridAccountTypes.Actions().SetEnabled("SelectUp", C.gridAccountTypes.ActiveDataRowListIndex() != -1);
    C.gridAccountTypes.Actions().SetEnabled("SelectDown", C.gridAccountTypes.ActiveDataRowListIndex() != -1);
    C.gridAccountTypes.Actions().SetEnabled("SelectGroup", C.gridAccountTypes.ActiveDataRowListIndex() != -1);
    C.gridAccountTypes.Actions().SetEnabled("Check", true);
    C.gridAccountTypes.Actions().SetEnabled("Uncheck", true);
  }

  C.gridAccountTypes.RefreshButtons();
}

function gridAccountTypes_InitialiseRow(e) {
  var item = mRecord.EntityAccountTypes[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.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.EntityAccountTypes[e.row.listIndex];
  
  switch(e.columnKey) {      
    case "Available":
      item.Available = e.newValue;
      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>wTAyxOcWk0izLN86NxXONg</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Entity</Caption>
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <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>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon>Entity</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="EntityId" 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>Entities</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.Entities</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,Calendar,Options,Branches,AccountTypes,Accounts,CreditReporting,GeneralLedger,Document,Messaging,UserDefined</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>