<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2022-05-11T23:22:26.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2022-03-01T02:20:30.7070000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2022-05-11T23:21:32.7100000</UpdatedUtcDate>
    <ScriptId>AAL</ScriptId>
    <Description>Account Accounting Ledger</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Category />
    <Code>' HtmlWidget_AccountAccountingLedger
Option Explicit On
Option Strict On

' #################################################################
' Account Accounting Ledger wizard HTML Widget
'
' Version: 2.00 (12/05/2022)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.08  23/04/2021  ISS                Updated
'    2.00  04/05/2022  ISS      J028341   Re-write to better match existing HTML Widgets
'          12/05/2022  ISS      J028734   Updated Frequency control
' #################################################################

' Constants
' If updating, also check handled values in GetResolvedFrequency()
Private Const FREQUENCY_LIST As String = "Weekly,Fortnightly,Monthly,End of Month,Quarterly,6 Monthly,Yearly"

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

' Standard Parameters
Private mAccountId As String
Private mAccountingLedgerPk As Integer
Private mReadOnly As Boolean

' Other
Private mAccount As finAccount

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

  ' Assume Success
  Main = True

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

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

  ' Get Standard Parameters
  With mCombinedParameters
    mAccountId = .GetString("AccountId")
    mAccountingLedgerPk = .GetInteger("AccountingLedgerPk")
    mReadOnly = .GetBoolean("ReadOnly")
  End With

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

    Case "CalculateAccruals"
      ' Calculate Accruals
      Main = CalculateAccruals(parametersJson, returnValue)

    Case "Delete"
      ' Delete Contact Method
      Main = Delete(returnValue)

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

    Case "GetFrequencyInfo"
      ' Get Frequency Information
      Main = GetFrequencyInfo(returnValue)

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

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

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

End Function

''' &lt;summary&gt;
'''  Calculate Accruals
''' &lt;/summary&gt;
''' &lt;returns&gt;&lt;/returns&gt;
Private Function CalculateAccruals(parametersJson As String,
                                   ByRef returnValue As String) As Boolean

  Dim AccountAccountingLedger As finAccountAccountingLedger
  Dim Record As AccountAccountingLedger
  Dim Success As Boolean
  Dim AccountAccountingLedgerAccruals As List(Of AccountAccountingLedgerAccrual)
  Dim AccountAccountingLedgerAccrual As finAccountAccountingLedgerAccrual

  ' Assume Success
  Success = True

  ' Get Accounting Ledger
  Success = GetRecord(parametersJson, Record)

  ' Get Account Accounting Ledger and update (Accruals calculated during update)
  If Success Then
    If GetAccountAccountingLedger(AccountAccountingLedger) Then
      Success = UpdateAccountingLedger(Record, AccountAccountingLedger, False)
    Else
      Success = False
    End If
  End If

  ' Convert to Json object
  If Success Then
    AccountAccountingLedgerAccruals = New List(Of AccountAccountingLedgerAccrual)
    For Each AccountAccountingLedgerAccrual In AccountAccountingLedger.Accruals
      AccountAccountingLedgerAccruals.Add(New AccountAccountingLedgerAccrual(AccountAccountingLedgerAccrual))
    Next
  End If

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

  Return Success

End Function

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

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Shortcut
  If mAccount IsNot Nothing Then
    Return Success
  End If

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

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

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

  ' Load Addresses
  If Success Then
    Success = mAccount.AccountingLedgersLoad()
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Load Account Accounting Ledger.
''' &lt;/summary&gt;
Private Function GetAccountAccountingLedger(ByRef accountAccountingLedger As finAccountAccountingLedger) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Intialise ByRef
  accountAccountingLedger = Nothing

  ' Validate
  If mAccountingLedgerPk = 0 OrElse mAccountingLedgerPk &lt; -1 Then
    Success = False
    finBL.Error.ErrorBeginFormat("Invalid Account Accounting Ledger Pk {0}.", mAccountingLedgerPk)
  End If

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

  ' Get Account Accounting Ledger
  If Success Then
    If mAccountingLedgerPk = -1 Then
      ' New
      accountAccountingLedger = mAccount.AccountingLedgers.CreateAccountAccountingLedger()
      mAccount.AccountingLedgers.Add(accountAccountingLedger)

      ' Defaults
      With accountAccountingLedger
        .BranchPk = mAccount.BranchPk
        .UnearnedBranchPk = .BranchPk
        .DepartmentPk = mAccount.DepartmentPk
        .UnearnedDepartmentPk = .DepartmentPk
        .Type = isefinAccountingLedgerType.AmortisationSchedule
      End With
    Else
      ' Existing
      If mAccount.AccountingLedgers.ExistsPk(mAccountingLedgerPk) Then
        accountAccountingLedger = mAccount.AccountingLedgers.ItemByPk(mAccountingLedgerPk)
      Else
        Success = False
        finBL.Error.ErrorBegin("Failed to retrieve Account Accounting Ledger. This record may have been deleted by another User.")
      End If
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Information based upon a frequency.
''' &lt;/summary&gt;
''' &lt;returns&gt;&lt;/returns&gt;
Private Function GetFrequencyInfo(ByRef returnValue As String) As Boolean

  Dim Data As Object
  Dim DateBegin As Date
  Dim FrequencyCycle As String
  Dim IntervalCount As Integer
  Dim IntervalFirstDate As Date
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    DateBegin = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("DateBegin"))
    FrequencyCycle = .GetString("FrequencyCycle")
  End With

  ' Load Account
  Success = GetAccount()

  ' Calculate Interval
  If Success Then
    If mAccount.DateMaturity = Nothing OrElse DateBegin &gt; mAccount.DateMaturity Then
      IntervalCount = -1
      IntervalFirstDate = finBL.Utilities.DateCycleGetTermEndDate(FrequencyCycle, DateBegin)
    Else
      finBL.Utilities.DateCycleGetIntervalCount(DateBegin, mAccount.DateMaturity, FrequencyCycle, IntervalCount, IntervalFirstDate)
    End If
  End If

  ' Return Data
  If Success Then
    Data = New With {
      .DateCycleDescription = finBL.HtmlEncode(finBL.Utilities.DateCycleGetDescription(True, FrequencyCycle)),
      .IntervalCount = IntervalCount,
      .IntervalFirstDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(IntervalFirstDate)
    }
  End If

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

  Return Success

End Function

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

  Dim AccountAccountingLedger As finAccountAccountingLedger
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean
  Dim TypeList As ISCodeDescriptionList
  Dim cdlItem As ISCodeDescriptionListItem
  Dim dv As DataView
  Dim Row As DataRow
  Dim ElementId As String

  ' Assume Success
  Success = True

  ' Validate

  ' Get Account Accounting Ledger
  If Success Then
    Success = GetAccountAccountingLedger(AccountAccountingLedger)
  End If

  ' Get Types
  If Success Then
    TypeList = finBL.Enums.isefinAccountingLedgerType_ToCodeDescriptionList(False)
  End If

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

      ' Record
      .CurrentDatabaseDate = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()
      .IsNew = AccountAccountingLedger.IsNew
      .Timestamp = AccountAccountingLedger.Timestamp

      Select Case AccountAccountingLedger.StatusOriginal
        Case isefinAccountingLedgerStatus.Active
          .IsActive = True
        Case isefinAccountingLedgerStatus.Cancel, isefinAccountingLedgerStatus.Reverse
          .IsCancelReverse = True
        Case isefinAccountingLedgerStatus.Cancelled, isefinAccountingLedgerStatus.Complete, isefinAccountingLedgerStatus.Reversed
          .IsCancelledCompleteReversed = True
        Case isefinAccountingLedgerStatus.Hold
          .IsHold = True
        Case isefinAccountingLedgerStatus.Suspended
          .IsSuspended = True
      End Select

      ' Account
      .AccountId = mAccount.AccountId
      .AccountName = mAccount.Name

      ' General
      .AccountAccountingLedger = New AccountAccountingLedger(AccountAccountingLedger)

      ' Lists
      .BranchFilter = finBL.Branches.GetDataViewFilter(True, AccountAccountingLedger.Account.EntityPk, True, False)
      .FrequencyList = FREQUENCY_LIST
      .TypeList = TypeList.ToJsonObject(False)
      For Each cdlItem In finBL.Enums.isefinAccountingLedgerMethod_ToCodeDescriptionList(False, AccountAccountingLedger.Account.AccountClass)
        .Methods.Add(New Method(cdlItem, AccountAccountingLedger))
      Next

      ' Elements
      If finBL.Elements.GetDataView(dv,, False, AccountAccountingLedger.AccountAccountingLedgers.ElementDataViewFilter()) Then
        For Each Row In dv.ToTable().Rows
          ElementId = finBL.Database.GetFieldString(Row!ElementId)

          If Len(ElementId) &lt;&gt; 0 AndAlso finBL.Elements.Exists(ElementId) Then
            .Elements.Add(New Element(finBL.Elements(ElementId)))
          End If
        Next
      Else
        Success = False
      End If

      If Success Then
        .ClassificationInformationListId = "AcctgLedgerClassification"
        .AllowBlankClassification = True
        If finBL.InformationLists.Exists(.ClassificationInformationListId) Then
          .AllowBlankClassification = (Not finBL.InformationLists(.ClassificationInformationListId).Mandatory)
        End If
        .AddonBranch = finBL.Settings.AddOns.Branch
        .CanCustomiseAccruals = (finBL.CurrentUser.Permissions.Allow("Account.AccountingLedgers.Customise") AndAlso Not .ReadOnly)
        .CanUpdateGLDetails = (finBL.CurrentUser.Permissions.Allow("Account.AccountingLedgers.GlDetailsUpdate") AndAlso Not .ReadOnly)

        ' Permissions
        If .ReadOnly OrElse .IsNew Then
          .CanDelete = False
        Else
          .CanDelete = finBL.CurrentUser.Permissions.Allow("Client.ContactMethods.Delete")
        End If

        ' Advanced
        .ShowClassification = mCombinedParameters.GetString("ShowClassification") : If Len(.ShowClassification) = 0 Then .ShowClassification = "Advanced"
        .ShowGeneralLedger = mCombinedParameters.GetString("ShowGeneralLedger") : If Len(.ShowGeneralLedger) = 0 Then .ShowGeneralLedger = "Advanced"
        .ShowNotes = mCombinedParameters.GetString("ShowNotes") : If Len(.ShowNotes) = 0 Then .ShowNotes = "Advanced"

        ' General
        .PageGeneralHasAdvanced = (.ShowClassification = "Advanced" OrElse .ShowGeneralLedger = "Advanced" OrElse .ShowNotes = "Advanced")

        ' Configuration Options
        .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
      End If
    End With
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Accounting Ledger.
''' &lt;/summary&gt;
Private Function GetRecord(parametersJson As String,
                           ByRef record As AccountAccountingLedger) As Boolean

  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Save Account Accounting Ledger.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted record (AccountAccountingLedger) object.
''' &lt;/param&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim AccountAccountingLedger As finAccountAccountingLedger
  Dim Index As Integer
  Dim Record As AccountAccountingLedger
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Parse Parameters
  Success = GetRecord(parametersJson, Record)

  ' Get Account Accounting Ledger and update
  If Success Then
    If GetAccountAccountingLedger(AccountAccountingLedger) Then
      Success = UpdateAccountingLedger(Record, AccountAccountingLedger, False)
    Else
      Success = False
    End If
  End If

  ' Save
  If Success Then
    ' Move?
    Select Case Record.MoveAction
      Case "MoveTop"
        Index = mAccount.AccountingLedgers.IndexOf(AccountAccountingLedger)
        mAccount.AccountingLedgers.Move(Index, 0)
    End Select

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Update Accounting Ledger with details from the UI.
''' &lt;/summary&gt;
''' &lt;returns&gt;&lt;/returns&gt;
Private Function UpdateAccountingLedger(record As AccountAccountingLedger,
                                        ByRef accountAccountingLedger As finAccountAccountingLedger,
                                        ByRef sortRequired As Boolean) As Boolean

  Dim AccountAccountingLedgerAccrual As finAccountAccountingLedgerAccrual
  Dim Accrual As AccountAccountingLedgerAccrual
  Dim Success As Boolean
  Dim i As Integer

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  sortRequired = False

  ' Update Accounting Ledger
  With accountAccountingLedger
    ' Element Id Changed?
    If record.ElementId &lt;&gt; .ElementId Then
      Success = .ElementIdSet(record.ElementId)
    End If

    ' General
    If Success Then
      .Classification = record.Classification
      .DateBegin = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(record.DateBegin)
      .DateEnd = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(record.DateEnd)
      .DateFirst = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(record.DateFirst)
      .Description = record.Description
      .FrequencyCycle = record.FrequencyCycle
      .MethodLess = record.MethodLess
      .MethodText = record.Method
      .Notes = record.Notes
      .NumberOfPeriods = record.NumberOfPeriods
      .TypeText = record.Type
      .Value = record.Value

      ' GL Updates
      If finBL.CurrentUser.Permissions.Allow("Account.AccountingLedgers.GlDetailsUpdate") Then
        If finBL.Settings.AddOns.Branch Then
          .BranchId = record.BranchId
          .UnearnedBranchId = record.UnearnedBranchId
        End If
        .DepartmentId = record.DepartmentId
        .GlAccountId = record.GlAccountId
        .GlEomSplit = record.GlEomSplit
        .UnearnedDepartmentId = record.UnearnedDepartmentId
        .UnearnedGlAccountId = record.UnearnedGlAccountId
      End If

      ' Accruals
      If .Method = isefinAccountingLedgerMethod.Custom AndAlso record.Accruals.Count &lt;&gt; 0 Then
        ' Make sure Accruals are loaded
        If .AccrualsLoad() Then
          Success = CreateAccruals(accountAccountingLedger)
        Else
          Success = False
        End If

        If Success Then
          ' Flag all for removal (valid ones will be retained later)
          For Each AccountAccountingLedgerAccrual In .Accruals
            AccountAccountingLedgerAccrual.Tag = "[DELETE]"
          Next

          For Each Accrual In record.Accruals
            If Accrual.Pk = 0 Then
              ' Add new Accrual
              AccountAccountingLedgerAccrual = .Accruals.CreateAccountAccountingLedgerAccrual()
              With AccountAccountingLedgerAccrual
                .Date = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(Accrual.Date)
                .Opening = Accrual.Opening
                .Value = Accrual.Value
              End With
              Success = .Accruals.Add(AccountAccountingLedgerAccrual)
            Else
              ' Update existing Accrual
              AccountAccountingLedgerAccrual = .Accruals.ItemByPk(Accrual.Pk)
              With AccountAccountingLedgerAccrual
                .Date = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(Accrual.Date)
                .Opening = Accrual.Opening
                .Tag = Nothing
                .Value = Accrual.Value
              End With
            End If

            ' Exit if error
            If Not Success Then Exit For
          Next
        End If

        ' Remove Accruals flagged as delete
        If Success Then
          For i = .Accruals.Count - 1 To 0 Step -1
            If .Accruals(i).Tag IsNot Nothing AndAlso .Accruals(i).CanDelete() Then
              If Not .Accruals.RemoveAt(i) Then
                Success = False
                Exit For
              End If
            End If
          Next
        End If

        ' Sort
        If Success Then
          sortRequired = .Accruals.Sort()
        End If
      ElseIf .Type = isefinAccountingLedgerType.AmortisationSchedule AndAlso .Method = isefinAccountingLedgerMethod.Custom Then
        ' Do not re-create accruals
      Else
        ' Create Accruals
        Success = CreateAccruals(accountAccountingLedger)
      End If
    End If

    ' Validate Accruals
    If Success Then
      Success = .Accruals.Validate(True)
    End If
  End With

  Return Success

End Function

''' &lt;summary&gt;
'''  Create Accruals.
''' &lt;/summary&gt;
Private Function CreateAccruals(ByRef accountAccountingLedger As finAccountAccountingLedger) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Create Accruals
  If Not mReadOnly AndAlso accountAccountingLedger.StatusOriginal = isefinAccountingLedgerStatus.Hold Then
    If accountAccountingLedger.Method = isefinAccountingLedgerMethod.Custom Then
      If accountAccountingLedger.Accruals.Count = 0 Then
        Success = accountAccountingLedger.CreateAccruals()
      End If
    Else
      Success = accountAccountingLedger.CreateAccruals()
    End If
  End If

  Return Success

End Function

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

  Dim AccountAccountingLedger As finAccountAccountingLedger
  Dim ConfirmList As List(Of String)
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Record As AccountAccountingLedger
  Dim RecordJson As String
  Dim SortRequired As Boolean
  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")
    RecordJson = .GetString("RecordJson")
  End With

  ' Validate Page
  Select Case PageId
    Case "Accruals"
      ' Accruals
      ConfirmList = New List(Of String)

      ' Parse Parameters
      Success = GetRecord(RecordJson, Record)

      ' Get Account Accounting Ledger and determine if all OK (or if a sort is required)
      If Success Then
        If GetAccountAccountingLedger(AccountAccountingLedger) Then
          Success = UpdateAccountingLedger(Record, AccountAccountingLedger, SortRequired)
        Else
          Success = False
        End If
      End If

      ' Sort Required?
      If Success AndAlso SortRequired Then
        Select Case AccountAccountingLedger.StatusOriginal
          Case isefinAccountingLedgerStatus.Hold, isefinAccountingLedgerStatus.Active, isefinAccountingLedgerStatus.Suspended
            ConfirmList.Add("Journals will be rearranged into the correct date order and/or zero items removed.")
        End Select
      End If

      ' Return Confirm List
      If ConfirmList.Count &lt;&gt; 0 Then Data = ConfirmList
  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;
'''  Delete Account Accounting Ledger.
''' &lt;/summary&gt;
Private Function Delete(ByRef returnValue As String) As Boolean

  Dim AccountAccountingLedger As finAccountAccountingLedger
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Contact Method
  If Success Then
    Success = GetAccountAccountingLedger(AccountAccountingLedger)
  End If

  ' Delete and Save
  If Success Then
    ' Delete
    mAccount.AccountingLedgers.Remove(AccountAccountingLedger)

    ' Save
    Success = mAccount.Save()
  End If

  Return Success

End Function



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

  ' Record
  Public CurrentDatabaseDate As Date
  Public IsNew As Boolean
  Public Timestamp As Integer
  Public IsActive As Boolean
  Public IsCancelReverse As Boolean
  Public IsCancelledCompleteReversed As Boolean
  Public IsHold As Boolean
  Public IsSuspended As Boolean

  ' Client Properties
  Public AccountId As String
  Public AccountName As String

  ' General
  Public AccountAccountingLedger As AccountAccountingLedger

  ' Lists
  Public BranchFilter As String
  Public Elements As New List(Of Element)
  Public FrequencyList As String
  Public TypeList As List(Of ISCodeDescriptionList.ISJsonCodeDescriptionListItem)
  Public Methods As New List(Of Method)

  ' Advanced Sections
  Public PageGeneralHasAdvanced As Boolean
  Public ShowClassification As String
  Public ShowGeneralLedger As String
  Public ShowNotes As String

  ' Configuration
  Public ClassificationInformationListId As String
  Public AllowBlankClassification As Boolean
  Public AddonBranch As Boolean
  Public CanCustomiseAccruals As Boolean
  Public CanUpdateGLDetails As Boolean
  Public CanDelete As Boolean
  Public PromptOnSave As Boolean
  Public [ReadOnly] As Boolean

  ' Other
  Public MoveAction As String

End Class



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

  Public AccountingLedgerGlEomSplit As Boolean
  Public AccountingLedgerLess As Double
  Public AccountingLedgerMethod As String
  Public AccountingLedgerType As String
  Public Description As String
  Public ElementId As String
  Public GlAccountId As String
  Public UnearnedGlAccountId As String

  Public Sub New(elementRO As finElementRO)

    With elementRO
      Me.AccountingLedgerGlEomSplit = .AccountingLedgerGlEomSplit
      Me.AccountingLedgerLess = .AccountingLedgerLess

      If .AccountingLedgerMethod &lt;&gt; isefinAccountingLedgerMethod.None Then
        Me.AccountingLedgerMethod = .AccountingLedgerMethodText
      End If
      If Len(.AccountingLedgerTypeText) = 0 OrElse .AccountingLedgerType = isefinAccountingLedgerType.None Then
        Me.AccountingLedgerType = finBLShared.Enums.isefinAccountingLedgerType_ToString(isefinAccountingLedgerType.AmortisationSchedule)
      Else
        Me.AccountingLedgerType = .AccountingLedgerTypeText
      End If

      Me.Description = .Description
      Me.ElementId = .ElementId
      Me.GlAccountId = .GlAccountId
      Me.UnearnedGlAccountId = .UnearnedGlAccountId
    End With

  End Sub

End Class



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

  Public Code As String
  Public DefaultDateBegin As Date?
  Public DefaultDateEnd As Date?
  Public DefaultDateFirst As Date?
  Public DefaultFrequencyCycle As String
  Public DefaultNumberOfPeriods As Integer
  Public Description As String

  Public Sub New(cdlItem As ISCodeDescriptionListItem,
                 accountAccountingLedger As finAccountAccountingLedger)

    Me.Code = cdlItem.Code
    Me.Description = cdlItem.Description

    ' Method Specific
    Select Case finBLShared.Enums.isefinAccountingLedgerMethod_FromString(cdlItem.Description)
      Case isefinAccountingLedgerMethod.AtClose
        Me.DefaultDateEnd = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(New DateTime(9999, 12, 31))

      Case isefinAccountingLedgerMethod.AtMaturity, isefinAccountingLedgerMethod.ContractualInterest
        Me.DefaultDateEnd = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(accountAccountingLedger.Account.DateMaturity)

      Case isefinAccountingLedgerMethod.Proportional, isefinAccountingLedgerMethod.ProportionalDaily, isefinAccountingLedgerMethod.RuleOf78
        With accountAccountingLedger
          If .Account.DateRestructured = Nothing Then
            .DateBegin = .Account.DateOpened
          Else
            .DateBegin = .Account.DateRestructured
          End If
          .DateEnd = .Account.DateMaturity
          .FrequencyCycle = .Account.AccountingLedgers.GetFrequencyCycle()
          .NumberOfPeriodsReset()

          ' Method Defaults
          Me.DefaultDateBegin = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.DateBegin)
          Me.DefaultDateFirst = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.DateFirst)
          Me.DefaultFrequencyCycle = .FrequencyCycle
          Me.DefaultNumberOfPeriods = .NumberOfPeriods
          Me.DefaultDateEnd = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.DateEnd)
        End With
    End Select

  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



''' &lt;summary&gt;
'''  Simple information about an Account Accounting Ledger.
''' &lt;/summary&gt;
Public Class AccountAccountingLedger

  Public Accruals As New List(Of AccountAccountingLedgerAccrual)
  Public BranchId As String
  Public CanCancel As Boolean
  Public CancelledDate As Date?
  Public CancelledUserId As String
  Public CanDelete As Boolean
  Public CanHold As Boolean
  Public CanReverse As Boolean
  Public CanSuspend As Boolean
  Public Classification As String
  Public CreatedDate As Date?
  Public CreatedUserId As String
  Public DateBegin As Date?
  Public DateEnd As Date?
  Public DateFirst As Date?
  Public DepartmentId As String
  Public Description As String
  Public ElementId As String
  Public FrequencyCycle As String  
  Public GlAccountId As String
  Public GlEomSplit As Boolean
  Public Method As String
  Public MethodLess As Double
  Public MoveAction As String
  Public Notes As String
  Public NumberOfPeriods As Integer
  Public Pk As Integer
  Public Status As String
  Public Timestamp As Integer
  Public Type As String
  Public UnearnedBranchId As String
  Public UnearnedDepartmentId As String
  Public UnearnedGlAccountId As String
  Public Value As Decimal

  Public Sub New()
  End Sub

  Public Sub New(accountAccountingLedger As finAccountAccountingLedger)

    Dim AccountAccountingLedgerAccrual As finAccountAccountingLedgerAccrual

    With accountAccountingLedger
      For Each AccountAccountingLedgerAccrual In .Accruals
        Me.Accruals.Add(New AccountAccountingLedgerAccrual(AccountAccountingLedgerAccrual))
      Next
      Me.BranchId = .BranchId
      Me.CanCancel = .CanCancel()
      Me.CancelledDate = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.CancelledDate)
      Me.CancelledUserId = .CancelledUserId
      Me.CanDelete = .CanDelete()
      Me.CanHold = .CanHold()
      Me.CanReverse = .CanReverse()
      Me.CanSuspend = .CanSuspend()
      Me.Classification = .Classification
      Me.CreatedDate = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(.CreatedDate)
      Me.CreatedUserId = .CreatedUserId
      Me.DateBegin = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.DateBegin)
      Me.DateEnd = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.DateEnd)
      Me.DateFirst = finBLShared.HtmlWidgetUtilities.GetNullableJsonUtcDateFromDatabaseDate(.DateFirst)
      Me.DepartmentId = .DepartmentId
      Me.Description = .Description
      Me.ElementId = .ElementId
      Me.FrequencyCycle = .FrequencyCycle      
      Me.GlAccountId = .GlAccountId
      Me.GlEomSplit = .GlEomSplit
      Me.Method = .MethodText      
      Me.MethodLess = .MethodLess
      Me.Notes = .Notes
      Me.NumberOfPeriods = .NumberOfPeriods
      Me.Pk = .Pk
      Me.Status = .StatusText
      Me.Timestamp = .Timestamp
      Me.Type = .TypeText
      Me.UnearnedBranchId = .UnearnedBranchId
      Me.UnearnedDepartmentId = .UnearnedDepartmentId
      Me.UnearnedGlAccountId = .UnearnedGlAccountId
      Me.Value = .Value
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Account Accounting Ledger Accrual.
''' &lt;/summary&gt;
Public Class AccountAccountingLedgerAccrual

  Public CanDelete As Boolean
  Public [Date] As Date
  Public Opening As Boolean
  Public Pk As Integer
  Public Value As Decimal
  Public ValueRemaining As Decimal
  Public ValueTransferred As Decimal
  Public WarningMessage As String

  Public Sub New()
  End Sub

  Public Sub New(accountAccountingLedgerAccrual As finAccountAccountingLedgerAccrual)

    With accountAccountingLedgerAccrual
      Me.CanDelete = .CanDelete()
      Me.Date = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.Date)
      Me.Opening = .Opening
      Me.Pk = .Pk
      Me.Value = .Value
      Me.ValueRemaining = .ValueRemaining
      Me.ValueTransferred = .ValueTransferred
      Me.WarningMessage = .WarningMessage
    End With

  End Sub

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System defined HTML Widget.

Used as a finPOWER Connect Cloud compatible version of the form "AccountAccountingLedger".</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General" tooltipText="Specify the Type of Accounting Ledger and the Method to use."&gt;Accounting Ledger&lt;/li&gt;
        &lt;li tabId="Accruals" tooltipText="Review the schedule of Accrual Journals."&gt;Accrual Journals&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;


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

        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblStatus"&gt;The current Status of the Accounting Ledger&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboStatus"&gt;Status:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboStatus" /&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblElement"&gt;Select the Element and enter a short description of the Accounting Ledger&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboElement"&gt;Element:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboElement" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtDescription"&gt;Description:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtDescription" /&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblLedgerDetails"&gt;Specify Account Ledger details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboType"&gt;Type:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboType" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboMethod"&gt;Method:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboMethod" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="numMethodLess"&gt;Less:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="numMethodLess" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr advancedId="Classification"&gt;
            &lt;th&gt;&lt;label for="cboClassification"&gt;Classification:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboClassification" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblAmortisation"&gt;Specify the Date and Value to begin amortisation&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateBegin"&gt;Opening:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateBegin" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="numValue"&gt;Value:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="numValue" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody id="tbClose"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblClose"&gt;Enter the Date to earn the value on&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateEnd"&gt;Closing:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateEnd" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody id="tbFrequency"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblFrequency"&gt;Enter the Frequency to release the debit value over&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboFrequency"&gt;Frequency:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboFrequency" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateFirst"&gt;First:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="dateFirst" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="numPeriods"&gt;Periods:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="numPeriods" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody id="tbGeneralLedger" advancedId="GeneralLedger"&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblGLDebit"&gt;Select the Debit details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboUnearnedGlAccount"&gt;GL Account:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboUnearnedGlAccount" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboUnearnedBranch"&gt;Branch:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboUnearnedBranch" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboUnearnedDepartment"&gt;Department:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboUnearnedDepartment" /&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblGLCredit"&gt;Select the Credit details&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboGlAccount"&gt;GL Account:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboGlAccount" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboBranch"&gt;Branch:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboBranch" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboDepartment"&gt;Department:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboDepartment" /&gt;&lt;/td&gt;
          &lt;/tr&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblGLOther"&gt;Other Options&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;input id="chkGlEomSplit" type="checkbox" /&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tbody advancedId="Notes"&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&gt;
            &lt;th&gt;&lt;label for="txtNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtNotes" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Accruals --&gt;
    &lt;div id="pageAccruals" style="display:flex; flex-direction:column"&gt;
      &lt;div style="flex-grow:3; position:relative"&gt;
        &lt;div id="gridAccruals"&gt;&lt;/div&gt;
      &lt;/div&gt;

      &lt;div style="flex-grow:1; position:relative; max-height:120px; max-width:520px; padding-top:8px;"&gt;
        &lt;table class="is-form"&gt;
          &lt;colgroup&gt;
            &lt;col style="width:8em" /&gt;
            &lt;col /&gt;
            &lt;col style="width:8em" /&gt;
            &lt;col /&gt;
          &lt;/colgroup&gt;

          &lt;tr&gt;
            &lt;th colspan="2"&gt;&lt;label id="lblAccruals"&gt;Accrual Journals&lt;/label&gt;&lt;/th&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="numTotal"&gt;Total:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="numTotal" /&gt;&lt;/td&gt;
            &lt;th&gt;&lt;label for="numTransferred"&gt;Transferred:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="numTransferred" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th id="thnumBalance"&gt;&lt;label for="numBalance"&gt;Balance:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="numBalance" /&gt;&lt;/td&gt;
            &lt;th&gt;&lt;label for="numRemaining"&gt;Remaining:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="numRemaining" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/table&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;


  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdActions"/&gt;
    &lt;button id="cmdAdvanced" class="is-button" style="float:left" title="Show/hide advanced options"&gt;Advanced&lt;/button&gt;

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

&lt;/div&gt;


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

// Controls
var C = {
  //   General
  lblStatus: null,
  cboStatus: null,

  lblElement: null,
  cboElement: null,
  txtDescription: null,

  lblLedgerDetails: null,
  cboType: null,
  cboMethod: null,
  numMethodLess: null,
  cboClassification: null,

  lblAmortisation: null,
  dateBegin: null,
  numValue: null,

  tbClose: null,
  lblClose: null,
	dateEnd: null,

  tbFrequency: null,
  lblFrequency: null,
  cboFrequency: null,
  dateFirst: null,
  numPeriods: null,  

  tbGeneralLedger: null,
  lblGLDebit: null,
  cboUnearnedGlAccount: null,
  cboUnearnedBranch: null,
  cboUnearnedDepartment: null,

  lblGLCredit: null,
  cboGlAccount: null,
  cboBranch: null,
  cboDepartment: null,

  lblGLOther: null,
  chkGlEomSplit: null,

  lblNotes: null,
  txtNotes: null,

  //   Accruals
  gridAccruals: null,
  lblAccruals: null,
  numTotal: null,
  numTransferred: null,
  thnumBalance: null,
  numBalance: null,
  numRemaining: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdAdvanced;

// Other
var mAdvancedVisible = false;
var mInitialLoad;
var mRefreshTimer;
var mMethod;
var mType;

// ==========
// Initialise
// ==========
$(function () {
  // --------
  // Controls
  // --------
  //   General
  C.lblStatus = widget.UI.Label("lblStatus", {});
  C.cboStatus = widget.UI.ComboBox("cboStatus", {
    allowDropdown: false,
    readOnly: true,
  });

  C.lblElement = widget.UI.Label("lblElement", {});
  C.cboElement = widget.UI.DBCombo("cboElement", {
    allowBlank: false,
    limitToList: true,
    width: widget.UI.FIELD_WIDTH_CODE_20,

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

  C.lblLedgerDetails = widget.UI.Label("lblLedgerDetails", {});
  C.cboType = widget.UI.ComboBox("cboType", {
    allowBlank: false,

    onChange: cboType_Change,
  });
  C.cboMethod = widget.UI.ComboBox("cboMethod", {
    allowBlank: false,

    onChange: cboMethod_Change,
  });
  C.numMethodLess = widget.UI.NumberBox("numMethodLess", {
    blankIfZero: false,
    decimals: 2,
    percentage: true,
    minValue: 0,
    maxValue: 100,
  });
  C.cboClassification = widget.UI.InformationListComboBox("cboClassification", {
    maxLength: 20,
  });

  C.lblAmortisation = widget.UI.Label("lblAmortisation", {});
  C.dateBegin = widget.UI.DateBox("dateBegin", {
    allowBlank: false,

    onChange: dateBegin_Change,
  });
  C.numValue = widget.UI.NumberBox("numValue", {
    allowBlank: false,
  });

  C.tbClose = $("#tbClose");
	C.lblClose = widget.UI.Label("lblClose", {});
	C.dateEnd = widget.UI.DateBox("dateEnd", {
    allowBlank: false,
  });

  C.tbFrequency = $("#tbFrequency");
  C.lblFrequency = widget.UI.Label("lblFrequency", {});
  C.cboFrequency = widget.UI.DateCycleComboBox("cboFrequency", {
    allowBlank: false,
    isFrequency: true,
    width: "12em",

    onChange: cboFrequency_Change,
  });
  C.dateFirst = widget.UI.DateBox("dateFirst", {
    allowBlank: false,
  });
  C.numPeriods = widget.UI.NumberBox("numPeriods", {
    allowBlank: false,
    decimals: 0,
    minValue: 1,
    maxValue: 9999,
  });  

  C.tbGeneralLedger = $("#tbGeneralLedger");
  C.lblGLDebit = widget.UI.Label("lblGLDebit", {});
  C.cboUnearnedGlAccount = widget.UI.DBCombo("cboUnearnedGlAccount", {
    allowBlank: false,
    limitToList: true,
  });
  C.cboUnearnedBranch = widget.UI.DBCombo("cboUnearnedBranch", {
    allowBlank: false,
    limitToList: true,
  });
  C.cboUnearnedDepartment = widget.UI.DBCombo("cboUnearnedDepartment", {
    allowBlank: false,
    limitToList: true,
  });

  C.lblGLCredit = widget.UI.Label("lblGLCredit", {});
  C.cboGlAccount = widget.UI.DBCombo("cboGlAccount", {
    allowBlank: false,
    limitToList: true,
  });
  C.cboBranch = widget.UI.DBCombo("cboBranch", {
    allowBlank: false,
    limitToList: true,
  });
  C.cboDepartment = widget.UI.DBCombo("cboDepartment", {
    allowBlank: false,
    limitToList: true,
  });

  C.lblGLOther = widget.UI.Label("lblGLOther", {});
  C.chkGlEomSplit = widget.UI.CheckBox("chkGlEomSplit", {
    caption: "Split and apportion Journals at Month End?",
    captionWrap: true,
  });

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

  //   Accruals
  C.lblAccruals = widget.UI.Label("lblAccruals", {});
  C.numTotal = widget.UI.NumberBox("numTotal", {
    readOnly: true,
  });
  C.numTransferred = widget.UI.NumberBox("numTransferred", {
    readOnly: true,
  });
  C.thnumBalance = $("#thnumBalance");
  C.numBalance = widget.UI.NumberBox("numBalance", {
    readOnly: true,
  });
  C.numRemaining = widget.UI.NumberBox("numRemaining", {
    readOnly: true,
  });

  // Grids
  C.gridAccruals = widget.UI.Grid("gridAccruals", {
    allowAddRows: true,
    maxNewRows: 100,
    stickyHeader: true,

    onAction: gridAccruals_Action,
    onAfterRowActivate: gridAccruals_AfterRowActivate,
    onBeforeCellUpdate: gridAccruals_BeforeCellUpdate,
    onInitialiseRow: gridAccruals_InitialiseRow,
    onRowAdd: gridAccruals_RowAdd,
  });

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

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

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

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

  cmdAdvanced = $("#cmdAdvanced");
  cmdAdvanced.click(AdvancedToggle);

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Defaults
  mInitialLoad = true;
  C.numMethodLess.Value(0);

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

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_AccountingLedger = null;
  mMethod = null;
  mType = 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);
  mRecord_AccountingLedger = mRecord.AccountAccountingLedger;

  // Give Collections ability To lookup by code
  widget.ArrayAllowLookupById(mRecord.Elements, "ElementId");
  widget.ArrayAllowLookupById(mRecord.Methods, "Description");
  widget.ArrayAllowLookupById(mRecord.TypeList, "Description");

  // Load Fields
  Fields_Load();

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

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboStatus.Text(mRecord_AccountingLedger.Status);
    C.cboElement.Text(mRecord_AccountingLedger.ElementId);
    C.txtDescription.Text(mRecord_AccountingLedger.Description);

    C.cboType.Text(mRecord_AccountingLedger.Type);
    C.cboMethod.Text(mRecord_AccountingLedger.Method);
    C.numMethodLess.Value(mRecord_AccountingLedger.MethodLess);
    C.cboClassification.Text(mRecord_AccountingLedger.Classification);

    C.dateBegin.Value(mRecord_AccountingLedger.DateBegin);
    C.numValue.Value(mRecord_AccountingLedger.Value);

    C.dateEnd.Value(mRecord_AccountingLedger.DateEnd);

    C.cboFrequency.Text(mRecord_AccountingLedger.FrequencyCycle);
    C.dateFirst.Value(mRecord_AccountingLedger.DateFirst);
    C.numPeriods.Value(mRecord_AccountingLedger.NumberOfPeriods);

    C.cboUnearnedGlAccount.Text(mRecord_AccountingLedger.UnearnedGlAccountId);
    C.cboUnearnedBranch.Text(mRecord_AccountingLedger.UnearnedBranchId);
    C.cboUnearnedDepartment.Text(mRecord_AccountingLedger.UnearnedDepartmentId);

    C.cboGlAccount.Text(mRecord_AccountingLedger.GlAccountId);
    C.cboBranch.Text(mRecord_AccountingLedger.BranchId);
    C.cboDepartment.Text(mRecord_AccountingLedger.DepartmentId);

    C.chkGlEomSplit.Value(mRecord_AccountingLedger.GlEomSplit);

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

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

  // Update Controls
  cboType_Change();
  cboMethod_Change();

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();

  // Reset initial load flag
  mInitialLoad = false;
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  if (mRecord) {
    //   General
    mRecord_AccountingLedger.Status = C.cboStatus.Text();
    mRecord_AccountingLedger.ElementId = C.cboElement.Text();
    mRecord_AccountingLedger.Description = C.txtDescription.Text();

    mRecord_AccountingLedger.Type = C.cboType.Text();
    mRecord_AccountingLedger.Method = C.cboMethod.Text();
    mRecord_AccountingLedger.MethodLess = C.numMethodLess.Value();
    mRecord_AccountingLedger.Classification = C.cboClassification.Text();

    mRecord_AccountingLedger.DateBegin = C.dateBegin.Value();
    mRecord_AccountingLedger.Value = C.numValue.Value();

    mRecord_AccountingLedger.DateEnd = C.dateEnd.Value();

    mRecord_AccountingLedger.FrequencyCycle = C.cboFrequency.Text();
    mRecord_AccountingLedger.DateFirst = C.dateFirst.Value();
    mRecord_AccountingLedger.NumberOfPeriods = C.numPeriods.Value();

    mRecord_AccountingLedger.UnearnedGlAccountId = C.cboUnearnedGlAccount.Text();
    mRecord_AccountingLedger.UnearnedBranchId = C.cboUnearnedBranch.Text();
    mRecord_AccountingLedger.UnearnedDepartmentId = C.cboUnearnedDepartment.Text();

    mRecord_AccountingLedger.GlAccountId = C.cboGlAccount.Text();
    mRecord_AccountingLedger.BranchId = C.cboBranch.Text();
    mRecord_AccountingLedger.DepartmentId = C.cboDepartment.Text();

    mRecord_AccountingLedger.GlEomSplit = C.chkGlEomSplit.Value();

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

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

  // Information Lists
  C.cboClassification.SetComboFromInformationList(mRecord.ClassificationInformationListId, true);

  // Lists
  C.cboFrequency.ListFromCsvString(mRecord.FrequencyList);
  C.cboType.ListFromCodeDescriptionList(mRecord.TypeList);
  C.cboMethod.ListFromCollection(mRecord.Methods, "Description");

  if (mRecord_AccountingLedger) {
    C.cboUnearnedGlAccount.RefreshFromStandardRange("GlAccounts", "", false, mRecord_AccountingLedger.UnearnedGlAccountId);
    C.cboUnearnedBranch.RefreshFromStandardRange("Branches", mRecord.BranchFilter, false, mRecord_AccountingLedger.UnearnedBranchId);
    C.cboUnearnedDepartment.RefreshFromStandardRange("Departments", "", false, mRecord_AccountingLedger.UnearnedDepartmentId);

    C.cboGlAccount.RefreshFromStandardRange("GlAccounts", "", false, mRecord_AccountingLedger.GlAccountId);
    C.cboBranch.RefreshFromStandardRange("Branches", mRecord.BranchFilter, false, mRecord_AccountingLedger.BranchId);
    C.cboDepartment.RefreshFromStandardRange("Departments", "", false, mRecord_AccountingLedger.DepartmentId);
  }

  // Controls
  if (mRecord) {
    // Initialise Advanced
    AdvancedInitialise();

    C.cboElement.RefreshFromCollection(mRecord.Elements, "ElementId", "Description");
    if (!C.cboType.Text()) C.cboType.Text(mRecord.TypeList[0].Description);

    // Branch
    if (!mRecord.AddonBranch) {
      C.cboUnearnedBranch.VisibleRow(false);
      C.cboBranch.VisibleRow(false);
    }

    // Status
    if (!mRecord.ReadOnly) Fields_Update_Status();

    // Layout Controls
    pageGeneral_Refresh();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

  // Read-Only?
  if (mRecord &amp;&amp; mRecord.ReadOnly) frmMain.FormReadOnly(C, true);

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

  // Resize Tab
  tabWizard_Resize();
}

function Fields_Update_Status() {
  // Disable all fields (except for 'Hold' status, let default values dictate read only)
  if (!mRecord.IsHold) {
    C.cboElement.ReadOnly(true);
    C.txtDescription.ReadOnly(true);
    C.cboType.ReadOnly(true);
    C.cboMethod.ReadOnly(true);
    C.numMethodLess.ReadOnly(true);
    C.cboClassification.ReadOnly(true);
    C.dateBegin.ReadOnly(true);
    C.numValue.ReadOnly(true);
    C.dateEnd.ReadOnly(true);
    C.cboFrequency.ReadOnly(true);
    C.dateFirst.ReadOnly(true);
    C.numPeriods.ReadOnly(true);
    C.cboUnearnedGlAccount.ReadOnly(true);
    C.cboUnearnedBranch.ReadOnly(true);
    C.cboUnearnedDepartment.ReadOnly(true);
    C.cboGlAccount.ReadOnly(true);
    C.cboBranch.ReadOnly(true);
    C.cboDepartment.ReadOnly(true);
    C.chkGlEomSplit.ReadOnly(true);
    C.txtNotes.ReadOnly(true);

    C.gridAccruals.ReadOnly(true);
  }

  // Re-enable based upon Status - doesn't apply to 'Hold' Status
  if (mRecord.IsActive || mRecord.IsSuspended) {
    C.txtDescription.ReadOnly(false);
    C.cboClassification.ReadOnly(false);
    C.txtNotes.ReadOnly(false);
    C.gridAccruals.ReadOnly(false);

    if (mRecord.CanUpdateGLDetails) {
      C.cboUnearnedGlAccount.ReadOnly(false);
      C.cboUnearnedBranch.ReadOnly(false);
      C.cboUnearnedDepartment.ReadOnly(false);

      C.cboGlAccount.ReadOnly(false);
      C.cboBranch.ReadOnly(false);
      C.cboDepartment.ReadOnly(false);

      C.chkGlEomSplit.ReadOnly(false);
    }
  }
  else if (mRecord.IsCancelReverse || mRecord.IsCancelledCompleteReversed) {
    C.txtDescription.ReadOnly(false);
    C.cboClassification.ReadOnly(false);
    C.txtNotes.ReadOnly(false);
  }

  // General Ledger Mandatory?
  C.cboBranch.AllowBlank(mRecord.IsHold);
  C.cboDepartment.AllowBlank(mRecord.IsHold);
  C.cboGlAccount.AllowBlank(mRecord.IsHold);
  C.cboUnearnedBranch.AllowBlank(mRecord.IsHold);
  C.cboUnearnedDepartment.AllowBlank(mRecord.IsHold);
  C.cboUnearnedGlAccount.AllowBlank(mRecord.IsHold);
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // General

  // Tab
  tabWizard_Resize();
}

// ==============
// Wizard Buttons
// ==============
function tabWizard_Cancel() {
  if (widget.CanClose()) {
    widget.Close();
  }
  else {
    widget.Reset();
  }
}

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

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

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

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      // General
      C.txtDescription.WidthResizeFromParent();
      break;
  }
}

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

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

function tabWizard_MovePost(direction) {
  var Ok = true;

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

    do {
      newTab += direction;

      switch (tabWizard.GetTabIdByIndex(newTab)) {
        default:
          found = true;
          break;
      }

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

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

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

      case "Accruals":
        // Accruals
        pageAccruals_Refresh();
        break;

      default:
        break;
    }
  }

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

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    default:
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;
  }

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

  // Resize Wizard
  tabWizard_Resize();

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

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        if (C.numValue.Value() == 0) {
          Ok = false;
          C.numValue.Focus();
        }
        else if (!mAdvancedVisible) {
          if (!C.cboClassification.Text() &amp;&amp; !mRecord.AllowBlankClassification) {
            Ok = false;
            cmdAdvanced.trigger("click");
            C.cboClassification.Focus();
          }
          else if (!mRecord.IsHold &amp;&amp; !C.cboUnearnedGlAccount.Text()) {
            Ok = false;
            cmdAdvanced.trigger("click");
            C.cboUnearnedGlAccount.Focus();
          }
          else if (!mRecord.IsHold &amp;&amp; !C.cboUnearnedBranch.Text()) {
            Ok = false;
            cmdAdvanced.trigger("click");
            C.cboUnearnedBranch.Focus();
          }
          else if (!mRecord.IsHold &amp;&amp; !C.cboUnearnedDepartment.Text()) {
            Ok = false;
            cmdAdvanced.trigger("click");
            C.cboUnearnedDepartment.Focus();
          }
          else if (!mRecord.IsHold &amp;&amp; !C.cboGlAccount.Text()) {
            Ok = false;
            cmdAdvanced.trigger("click");
            C.cboGlAccount.Focus();
          }
          else if (!mRecord.IsHold &amp;&amp; !C.cboBranch.Text()) {
            Ok = false;
            cmdAdvanced.trigger("click");
            C.cboBranch.Focus();
          }
          else if (!mRecord.IsHold &amp;&amp; !C.cboDepartment.Text()) {
            Ok = false;
            cmdAdvanced.trigger("click");
            C.cboDepartment.Focus();
          }
        }
        break;

      case "Accruals":
        // Server side validation required
        break;

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

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

    switch (tabWizard.SelectedTabId()) {
      case "Accruals":
        if (!mRecord.ReadOnly) {
          // Save
          Fields_Save();

          // Params
          params = {
            recordJson: JSON.parse(JSON.stringify(mRecord_AccountingLedger)),
          }
        }
        break;
    }

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

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

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

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

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

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

          // Allow callbacks to continue
          return;
        };

        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

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

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

    case "MOVETOP":
      Form_ExecuteAction_MoveTop();
      break;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==================
// Move to Top Action
// ==================
function Form_ExecuteAction_MoveTop() {
  // Validate
  tabWizard_Validate(function () {
    // Confirm
    if (mRecord.PromptOnSave) {
      widget.UI.MsgBoxConfirm("Move the Accounting Ledger to the top of the list?\n\nNote, this will also update your changes.",
                              { heading: "Update and Promote Accounting Ledger" },
                              function () {
                                // Save and Move
                                Form_ExecuteAction_FinishPost("MoveTop");
                              });
    }
    else {
      // Save and Move without prompting
      Form_ExecuteAction_FinishPost("MoveTop");
    }
  });
}

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  // Controls
  C.cboMethod.VisibleRow(false);
  C.numMethodLess.VisibleRow(false);
  C.tbClose.hide();
  C.tbFrequency.hide();
  C.lblGLOther.VisibleRow(true);
  C.chkGlEomSplit.VisibleRow(true);

  // Type
  if (mType) {
    // Method
    switch (mType.Code) {
      case "AmortisationSchedule":
        C.cboMethod.VisibleRow(true);
        break;

      default:
        // Reset Method
        C.cboMethod.Text("");
        cboMethod_Change();
        break;
    }

    // General Ledger
    if (mType.Code == "SimpleJournal") {
      C.lblGLDebit.Text("Select the Debit details");
      C.lblGLCredit.Text("Select the Credit details");
    }
    else {
      C.lblGLDebit.Text("Select the Unearned details");
      C.lblGLCredit.Text("Select the Earned details");
    }
  }

  // Method
  if (mMethod) {
    // "Less" display
    switch (mMethod.Code) {
      case "ProportionalDaily":
      case "Proportional":
      case "RuleOf78":
      case "ContractualInterest":
        C.numMethodLess.VisibleRow(true);
        break;
    }

    // Close Date and GL EOM Splits
    switch (mMethod.Code) {
      case "AtClose":
      case "AtMaturity":
      case "OnDate":
        C.tbClose.show();

        C.lblGLOther.VisibleRow(false);
        C.chkGlEomSplit.VisibleRow(false);
        break;
    }

    // Frequency
    switch (mMethod.Code) {
      case "ProportionalDaily":
      case "Proportional":
      case "RuleOf78":
        C.tbFrequency.show();
        break;
    }
  }

  // Update Controls
  cboFrequency_Change();
}

// ============
// pageAccruals
// ============
function pageAccruals_Refresh() {
  var RefreshRequired = true;

  // Only calculate Accruals when "Custom" if there are none
  if (C.cboMethod.Text() == "Custom" &amp;&amp; mRecord_AccountingLedger &amp;&amp; mRecord_AccountingLedger.Accruals) {
    RefreshRequired = (mRecord_AccountingLedger.Accruals.length == 0);
  }

  if (!RefreshRequired || mRecord.ReadOnly) {
    // Refresh Grid
    gridAccruals_Refresh();
  }
  else {
    // Calculate Accruals
    pageAccruals_Refresh_Post();
  }
}

function pageAccruals_Refresh_Post() {
  // Hide content
  frmMain.Visible(false);

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

  // Save
  Fields_Save();

  // Params
  var params = JSON.parse(JSON.stringify(mRecord_AccountingLedger));

  // Calculate
  widget.GetString("CalculateAccruals", params,
    function(data) {
      // Parse
      if (data) mRecord_AccountingLedger.Accruals = JSON.parse(data);

      // Refresh Grid
      gridAccruals_Refresh();

      // Unblock
      widget.UI.Unblock();

      // Show content
      frmMain.Visible(true);
    },
    function(errorMessage) {
      // Unblock
      widget.UI.Unblock();

      // Show content
      frmMain.Visible(true);

      // Move back a page
      tabWizard_Move(-1);

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

// ==========
// cboElement
// ==========
function cboElement_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Get Element
  var Element = mRecord.Elements.GetItem(C.cboElement.Text());

  // Update Defaults
  if (e) {
    if (Element) {
      C.txtDescription.Text(Element.Description);
      C.cboType.Text(Element.AccountingLedgerType);
      C.cboMethod.Text(Element.AccountingLedgerMethod);
      C.numMethodLess.Value(Element.AccountingLedgerLess);
      C.cboGlAccount.Text(Element.GlAccountId);
      C.cboUnearnedGlAccount.Text(Element.UnearnedGlAccountId);
      C.chkGlEomSplit.Value(Element.AccountingLedgerGlEomSplit);

      // Update Controls
      cboType_Change(sender, e);
      cboMethod_Change(sender, e);
    }
    else {
      C.txtDescription.Text("");
    }
  }
}

// ============
// cboFrequency
// ============
function cboFrequency_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Delayed refresh
  if (mRefreshTimer) {
    window.clearTimeout(mRefreshTimer);
    mRefreshTimer = null;
  }

  // Only calculate for specific methods
  if (!mInitialLoad &amp;&amp; C.dateBegin.Value() &amp;&amp; C.cboFrequency.Text() &amp;&amp; mMethod) {
    switch (mMethod.Code) {
      case "ProportionalDaily":
      case "Proportional":
      case "RuleOf78":
        // Refresh after 500ms
        mRefreshTimer = window.setTimeout(cboFrequency_Change_Post, 500);
        break;
    }
  }
}

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

  // Params
  var params = {
    dateBegin: C.dateBegin.Value(),
    frequencyCycle: C.cboFrequency.Text(),
  }

  // Get Information
  widget.GetString("GetFrequencyInfo", params,
    function(data) {
      // Parse
      if (data) data = JSON.parse(data);

      // Update
      C.dateFirst.Value(data.IntervalFirstDate);
      if (data.IntervalCount != -1) C.numPeriods.Value(data.IntervalCount);      

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

    function(errorMessage) {
      // Unblock
      widget.UI.Unblock();

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

// =======
// cboType
// =======
function cboType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Set Type
  mType = mRecord.TypeList.GetItem(C.cboType.Text());

  // Refresh General Page
  if (e) pageGeneral_Refresh();
}

// =========
// cboMethod
// =========
function cboMethod_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Set Method
  mMethod = mRecord.Methods.GetItem(C.cboMethod.Text());

  // Set Defaults
  if (mMethod &amp;&amp; e) {
    if (mMethod.DefaultDateBegin) C.dateBegin.Value(mMethod.DefaultDateBegin);
    if (mMethod.DefaultFrequencyCycle) C.cboFrequency.Text(mMethod.DefaultFrequencyCycle);
    if (mMethod.DefaultDateFirst) C.dateFirst.Value(mMethod.DefaultDateFirst);
    if (mMethod.DefaultNumberOfPeriods) C.numPeriods.Value(mMethod.DefaultNumberOfPeriods);
    if (mMethod.DefaultDateEnd) C.dateEnd.Value(mMethod.DefaultDateEnd);
  }

  // Refresh General Page
  if (e) pageGeneral_Refresh();
}

// =========
// dateBegin
// =========
function dateBegin_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Recalculate frequency
  cboFrequency_Change();
}

// ============
// gridAccruals
// ============
function gridAccruals_Refresh() {
  // Columns to include
  var showWarning = false;
  var showOpening = false;
  for (var i = 0; i &lt; mRecord_AccountingLedger.Accruals.length; i++) {
    var item = mRecord_AccountingLedger.Accruals[i];

    if (item.WarningMessage) showWarning = true;
  }

  if (mType) showOpening = (mType.Code == "AmortisationSchedule");

  // Add Columns
  C.gridAccruals.ClearColumns();
  C.gridAccruals.AddColumnInteger("RowNumber", { caption: "", width: "8px" });
  C.gridAccruals.AddColumnDate("Date", { caption: "Date", allowEdit: true });
  C.gridAccruals.AddColumnBoolean("Opening", { caption: "Opening", allowEdit: true, visible: showOpening });
  C.gridAccruals.AddColumnCurrency("Value", { caption: "Value", allowEdit: true });
  C.gridAccruals.AddColumnCurrency("ValueTransferred", { caption: "Transferred" });
  C.gridAccruals.AddColumnCurrency("ValueRemaining", { caption: "Remaining" });
  C.gridAccruals.AddColumnString("WarningMessage", { caption: "Warning", visible: showWarning });

  // Actions
  if (mRecord.CanCustomiseAccruals) {
    C.gridAccruals.Actions().Define([{ actionId: "Customise", caption: "", tooltipText: "Customise Journals", icon: "Tools" },
                                     { actionId: "DeleteRow", tooltipText: "Remove row", icon: "Grid_Row_Delete" }]);
  }

  // Can customise
  var InCustomiseMode = false;
  C.gridAccruals.ReadOnly(true);
  if (mRecord.CanCustomiseAccruals &amp;&amp; C.cboMethod.Text() == "Custom") {
    InCustomiseMode = true;
    C.gridAccruals.ReadOnly(false);
  }

  // Grid Actions
  C.gridAccruals.Actions().SetEnabled("Customise", !InCustomiseMode);

  // Refresh
  C.gridAccruals.VirtualDataRefresh(mRecord_AccountingLedger.Accruals);

  // Select first row
  C.gridAccruals.ActivateFirstDataRow(true);

  // Refresh Buttons
  C.gridAccruals.RefreshButtons();

  // Refresh Totals
  CalculateAccrualTotals();
}

function gridAccruals_AfterRowActivate(e) {
  // Update Delete Row button
  C.gridAccruals.Actions().SetEnabled("DeleteRow", false);
  if (C.cboMethod.Text() == "Custom") {
    if (C.gridAccruals.ActiveDataRowListIndex() != -1) {
      var item = mRecord_AccountingLedger.Accruals[C.gridAccruals.ActiveDataRowIndex()];
      C.gridAccruals.Actions().SetEnabled("DeleteRow", item.CanDelete);
    }
  }

  // Refresh Buttons
  C.gridAccruals.RefreshButtons();
}

function gridAccruals_InitialiseRow(e) {
  var item = mRecord_AccountingLedger.Accruals[e.row.listIndex];

  // Update cells
  e.row.AutoBind(item);

  // Row Number
  e.row.cells.RowNumber.value = e.row.listIndex;

  // Update Read Only
  var EditMode = (mRecord.CanCustomiseAccruals &amp;&amp; C.cboMethod.Text() == "Custom");
  e.row.cells.RowNumber.readOnly = true;
  e.row.cells.Date.readOnly = !EditMode;
  e.row.cells.Opening.readOnly = !EditMode;
  e.row.cells.Value.readOnly = !EditMode;
  e.row.cells.ValueTransferred.readOnly = true;
  e.row.cells.ValueRemaining.readOnly = true;
  e.row.cells.WarningMessage.readOnly = true;
}

function gridAccruals_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "CUSTOMISE":
      // Update Method to "Custom"
      C.cboMethod.Text("Custom");

      // Update Controls
      cboMethod_Change();

      // Grid Actions
      gridAccruals_Refresh();
      break;

    case "DELETEROW":
      // Block UI
      widget.UI.Block("Removing Accrual, please wait...")

      // Get Item
      var item = mRecord_AccountingLedger.Accruals[C.gridAccruals.ActiveDataRowIndex()];

      // Delete
      if (item.CanDelete) {
        C.gridAccruals.RemoveRowAndCollectionItem(C.gridAccruals.ActiveDataRowIndex());
        C.gridAccruals.Focus();
      }

      // Refresh Grid (mostly so row numbers update correctly)
      gridAccruals_Refresh();

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

function gridAccruals_BeforeCellUpdate(e) {
  var item = mRecord_AccountingLedger.Accruals[e.row.listIndex];

  switch(e.columnKey) {
    case "Date":
      item.Date = e.newValue;
      break;

    case "Opening":
      item.Opening = e.newValue;
      break;

    case "Value":
      item.Value = e.newValue;
      break;
  }

  // Refresh row to update styles
  e.refreshRow = true;

  // Recalculate
  CalculateAccrualTotals();
}

function gridAccruals_RowAdd(e) {
  // Create item
  var item = {
    CanDelete: true,
    Date: mRecord.CurrentDatabaseDate,
    Opening: false,
    Pk: 0,
    Value: 0,
    ValueRemaining: 0,
    ValueTransferred: 0,
    WarningMessage: "",
  };

  // Add
  mRecord_AccountingLedger.Accruals.push(item);
}

// ==============================
// Calculate Accruals Grid totals
// ==============================
function CalculateAccrualTotals() {
  var BalanceVisible = false;

  // Reset
  C.numTotal.Value(0);
  C.numTransferred.Value(0);
  C.numBalance.Value(0);
  C.numRemaining.Value(0);

  // Calculate Totals
  var TotalTransferredEarned = 0;
  var TotalOpening = 0;
  var Total = 0;
  var TotalEarned = 0;
  for (var i = 0; i &lt; mRecord_AccountingLedger.Accruals.length; i++) {
    var item = mRecord_AccountingLedger.Accruals[i];

    // Total
    Total += item.Value;

    // Total Opening / Earned
    if (item.Opening) {
      TotalOpening += item.Value;
    }
    else {
      TotalEarned += item.Value;
    }

    // Total Transferred Earned
    if (mType) {
      switch (mType.Code) {
        case "AmortisationSchedule":
          if (!item.Opening) TotalTransferredEarned += item.ValueTransferred;
          break;

        case "SimpleJournal":
          TotalTransferredEarned -= item.ValueTransferred;
          break;
      }
    }
  }

  // Refresh Totals
  if (mType) {
    switch (mType.Code) {
      case "AmortisationSchedule":
        C.numTotal.Value(TotalOpening);
        C.numBalance.Value(Total);
        C.numRemaining.Value(TotalEarned - TotalTransferredEarned);
        break;

      case "SimpleJournal":
        C.numTotal.Value(Total);
        C.numBalance.Value(0);
        C.numRemaining.Value(Total + TotalTransferredEarned);
        break;
    }
  }

  // Show / Hide Balance
  if (mType &amp;&amp; mMethod) {
    if (mMethod.Code == "Custom") {
      BalanceVisible = (mType.Code == "AmortisationSchedule");
    }
    else {
      BalanceVisible = (C.numBalance.Value() != 0);
    }
  }

  // Update Balance Visibility
  if (BalanceVisible) {
    C.thnumBalance.css("visibility", "");
    C.numBalance.Visible(true);
  }
  else {
    C.thnumBalance.css("visibility", "hidden");
    C.numBalance.Visible(false);
  }
}

// =================
// Advanced handling
// =================
function AdvancedInitialise() {
  // Tweaks

  // General
  AdvancedInitialiseSection("Classification", mRecord.ShowClassification);
  AdvancedInitialiseSection("GeneralLedger", mRecord.ShowGeneralLedger);
  AdvancedInitialiseSection("Notes", mRecord.ShowNotes);
}

function AdvancedInitialiseSection(id, option) {
  // Get elements
  var els=$("*[advancedId='" + id + "']");

  // Update
  switch(option.toUpperCase()) {
    case "TRUE":
      // Always show, i.e., not advanced
      break;

    case "FALSE":
      // Never show
      els.hide();
      break;

    case "ADVANCED":
      // Only show in 'Advanced' mode
      els.addClass("advanced");
      break;
  }
}

function AdvancedToggle() {
  // Toggle Advanced
  mAdvancedVisible = !mAdvancedVisible;

  // Update Controls
  if (mAdvancedVisible) {
    // Showing
    $("body").addClass("advanced-visible");
    cmdAdvanced.attr("showing", true);
  }
  else {
    // Not showing
    $("body").removeClass("advanced-visible");
    cmdAdvanced.attr("showing", false);
  }

  // Other
  switch (tabWizard.SelectedTabId()) {
    default:
      break;
  }

  // Finalise
  AdvancedInitialise();

  // Force resize
  tabWizard_Resize()
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>LhzA5wc7RUq603QUq-wDTw</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ShowClassification" 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>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowGeneralLedger" 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>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ShowNotes" 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>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</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>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="AccountId" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <List>RANGE.Accounts</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AccountingLedgerPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>