<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-08T23:46:24.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-09-08T23:33:37.3100000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-08T23:40:07.5720000</UpdatedUtcDate>
    <ScriptId>HWAREST</ScriptId>
    <Description>Account Restructure</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountRestructure
Option Explicit On
Option Strict On

' #################################################################
' Account Restructure HTML Widget
'
' Version: 1.04 (09/09/2024)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  02/11/2022  ISS      J028580   Created
'    1.01  17/03/2023  ISS      J030259   Added support for Workflows
'    1.02  28/08/2023  ISS      J031396   finAccount.CanRestructure() now called in GetInitialisationInfo
'    1.03  31/01/2024  ISS      J032823   Overriding Payments may not allow "Promise" type
'    1.04  09/09/2024  ISS      J034199   Added support for custom "Other Interest" caption 
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountRestructure"

' Common Parameters
Private mAccountId As String
Private mStdTransWidgetId As String
Private mWorkflowPk As Integer
Private mWorkflowItemPk As Integer

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

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 Common Parameters
  With mCombinedParameters
    mAccountId = .GetString("AccountId")
    mStdTransWidgetId = .GetString("StdTransWidgetId")
    mWorkflowPk = .GetInteger("WorkflowPk")
    mWorkflowItemPk = .GetInteger("WorkflowItemPk")
  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 "GetInitialisationInfo"
      ' Get Initialisation Information required for this wizard
      Main = GetInitialisationInfo(returnValue)

    Case "AccrualsRefresh"
      ' Refresh Accruals page
      Main = AccrualsRefresh(parametersJson, returnValue)
      
    Case "AllocationsRefresh"
      ' Refresh Allocations page
      Main = AllocationsRefresh(parametersJson, returnValue)

    Case "Calculate"
      ' Calculate Financials
      Main = Calculate(parametersJson, returnValue)

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

    Case "GetSchedule"
      ' Get Schedule
      Main = GetSchedule(parametersJson, returnValue)

    Case "OverridingPaymentsHandling"
      ' Create Blank Regular Payments
      Main = OverridingPaymentsHandling(returnValue)      
      
    Case "PrintAdvice"
      ' Print Advice
      Main = PrintAdvice(returnValue)        
      
    Case "UpdateNetBalance"
      ' Updates Net Balance
      Main = UpdateNetBalance(parametersJson, returnValue)
      
    Case Else
      finBL.Error.ErrorBeginFormat("Unhandled event '{0}'.", eventId)
      Main = False
  End Select

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 AccountRestructure As finAccountRestructure
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Message As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

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

  ' Get Account Restructure
  If Success Then
    Success = CreateAccountRestructure(AccountRestructure, Nothing)
  End If

  ' Validate to ensure this Account can be Restructured by the current User
  If Success Then
    If Not AccountRestructure.Account.CanRestructure(Message) Then
      Success = False
      finBL.Error.ErrorBegin(Message)
    End If
  End If
  
  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Account
      .RecordCode = AccountRestructure.Account.AccountId
      .RecordDescription = AccountRestructure.Account.Name
      .SuspendDefaultFees = AccountRestructure.Account.SuspendDefaultFees
      .SuspendDefaultInterest = AccountRestructure.Account.SuspendDefaultInterest
      .SuspendFacilityFee = AccountRestructure.Account.SuspendFacilityFee
      .SuspendInterest = AccountRestructure.Account.SuspendInterest
      .SuspendStandardTransactions = AccountRestructure.Account.SuspendStandardTransactions
      .OtherInterestDescription = AccountRestructure.Account.AccountType.OtherInterestDescriptionResolved
      .OverridingPaymentsCountPromises = AccountRestructure.Account.Calculation.Payments.CountPromises

      .RestructureDateMin = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(AccountRestructure.Account.DateRestructured.AddDays(1))
      .RestructureDateMax = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(AccountRestructure.Account.Entity.DateTransactionEnd)
      
      ' Record
      .AccountRestructureDetails = New AccountRestructureDetails(AccountRestructure)

      ' Workflow
      If mWorkflowPk &lt;&gt; 0 Then
        .WorkflowDescription = finBL.WorkflowFunctions.GetRecordCodeDescription(mWorkflowPk, .WorkflowId)
        .WorkflowItemPk = mWorkflowItemPk
      End If
      
      ' Lists
      .ByWhomList = finBL.AccountFunctions.GetByWhomList(AccountRestructure.Account, True, False, True).ToCsvString()
      .PaymentCycleList = AccountRestructure.Account.AccountType.PaymentCycleListResolved()
      .PaymentTypeList = finBl.Enums.isefinAccountCalcPaymentType_ToCodeDescriptionList().ToJsonObject()
      
      ' Information Lists

      ' Global Collections

      ' Permissions

      ' Advanced Sections

      ' Configuration
      .CanChargeFee = (AccountRestructure.FeeElementPk &lt;&gt; 0)
      .CanChangeFee = (.CanChargeFee AndAlso AccountRestructure.FeeAllowChange)
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
      .ShowPrintAdvice = finBL.Documents.Exists(AccountRestructure.Account.AccountType.RestructureDocumentId)
      .StdTransWidgetId = mStdTransWidgetId

      ' Form Heading
      .FormHeading = ScriptInfo.ScriptCaption
        If Len(.FormHeading) = 0 Then .FormHeading = "Account Restructure"
    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 Wizard Finish Parameters.
''' &lt;/summary&gt;
Private Function GetWizardFinishParameters(parametersJson As String,
                                           ByRef wizardFinishParameters As WizardFinishParameters) As Boolean

  Dim obj As Object
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  wizardFinishParameters = Nothing

  ' Get Finish Parameters
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(WizardFinishParameters), obj) Then
    wizardFinishParameters = DirectCast(obj, WizardFinishParameters)
  Else
    Success = False
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Create an Account Restructure
''' &lt;/summary&gt;
''' &lt;returns&gt;&lt;/returns&gt;
Private Function CreateAccountRestructure(ByRef accountRestructure As finAccountRestructure,
                                          parameters As WizardFinishParameters) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountRestructure = finBL.CreateAccountRestructure()

  ' Load
  Success = accountRestructure.AccountLoad(mAccountId)

  ' Update
  If Success AndAlso parameters IsNot Nothing Then
    With accountRestructure
      .RestructureDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.RestructureDate)
      .RestructureByWhom = parameters.RestructureByWhom
      .RestructureType = parameters.RestructureType
      .RestructureReason = parameters.RestructureReason

      .FeeCharge = parameters.FeeChargeFee
      .FeeValue = parameters.FeeValue

      .PrintAdvice = parameters.PrintAdvice
      .LogCreate = parameters.CreateLog

      ' Workflow
      .WorkflowPk = mWorkflowPk
      .WorkflowItemPk = mWorkflowItemPk
      
      ' Ensure balances are correct based upon the Restructure Date before setting other fields
      If .CalculateCurrent() Then
        Success = .ResetNew()
      Else 
        Success = False
      End If
      
      If Success Then
        ' Accruals
        If Not parameters.InitialAccrualsLoad Then
          .AccruedInterest = parameters.AccruedInterest
          .AccruedInterestCharge = parameters.AccruedInterestCharge
          .AccruedDefaultInterest = parameters.AccruedDefaultInterest
          .AccruedDefaultInterestCharge = parameters.AccruedDefaultInterestCharge
          .AccruedOtherInterest = parameters.AccruedOtherInterest
          .AccruedOtherInterestCharge = parameters.AccruedOtherInterestCharge
          .UnpostedDefaultFees = parameters.UnpostedDefaultFees
          .UnpostedDefaultFeesCharge = parameters.UnpostedDefaultFeesCharge
          .UnpostedOverLimitFees = parameters.UnpostedOverLimitFees
          .UnpostedOverLimitFeesCharge = parameters.UnpostedOverLimitFeesCharge
          .UnpostedFacilityFees = parameters.UnpostedFacilityFees
          .UnpostedFacilityFeesCharge = parameters.UnpostedFacilityFeesCharge
          .UnpostedStandardTransactionsCharge = parameters.UnpostedStandardTransactionsCharge
          
          .SuspendInterest = parameters.SuspendInterest
          .SuspendDefaultInterest = parameters.SuspendDefaultInterest
          .SuspendDefaultFees = parameters.SuspendDefaultFees
          .SuspendFacilityFee = parameters.SuspendFacilityFee
          .SuspendStandardTransactions = parameters.SuspendStandardTransactions
        End If      
  
        ' Balance Allocations
        If Not parameters.InitialAllocationsLoad Then
          .BalancePrincipalNIB = parameters.BalancePrincipalNIB
          .BalancePrincipalIB = parameters.BalancePrincipalIB
          .BalanceInterest = parameters.BalanceInterest
          .BalanceFeeNIB = parameters.BalanceFeeNIB
          .BalanceFeeIB = parameters.BalanceFeeIB     
          .BalanceOverdue = parameters.BalanceOverdue
        End If      
  
        ' Calculation
        If Len(parameters.AccountCalcJson) &lt;&gt; 0 Then
          Success = .CalculationNew.FromHtmlWidgetJsonString(parameters.AccountCalcJson)
        End If
        If Success AndAlso Len(parameters.PromisesJson) &lt;&gt; 0 Then
          Success = .AddPromisesFromHtmlWidgetJsonString(parameters.PromisesJson)
        End If
      End If      
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Refresh Accruals.
''' &lt;/summary&gt;
Private Function AccrualsRefresh(parametersJson As String,
                                 ByRef returnValue As String) As Boolean

  Dim AccountRestructure As finAccountRestructure
  Dim Data As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  Dim strTemp As String
  
  ' Assume Success
  Success = True
  
  ' Get Account Restructure
  If GetWizardFinishParameters(parametersJson, WizardFinishParameters) Then
    Success = CreateAccountRestructure(AccountRestructure, WizardFinishParameters)
  Else
    Success = False
  End If  
  
  ' Validate
  If Success Then
    If Not AccountRestructure.ValidateCurrent() Then
      Success = False
    ElseIf AccountRestructure.OriginalBalance &lt;= 0 Then
      Success = False
      finBL.Error.ErrorBegin("Cannot Restructure an Account with a Credit or Nil Balance.")
    ElseIf AccountRestructure.PrintAdvice AndAlso Not AccountRestructure.CanSendDocument(strTemp) Then
      Success = False
      finBL.Error.ErrorBegin(strTemp)
    End If
  End If
  
  ' Return Data
  If Success Then
    Data = New With {
      .OriginalBalanceFuture = AccountRestructure.OriginalBalanceFuture,
      .OriginalBalance = AccountRestructure.OriginalBalance,
      .AccruedInterest = AccountRestructure.AccruedInterest,
      .AccruedInterestCharge = AccountRestructure.AccruedInterestCharge,
      .AccruedDefaultInterest = AccountRestructure.AccruedDefaultInterest,
      .AccruedDefaultInterestCharge = AccountRestructure.AccruedDefaultInterestCharge,
      .AccruedOtherInterest = AccountRestructure.AccruedOtherInterest,
      .AccruedOtherInterestCharge = AccountRestructure.AccruedOtherInterestCharge,
      .UnpostedDefaultFees = AccountRestructure.UnpostedDefaultFees,
      .UnpostedDefaultFeesCharge = AccountRestructure.UnpostedDefaultFeesCharge,
      .UnpostedOverLimitFees = AccountRestructure.UnpostedOverLimitFees,
      .UnpostedOverLimitFeesCharge = AccountRestructure.UnpostedOverLimitFeesCharge,
      .UnpostedFacilityFees = AccountRestructure.UnpostedFacilityFees,
      .UnpostedFacilityFeesCharge = AccountRestructure.UnpostedFacilityFeesCharge,
      .UnpostedStandardTransactions = AccountRestructure.UnpostedStandardTransactions,
      .UnpostedStandardTransactionsCharge = AccountRestructure.UnpostedStandardTransactionsCharge,
      .SuspendInterest = AccountRestructure.SuspendInterest,
      .SuspendDefaultInterest = AccountRestructure.SuspendDefaultInterest,
      .SuspendDefaultFees = AccountRestructure.SuspendDefaultFees,
      .SuspendFacilityFee = AccountRestructure.SuspendFacilityFee,
      .SuspendStandardTransactions = AccountRestructure.SuspendStandardTransactions
    }
  End If
  
  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(Data, returnValue)
  End If
  
  Return Success
                                 
End Function

''' &lt;summary&gt;
'''  Refresh Allocations.
''' &lt;/summary&gt;
Private Function AllocationsRefresh(parametersJson As String,
                                    ByRef returnValue As String) As Boolean

  Dim AccountRestructure As finAccountRestructure
  Dim Data As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  Dim BalanceOverdue As Decimal

  ' Assume Success
  Success = True

  ' Get Account Restructure
  If GetWizardFinishParameters(parametersJson, WizardFinishParameters) Then
    Success = CreateAccountRestructure(AccountRestructure, WizardFinishParameters)
  Else
    Success = False
  End If  
  
  ' Get Allocation information
  If Success Then
    ' Overdue Information
    If AccountRestructure.Account.AccountType Is Nothing Then
      BalanceOverdue = AccountRestructure.NetBalanceOverdueContractual
    Else
      Select Case AccountRestructure.Account.AccountType.DefaultInterestOverdueBasis
        Case isefinDefaultInterestOverdueBasis.Overdue
          BalanceOverdue = AccountRestructure.NetBalanceOverdue
        Case Else
          BalanceOverdue = AccountRestructure.NetBalanceOverdueContractual
      End Select
    End If

    ' Return Data
    Data = New With {
      .NetBalancePrincipalNIB = AccountRestructure.NetBalancePrincipalNIB,
      .NetBalancePrincipalIB = AccountRestructure.NetBalancePrincipalIB,
      .NetBalanceInterest = AccountRestructure.NetBalanceInterest,
      .NetBalanceFeeNIB = AccountRestructure.NetBalanceFeeNIB,
      .NetBalanceFeeIB = AccountRestructure.NetBalanceFeeIB,
      .NetBalance = AccountRestructure.NetBalance,
      .BalancePrincipalNIB = AccountRestructure.BalancePrincipalNIB,
      .BalancePrincipalIB = AccountRestructure.BalancePrincipalIB,
      .BalanceInterest = AccountRestructure.BalanceInterest,
      .BalanceFeeNIB = AccountRestructure.BalanceFeeNIB,
      .BalanceFeeIB = AccountRestructure.BalanceFeeIB,
      .Balance = AccountRestructure.NetBalance,
      .AdjustPrincipalIB = (AccountRestructure.BalancePrincipalIB - AccountRestructure.NetBalancePrincipalIB),
      .AdjustPrincipalNIB = (AccountRestructure.BalancePrincipalNIB - AccountRestructure.NetBalancePrincipalNIB),
      .AdjustFeeIB = (AccountRestructure.BalanceFeeIB - AccountRestructure.NetBalanceFeeIB),
      .AdjustFeeNIB = (AccountRestructure.BalanceFeeNIB - AccountRestructure.NetBalanceFeeNIB),
      .AdjustInterest = (AccountRestructure.BalanceInterest - AccountRestructure.NetBalanceInterest),
      .NetBalanceOverdue = BalanceOverdue,
      .BalanceOverdueCommitted = AccountRestructure.BalanceOverdueFutureAdjustment,
      .BalanceOverdueCurrent = (AccountRestructure.NetBalanceOverdue + AccountRestructure.BalanceOverdueFutureAdjustment),
      .BalanceOverdue = AccountRestructure.BalanceOverdue,
      .AdjustOverdue = (AccountRestructure.BalanceOverdue - AccountRestructure.NetBalanceOverdue)
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Calculate Financials.
''' &lt;/summary&gt;
Private Function Calculate(parametersJson As String,
                           ByRef returnValue As String) As Boolean

  Dim AccountRestructure As finAccountRestructure
  Dim Data As Object
  Dim ErrorAsSummaryPage As Boolean
  Dim Reset As Boolean
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters    
    ErrorAsSummaryPage = .GetBoolean("ErrorAsSummaryPage")
    Reset = .GetBoolean("Reset")    
  End With
  
  ' Get Account Restructure
  If GetWizardFinishParameters(parametersJson, WizardFinishParameters) Then
    Success = CreateAccountRestructure(AccountRestructure, WizardFinishParameters)
  Else
    Success = False
  End If

  ' Reset Financials?
  If Success AndAlso Reset Then
    If AccountRestructure.ResetNew() Then
      AccountRestructure.CalculationNew.PaymentRegularOverride = AccountRestructure.CalculationCurrent.PaymentRegular
    Else 
      Success = False
    End If
  End If
  
  ' Calculate
  If Success Then
    Success = AccountRestructure.CalculateNew()
  End If
  
  ' Return
  If Success Then
    Data = New With {
      .AccountCalcJson = AccountRestructure.CalculationNew.ToHtmlWidgetJsonString(True, False, True, AccountRestructure.RestructureDate),
      .BalanceOverdue = AccountRestructure.BalanceOverdue,
      .RestructureSummaryHtml = finBL.SummaryPageFunctions.AccountRestructureFinancialSummary(False, AccountRestructure, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
    }
  ElseIf ErrorAsSummaryPage Then
    Success = True    
    Data = New With {
      .ErrorHtml = finBL.GetHtmlErrorMessage()
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Commit the Restructure.
''' &lt;/summary&gt;
Private Function Finish(parametersJson As String,
                        ByRef returnValue As String) As Boolean

  Dim AccountLog As finAccountLog
  Dim AccountRestructure As finAccountRestructure
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  Dim Warnings As finWarnings
  Dim LogPk As Integer
  Dim Data As Object

  ' Assume Success
  Success = True

  ' Initialise
  Warnings = finBL.CreateWarnings()

  ' Get Finish Parameters
  If GetWizardFinishParameters(parametersJson, WizardFinishParameters) Then
    Success = CreateAccountRestructure(AccountRestructure, WizardFinishParameters)
  Else
    Success = False
  End If

  ' Calculate
  If Success Then
    Success = AccountRestructure.CalculateNew()
  End If

  ' Commit
  If Success Then
    Success = AccountRestructure.ExecuteCommit()
  End If

  ' Publish Documents
  If Success AndAlso AccountRestructure.PrintAdvice Then
    LogPk = 0

    For Each AccountLog In AccountRestructure.DocumentLogs
      If AccountLog.Publish(isefinLogPublishType.Publish, True) Then
        ' Only download the first document which exists
        If LogPk = 0 AndAlso Len(AccountLog.DocumentFileNameResolved) &lt;&gt; 0 AndAlso finBL.Runtime.FileUtilities.FileExists(AccountLog.DocumentFileNameResolved) Then
          LogPk = AccountLog.Pk
        End If
      Else
        Warnings.AddWarning(finBL.Error.Message(True, False, True))
      End If
    Next
  End If

  ' Return
  If Success Then
    Data = New With {
      .DocumentLogPk = LogPk,
      .Warnings = Warnings.GetSummaryNumbered(,,,, True)
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get the Account Schedule.
''' &lt;/summary&gt;
Private Function GetSchedule(parametersJson As String,
                             ByRef returnValue As String) As Boolean

  Dim AccountRestructure As finAccountRestructure
  Dim Current As Boolean
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Parameters
  With mCombinedParameters
    Current = .GetBoolean("Current")
  End With

  ' Get Account Restructure
  If GetWizardFinishParameters(parametersJson, WizardFinishParameters) Then
    Success = CreateAccountRestructure(AccountRestructure, WizardFinishParameters)
  Else
    Success = False
  End If

  ' Get Schedule Information
  If Success Then
    If Current Then
      returnValue = AccountRestructure.CalculationCurrent.Schedule.ToHtmlWidgetJsonString("Date,ScheduleType,ElementId,Reference,Value,Balance,Notes")
    Else
      If AccountRestructure.CalculateNew() Then
        returnValue = AccountRestructure.CalculationNew.Schedule.ToHtmlWidgetJsonString("Date,ScheduleType,ElementId,Reference,Value,Balance,Notes")
      Else
        Success = False
      End If
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Print Restructure Advice.
''' &lt;/summary&gt;
Private Function PrintAdvice(ByRef returnValue As String) As Boolean

  Dim AccountLog As finAccountLog
  Dim DocumentLogPk As Integer
  Dim FileInfo As finFileDownloadInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  AccountLog = finBL.CreateAccountLog()
  FileInfo = finBL.CreateFileDownloadInfo()

  ' Parameters
  With mCombinedParameters
    DocumentLogPk = .GetInteger("DocumentLogPk")
  End With

  ' Load
  If AccountLog.Load(DocumentLogPk) Then
    Success = FileInfo.LoadFile(AccountLog.DocumentFileNameResolved)
  Else
    Success = False
  End If

  ' Return
  If Success Then
    returnValue = FileInfo.ToXmlString()
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Update Net Balance.
''' &lt;/summary&gt;
Private Function UpdateNetBalance(parametersJson As String,
                                  ByRef returnValue As String) As Boolean

  Dim AccountRestructure As finAccountRestructure
  Dim Data As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  Dim UnpostedTransactions As Decimal
  Dim UnpostedTransactionsValueIsBlank As Boolean

  ' Assume Success
  Success = True

  ' Get Account Restructure
  If GetWizardFinishParameters(parametersJson, WizardFinishParameters) Then
    Success = CreateAccountRestructure(AccountRestructure, WizardFinishParameters)
  Else
    Success = False
  End If

  ' Get Balance
  If Success Then
    ' Unposted Transactions
    If AccountRestructure.UnpostedStandardTransactions &lt;&gt; 0 Then
      If AccountRestructure.UnpostedStandardTransactionsCharge Then
        UnpostedTransactions = AccountRestructure.UnpostedStandardTransactions
      Else
        UnpostedTransactionsValueIsBlank = True
      End If
    End If

    ' Calculate Balance

    ' Return Data
    Data = New With {
      .AccruedInterestCharge = AccountRestructure.AccruedInterestCharge,
      .AccruedInterestBlankTip = finBL.FormatCurrency(AccountRestructure.AccruedInterest, False, False),
      .AccruedDefaultInterestCharge = AccountRestructure.AccruedDefaultInterestCharge,
      .AccruedDefaultInterestBlankTip = finBL.FormatCurrency(AccountRestructure.AccruedDefaultInterest, False, False),
      .AccruedOtherInterestCharge = AccountRestructure.AccruedOtherInterestCharge,
      .AccruedOtherInterestBlankTip = finBL.FormatCurrency(AccountRestructure.AccruedOtherInterest, False, False),
      .UnpostedDefaultFeesCharge = AccountRestructure.UnpostedDefaultFeesCharge,
      .UnpostedDefaultFeesBlankTip = finBL.FormatCurrency(AccountRestructure.UnpostedDefaultFees, False, False),
      .UnpostedOverLimitFeesCharge = AccountRestructure.UnpostedOverLimitFeesCharge,
      .UnpostedOverLimitFeesBlankTip = finBL.FormatCurrency(AccountRestructure.UnpostedOverLimitFees, False, False),
      .UnpostedFacilityFeesCharge = AccountRestructure.UnpostedFacilityFeesCharge,
      .UnpostedFacilityFeesBlankTip = finBL.FormatCurrency(AccountRestructure.UnpostedFacilityFees, False, False),
      .UnpostedTransactions = UnpostedTransactions,
      .UnpostedTransactionsValueIsBlank = UnpostedTransactionsValueIsBlank,
      .BalanceNet = (AccountRestructure.OriginalBalance + AccountRestructure.AccruedInterest + AccountRestructure.AccruedDefaultInterest + AccountRestructure.AccruedOtherInterest + AccountRestructure.UnpostedDefaultFees + AccountRestructure.UnpostedOverLimitFees + AccountRestructure.UnpostedFacilityFees + AccountRestructure.UnpostedStandardTransactions)
    }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Overriding Payments Handling.
''' &lt;/summary&gt;
Private Function OverridingPaymentsHandling(ByRef returnValue As String) As Boolean

  Dim AccountRestructure As finAccountRestructure
  Dim AccountRestructureJson As String
  Dim Action As String
  Dim OverridingPaymentsJson As String
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' Assume Success
  Success = True
  
  ' Get Parameters
  With mCombinedParameters
    Action = .GetString("Action")
    AccountRestructureJson = .GetString("AccountRestructureJson")
    OverridingPaymentsJson = .GetString("OverridingPaymentsJson")
  End With
  
  ' Parse Parameters
  Success = GetWizardFinishParameters(AccountRestructureJson, WizardFinishParameters)
  
  ' Create Account Restructure object and update payments
  If Success Then
    If CreateAccountRestructure(AccountRestructure, WizardFinishParameters) Then
      If AccountRestructure.CalculateNew() Then
        Success = AccountRestructure.CalculationNew.Payments.FromHtmlWidgetJsonString(OverridingPaymentsJson)
      Else 
        Success = False
      End If
    Else 
      Success = False
    End If
  End If  
  
  ' Handle Action
  If Success Then
    Select Case Action
      Case "PaymentsCleanup"
        With AccountRestructure.CalculationNew.Payments
          Success = (.RemoveIgnored() AndAlso .RemoveBlankRegularPayments())
        End With
        
      Case "RegularPaymentsCreate"
        ' Create Payments
        Success = AccountRestructure.RegularPaymentsCreate()
        
      Case Else
        Success = False
        finBL.Error.ErrorBeginFormat("Overriding Payments Action '{0}' is unhandled.", Action)
    End Select   
  End If
  
  ' Return
  If Success Then
    returnValue = AccountRestructure.CalculationNew.Payments.ToHtmlWidgetJsonString()
  End If
  
  Return Success
                                       
End Function



''' &lt;summary&gt;
'''  Wizard Initialisation Information.
''' &lt;/summary&gt;
Public Class FormInitialisationInfo

  ' Account
  Public RecordCode As String
  Public RecordDescription As String
  Public SuspendDefaultFees As Boolean
  Public SuspendDefaultInterest As Boolean
  Public SuspendFacilityFee As Boolean
  Public SuspendInterest As Boolean
  Public SuspendStandardTransactions As Boolean
  Public OtherInterestDescription As String
  Public OverridingPaymentsCountPromises As Integer  
  Public RestructureDateMin As Date
  Public RestructureDateMax As Date

  ' Record
  Public AccountRestructureDetails As AccountRestructureDetails

  ' Workflow
  Public WorkflowId As String
  Public WorkflowDescription As String
  Public WorkflowItemPk As Integer
  
  ' Lists
  Public ByWhomList As String
  Public PaymentCycleList As String
  Public PaymentTypeList As Object

  ' Information Lists

  ' Permissions

  ' Advanced Sections

  ' Global Collections

  ' Configuration
  Public CanChangeFee As Boolean
  Public CanChargeFee As Boolean
  Public FormHeading As String
  Public PromptOnCommit As Boolean
  Public StdTransWidgetId As String
  Public ShowPrintAdvice As Boolean

End Class



''' &lt;summary&gt;
'''  Account Restructure Details.
''' &lt;/summary&gt;
Public Class AccountRestructureDetails

  Public AccountCalcJson As String
  Public AccruedDefaultInterest As Decimal
  Public AccruedDefaultInterestCharge As Boolean
  Public AccruedDefaultInterestOriginal As Decimal
  Public AccruedDefaultInterestSuspended As Boolean
  Public AccruedInterest As Decimal
  Public AccruedInterestCharge As Boolean
  Public AccruedInterestOriginal As Decimal
  Public AccruedInterestSuspended As Boolean
  Public AccruedOtherInterest As Decimal
  Public AccruedOtherInterestAvailable As Boolean
  Public AccruedOtherInterestCharge As Boolean
  Public AccruedOtherInterestOriginal As Decimal
  Public AccruedOtherInterestSuspended As Boolean
  Public BalanceFeeIB As Decimal
  Public BalanceFeeNIB As Decimal
  Public BalanceInterest As Decimal
  Public BalanceOverdue As Decimal
  Public BalanceOverdueContractualFutureAdjustment As Decimal
  Public BalanceOverdueFutureAdjustment As Decimal
  Public BalancePrincipalIB As Decimal
  Public BalancePrincipalNIB As Decimal
  Public FeeAllowChange As Boolean
  Public FeeCharge As Boolean
  Public FeeElementId As String
  Public FeeValue As Decimal
  Public FeeValueResolved As Decimal
  Public NetBalance As Decimal
  Public NetBalanceFeeIB As Decimal
  Public NetBalanceFeeNIB As Decimal
  Public NetBalanceInterest As Decimal
  Public NetBalanceOverdue As Decimal
  Public NetBalanceOverdueContractual As Decimal
  Public NetBalancePrincipalIB As Decimal
  Public NetBalancePrincipalNIB As Decimal
  Public OriginalBalance As Decimal
  Public OriginalBalanceFeeIB As Decimal
  Public OriginalBalanceFeeNIB As Decimal
  Public OriginalBalanceFuture As Decimal
  Public OriginalBalanceInterest As Decimal
  Public OriginalBalanceOverdue As Decimal
  Public OriginalBalanceOverdueContractual As Decimal
  Public OriginalBalancePrincipalIB As Decimal
  Public OriginalBalancePrincipalNIB As Decimal
  Public OriginalCreditLimit1 As Decimal
  Public OriginalCreditLimit2 As Decimal
  Public OriginalCreditLimit3 As Decimal
  Public OriginalDefaultInterestRate As Double
  Public OriginalDefaultInterestRateBasis As String
  Public OriginalOtherInterestRate As Double
  Public PaymentMethodIsDirectDebit As Boolean
  Public PrintAdvice As Boolean
  Public RestructureByWhom As String
  Public RestructureDate As Date
  Public RestructureReason As String
  Public RestructureType As String
  Public SuspendDefaultFees As Boolean
  Public SuspendDefaultInterest As Boolean
  Public SuspendFacilityFee As Boolean
  Public SuspendInterest As Boolean
  Public SuspendStandardTransactions As Boolean
  Public UnpostedDefaultFees As Decimal
  Public UnpostedDefaultFeesAvailable As Boolean
  Public UnpostedDefaultFeesCharge As Boolean
  Public UnpostedDefaultFeesOriginal As Decimal
  Public UnpostedDefaultFeesResolved As Decimal
  Public UnpostedDefaultFeesSuspended As Boolean
  Public UnpostedFacilityFees As Decimal
  Public UnpostedFacilityFeesAvailable As Boolean
  Public UnpostedFacilityFeesCharge As Boolean
  Public UnpostedFacilityFeesOriginal As Decimal
  Public UnpostedFacilityFeesResolved As Decimal
  Public UnpostedFacilityFeesSuspended As Boolean
  Public UnpostedOverLimitFees As Decimal
  Public UnpostedOverLimitFeesAvailable As Boolean
  Public UnpostedOverLimitFeesCharge As Boolean
  Public UnpostedOverLimitFeesOriginal As Decimal
  Public UnpostedOverLimitFeesResolved As Decimal
  Public UnpostedOverLimitFeesSuspended As Boolean
  Public UnpostedStandardTransactions As Decimal
  Public UnpostedStandardTransactionsCharge As Boolean
  Public UnpostedStandardTransactionsResolved As Decimal
  Public UnpostedStandardTransactionsSuspended As Boolean
  Public WorkflowId As String

  Public Sub New()
  End Sub

  Public Sub New(accountRestructure As finAccountRestructure)

    With accountRestructure
      Me.AccountCalcJson = .CalculationNew.ToHtmlWidgetJsonString(True, False, True, accountRestructure.RestructureDate)
      Me.AccruedDefaultInterest = .AccruedDefaultInterest
      Me.AccruedDefaultInterestCharge = .AccruedDefaultInterestCharge
      Me.AccruedDefaultInterestOriginal = .AccruedDefaultInterestOriginal
      Me.AccruedDefaultInterestSuspended = .AccruedDefaultInterestSuspended
      Me.AccruedInterest = .AccruedInterest
      Me.AccruedInterestCharge = .AccruedInterestCharge
      Me.AccruedInterestOriginal = .AccruedInterestOriginal
      Me.AccruedInterestSuspended = .AccruedInterestSuspended
      Me.AccruedOtherInterest = .AccruedOtherInterest
      Me.AccruedOtherInterestAvailable = .AccruedOtherInterestAvailable
      Me.AccruedOtherInterestCharge = .AccruedOtherInterestCharge
      Me.AccruedOtherInterestOriginal = .AccruedOtherInterestOriginal
      Me.AccruedOtherInterestSuspended = .AccruedOtherInterestSuspended
      Me.BalanceFeeIB = .BalanceFeeIB
      Me.BalanceFeeNIB = .BalanceFeeNIB
      Me.BalanceInterest = .BalanceInterest
      Me.BalanceOverdue = .BalanceOverdue
      Me.BalanceOverdueContractualFutureAdjustment = .BalanceOverdueContractualFutureAdjustment
      Me.BalanceOverdueFutureAdjustment = .BalanceOverdueFutureAdjustment
      Me.BalancePrincipalIB = .BalancePrincipalIB
      Me.BalancePrincipalNIB = .BalancePrincipalNIB
      Me.FeeAllowChange = .FeeAllowChange
      Me.FeeCharge = .FeeCharge
      Me.FeeElementId = .FeeElementId
      Me.FeeValue = .FeeValue
      Me.FeeValueResolved = .FeeValueResolved
      Me.NetBalance = .NetBalance
      Me.NetBalanceFeeIB = .NetBalanceFeeIB
      Me.NetBalanceFeeNIB = .NetBalanceFeeNIB
      Me.NetBalanceInterest = .NetBalanceInterest
      Me.NetBalanceOverdue = .NetBalanceOverdue
      Me.NetBalanceOverdueContractual = .NetBalanceOverdueContractual
      Me.NetBalancePrincipalIB = .NetBalancePrincipalIB
      Me.NetBalancePrincipalNIB = .NetBalancePrincipalNIB
      Me.OriginalBalance = .OriginalBalance
      Me.OriginalBalanceFeeIB = .OriginalBalanceFeeIB
      Me.OriginalBalanceFeeNIB = .OriginalBalanceFeeNIB
      Me.OriginalBalanceFuture = .OriginalBalanceFuture
      Me.OriginalBalanceInterest = .OriginalBalanceInterest
      Me.OriginalBalanceOverdue = .OriginalBalanceOverdue
      Me.OriginalBalanceOverdueContractual = .OriginalBalanceOverdueContractual
      Me.OriginalBalancePrincipalIB = .OriginalBalancePrincipalIB
      Me.OriginalBalancePrincipalNIB = .OriginalBalancePrincipalNIB
      Me.OriginalCreditLimit1 = .OriginalCreditLimit1
      Me.OriginalCreditLimit2 = .OriginalCreditLimit2
      Me.OriginalCreditLimit3 = .OriginalCreditLimit3
      Me.OriginalDefaultInterestRate = .OriginalDefaultInterestRate
      Me.OriginalDefaultInterestRateBasis = .OriginalDefaultInterestRateBasisText
      Me.OriginalOtherInterestRate = .OriginalOtherInterestRate      
      Me.PaymentMethodIsDirectDebit = .PaymentMethodIsDirectDebit
      Me.PrintAdvice = .PrintAdvice
      Me.RestructureByWhom = .RestructureByWhom
      Me.RestructureDate = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.RestructureDate)
      Me.RestructureReason = .RestructureReason
      Me.RestructureType = .RestructureType
      Me.SuspendDefaultFees = .SuspendDefaultFees
      Me.SuspendDefaultInterest = .SuspendDefaultInterest
      Me.SuspendFacilityFee = .SuspendFacilityFee
      Me.SuspendInterest = .SuspendInterest
      Me.SuspendStandardTransactions = .SuspendStandardTransactions
      Me.UnpostedDefaultFees = .UnpostedDefaultFees
      Me.UnpostedDefaultFeesAvailable = .UnpostedDefaultFeesAvailable
      Me.UnpostedDefaultFeesCharge = .UnpostedDefaultFeesCharge
      Me.UnpostedDefaultFeesOriginal = .UnpostedDefaultFeesOriginal
      Me.UnpostedDefaultFeesResolved = .UnpostedDefaultFeesResolved
      Me.UnpostedDefaultFeesSuspended = .UnpostedDefaultFeesSuspended
      Me.UnpostedFacilityFees = .UnpostedFacilityFees
      Me.UnpostedFacilityFeesAvailable = .UnpostedFacilityFeesAvailable
      Me.UnpostedFacilityFeesCharge = .UnpostedFacilityFeesCharge
      Me.UnpostedFacilityFeesOriginal = .UnpostedFacilityFeesOriginal
      Me.UnpostedFacilityFeesResolved = .UnpostedFacilityFeesResolved
      Me.UnpostedFacilityFeesSuspended = .UnpostedFacilityFeesSuspended
      Me.UnpostedOverLimitFees = .UnpostedOverLimitFees
      Me.UnpostedOverLimitFeesAvailable = .UnpostedOverLimitFeesAvailable
      Me.UnpostedOverLimitFeesCharge = .UnpostedOverLimitFeesCharge
      Me.UnpostedOverLimitFeesOriginal = .UnpostedOverLimitFeesOriginal
      Me.UnpostedOverLimitFeesResolved = .UnpostedOverLimitFeesResolved
      Me.UnpostedOverLimitFeesSuspended = .UnpostedOverLimitFeesSuspended
      Me.UnpostedStandardTransactions = .UnpostedStandardTransactions
      Me.UnpostedStandardTransactionsCharge = .UnpostedStandardTransactionsCharge
      Me.UnpostedStandardTransactionsResolved = .UnpostedStandardTransactionsResolved
      Me.UnpostedStandardTransactionsSuspended = .UnpostedStandardTransactionsSuspended
      Me.WorkflowId = .WorkflowId
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Wizard Finish Parameters.
''' &lt;/summary&gt;
Public Class WizardFinishParameters

  Public RestructureDate As Date
	Public RestructureByWhom As String
	Public RestructureType As String
	Public RestructureReason As String

	Public FeeChargeFee As Boolean
	Public FeeValue As Decimal

	Public PrintAdvice As Boolean
	Public CreateLog As Boolean

	Public AccruedInterest As Decimal
	Public AccruedInterestCharge As Boolean
	Public AccruedDefaultInterest As Decimal
	Public AccruedDefaultInterestCharge As Boolean
	Public AccruedOtherInterest As Decimal
	Public AccruedOtherInterestCharge As Boolean
	Public UnpostedDefaultFees As Decimal
	Public UnpostedDefaultFeesCharge As Boolean
	Public UnpostedOverLimitFees As Decimal
	Public UnpostedOverLimitFeesCharge As Boolean
	Public UnpostedFacilityFees As Decimal
	Public UnpostedFacilityFeesCharge As Boolean
	Public UnpostedStandardTransactionsCharge As Boolean

  Public BalancePrincipalNIB As Decimal
  Public BalancePrincipalIB As Decimal
  Public BalanceInterest As Decimal
  Public BalanceFeeNIB As Decimal
  Public BalanceFeeIB As Decimal
  Public BalanceOverdue As Decimal

	Public SuspendInterest As Boolean
	Public SuspendDefaultInterest As Boolean
	Public SuspendDefaultFees As Boolean
	Public SuspendFacilityFee As Boolean
	Public SuspendStandardTransactions As Boolean

  Public AccountCalcJson As String
  Public PromisesJson As String

  ' Other
  Public InitialAccrualsLoad As Boolean
  Public InitialAllocationsLoad As Boolean

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

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

  &lt;!-- HTML Widget Styles --&gt;
  &lt;style type="text/less"&gt;
    #tblManualAllocation {
      border-collapse:collapse;
      border-radius:4px;
      margin:4px 0 8px 4px;

      td, th {
        padding:4px;
      }

      thead {
        td {
          background-color:#F0F0F0;
          font-weight:bold;
          text-align:right;
        }
      }

      tbody {
        th {
          text-align:left;
        }

        td:nth-child(2), td:last-child {
          min-width:6em;
          text-align:right;
        }

        tr:nth-child(even) {
          background-color:#FAFAFA;
        }

        tr:last-child {
          td:nth-child(3) {
            text-align:right;
            padding-right:8px;
          }
        }
      }

      tfoot {
        background-color:#FFE5BF;
        color:#000080;
        font-weight:bold;

        th {
          text-align:left;
        }

        td {
          text-align:right;
        }

        tr:last-child {
          td:nth-child(3) {
            padding-right:8px;
          }
        }
      }
    }

    .negative-allocation {
      color:red;
    }

    label.is-label-information {
      display:inline-block;
      margin-left:4px;
    }

    /* Finacial page (used in conjunction with widget.css) */
    #pageFinancial &gt; div {
      display:flex;
      flex-direction:column;
      overflow:hidden;

      &gt; div:first-child {
        position:relative;
        overflow:auto;
        flex-grow:2;
        flex-shrink:0;
      }

      &gt; div:last-child {
        position:relative;
        overflow:auto;
        flex-grow:1;
        flex-shrink:0;
      }
    }

    /* Small device portrait */
    @media screen and (max-width:640px) {
    #pageFinancial &gt; div {
      &gt; div:first-child {
        height:60%;
        overflow:hidden;
      }

      &gt; div:last-child {
        height:40%;
      }
    }
    }
  &lt;/style&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;Account Restructure&lt;/div&gt;
    &lt;div class="summary"&gt;Enter Account details.&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General" tooltipText="Restructure details."&gt;Restructure&lt;/li&gt;
        &lt;li tabId="Accruals" tooltipText="Update Accruals and other charges."&gt;Accruals&lt;/li&gt;
        &lt;li tabId="Allocations" tooltipText="Update Balance Allocations if necessary."&gt;Balance Allocations&lt;/li&gt;
        &lt;li tabId="Financial" tooltipText="Enter Financial information."&gt;Financial&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" class="is-tab-page"&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="lblAccountRestructure"&gt;Account to Restructure&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccount"&gt;Account:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccount" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblWorkflow"&gt;Workflow details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboWorkflow"&gt;Workflow:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboWorkflow" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblRestructureDate"&gt;Enter the effective date of the Restructure&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateRestructureDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateRestructureDate" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRestructureByWhom"&gt;By Whom:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRestructureByWhom" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRestructureType"&gt;Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRestructureType" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtRestructureReason"&gt;Reason:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRestructureReason" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblFee"&gt;Charge a fee?&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkFeeChargeFee" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="numFeeValue"&gt;Fee:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numFeeValue" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblOtherOptions"&gt;Other options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkPrintAdvice" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkCreateLog" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Accruals --&gt;
    &lt;div id="pageAccruals" class="is-tab-page"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:12em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblAccountBalance"&gt;Account Balance&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numBalanceCurrent"&gt;Current&amp;nbsp;Balance:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numBalanceCurrent" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numBalanceCommitted"&gt;less&amp;nbsp;Committed&amp;nbsp;Transactions:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numBalanceCommitted" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numBalanceRestructure"&gt;Restructure&amp;nbsp;Balance:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;
            &lt;input id="numBalanceRestructure" /&gt;
            &lt;button id="cmdScheduleCurrent" class="is-button small"&gt;Schedule&lt;/button&gt;
          &lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblAccrualTransactions"&gt;Plus Accruals and Transactions not yet posted&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numAccruedInterest"&gt;Accrued&amp;nbsp;Interest:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;
            &lt;input id="numAccruedInterest" /&gt;
            &lt;input id="chkAccruedInterestCharge" type="checkbox" /&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numAccruedDefaultInterest"&gt;Accrued&amp;nbsp;Default&amp;nbsp;Interest:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;
            &lt;input id="numAccruedDefaultInterest" /&gt;
            &lt;input id="chkAccruedDefaultInterestCharge" type="checkbox" /&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numAccruedOtherInterest"&gt;Accrued&amp;nbsp;Other&amp;nbsp;Interest:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;
            &lt;input id="numAccruedOtherInterest" /&gt;
            &lt;input id="chkAccruedOtherInterestCharge" type="checkbox" /&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numUnpostedDefaultFees"&gt;Unposted&amp;nbsp;Default&amp;nbsp;Fees:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;
            &lt;input id="numUnpostedDefaultFees" /&gt;
            &lt;input id="chkUnpostedDefaultFeesCharge" type="checkbox" /&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numUnpostedOverLimitFees"&gt;Unposted&amp;nbsp;Over&amp;nbsp;Limit&amp;nbsp;Fees:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;
            &lt;input id="numUnpostedOverLimitFees" /&gt;
            &lt;input id="chkUnpostedOverLimitFeesCharge" type="checkbox" /&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numUnpostedFacilityFees"&gt;Unposted&amp;nbsp;Facility&amp;nbsp;Fees:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;
            &lt;input id="numUnpostedFacilityFees" /&gt;
            &lt;input id="chkUnpostedFacilityFeesCharge" type="checkbox" /&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numUnpostedStandardTransactions"&gt;Unposted&amp;nbsp;Transactions:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;
            &lt;input id="numUnpostedStandardTransactions" /&gt;
            &lt;input id="chkUnpostedStandardTransactionsCharge" type="checkbox" /&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numBalanceNet"&gt;Net&amp;nbsp;Restructure&amp;nbsp;Balance:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numBalanceNet" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSuspension"&gt;Unsuspend items as required&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkSuspendInterest" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkSuspendDefaultInterest" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkSuspendDefaultFees" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2" class="indent1"&gt;&lt;input id="chkSuspendFacilityFee" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkSuspendStandardTransactions" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Allocations --&gt;
    &lt;div id="pageAllocations" class="is-tab-page"&gt;
      &lt;table id="tblManualAllocation"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:8em;"/&gt;
          &lt;col style="width:10em;"/&gt;
          &lt;col /&gt;
          &lt;col style="width:1em;"/&gt;
          &lt;col style="width:10em;"/&gt;
        &lt;/colgroup&gt;

        &lt;thead&gt;
          &lt;tr&gt;
            &lt;td&gt;&lt;/td&gt;
            &lt;td&gt;&lt;/td&gt;
            &lt;td style="text-align:center"&gt;+/-&lt;/td&gt;
            &lt;td&gt;&lt;/td&gt;
            &lt;td&gt;New&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/thead&gt;

        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label&gt;Principal NIB:&lt;/label&gt;&lt;/th&gt;
            &lt;td ng-bind="widget.FormatCurrency(mRecord_DefaultAllocations.BalancePrincipalNIB, true, false)" ng-class="mRecord_DefaultAllocations.BalancePrincipalNIB &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
            &lt;td&gt;&lt;input id="numPnibAllocated" /&gt;&lt;/td&gt;
            &lt;td&gt;&lt;button id="cmdAllocatePnib" class="is-button small icon" icon="Arrow_Left" tabindex="-1"&gt;&lt;/button&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mRecord_DefaultAllocations.NewPrincipalNIB, true, false)" ng-class="mRecord_DefaultAllocations.NewPrincipalNIB &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label&gt;Principal:&lt;/label&gt;&lt;/th&gt;
            &lt;td ng-bind="widget.FormatCurrency(mRecord_DefaultAllocations.BalancePrincipalIB, true, false)" ng-class="mRecord_DefaultAllocations.BalancePrincipalIB &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
            &lt;td&gt;&lt;input id="numPibAllocated" /&gt;&lt;/td&gt;
            &lt;td&gt;&lt;button id="cmdAllocatePib" class="is-button small icon" icon="Arrow_Left" tabindex="-1"&gt;&lt;/button&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mRecord_DefaultAllocations.NewPrincipalIB, true, false)" ng-class="mRecord_DefaultAllocations.NewPrincipalIB &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label&gt;Interest:&lt;/label&gt;&lt;/th&gt;
            &lt;td ng-bind="widget.FormatCurrency(mRecord_DefaultAllocations.BalanceInterest, true, false)" ng-class="mRecord_DefaultAllocations.BalanceInterest &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
            &lt;td&gt;&lt;input id="numIAllocated" /&gt;&lt;/td&gt;
            &lt;td&gt;&lt;button id="cmdAllocateI" class="is-button small icon" icon="Arrow_Left" tabindex="-1"&gt;&lt;/button&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mRecord_DefaultAllocations.NewInterest, true, false)" ng-class="mRecord_DefaultAllocations.NewInterest &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label&gt;Fee NIB:&lt;/label&gt;&lt;/th&gt;
            &lt;td ng-bind="widget.FormatCurrency(mRecord_DefaultAllocations.BalanceFeeNIB, true, false)" ng-class="mRecord_DefaultAllocations.BalanceFeeNIB &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
            &lt;td&gt;&lt;input id="numFnibAllocated" /&gt;&lt;/td&gt;
            &lt;td&gt;&lt;button id="cmdAllocateFnib" class="is-button small icon" icon="Arrow_Left" tabindex="-1"&gt;&lt;/button&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mRecord_DefaultAllocations.NewFeeNIB, true, false)" ng-class="mRecord_DefaultAllocations.NewFeeNIB &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label&gt;Fee:&lt;/label&gt;&lt;/th&gt;
            &lt;td ng-bind="widget.FormatCurrency(mRecord_DefaultAllocations.BalanceFeeIB, true, false)" ng-class="mRecord_DefaultAllocations.BalanceFeeIB &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
            &lt;td&gt;&lt;input id="numFibAllocated" /&gt;&lt;/td&gt;
            &lt;td&gt;&lt;button id="cmdAllocateFib" class="is-button small icon" icon="Arrow_Left" tabindex="-1"&gt;&lt;/button&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mRecord_DefaultAllocations.NewFeeIB, true, false)" ng-class="mRecord_DefaultAllocations.NewFeeIB &lt; 0 ? 'negative-allocation' : ''"&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;

        &lt;tfoot&gt;
          &lt;tr&gt;
            &lt;th&gt;Totals:&lt;/th&gt;
            &lt;td ng-bind="widget.FormatCurrency(mRecord_DefaultAllocations.TotalBalance, true, false)"&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mRecord_DefaultAllocations.TotalAllocations, true, false)"&gt;&lt;/td&gt;
            &lt;td&gt;&lt;/td&gt;
            &lt;td ng-bind="widget.FormatCurrency(mRecord_DefaultAllocations.TotalNew, true, false)"&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tfoot&gt;
      &lt;/table&gt;

      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:12em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblOverdueBalance"&gt;Overdue Balance&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numBalanceOverdueCurrent"&gt;Current&amp;nbsp;Overdue&amp;nbsp;Balance:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numBalanceOverdueCurrent" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numBalanceOverdueCommitted"&gt;less&amp;nbsp;Committed&amp;nbsp;Overdue:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numBalanceOverdueCommitted" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numNetBalanceOverdue"&gt;Restructure&amp;nbsp;Overdue:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numNetBalanceOverdue" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numAdjustOverdue"&gt;Adjustment:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numAdjustOverdue" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numBalanceOverdue"&gt;Net&amp;nbsp;Restructure&amp;nbsp;Overdue:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numBalanceOverdue" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Financial --&gt;
    &lt;div id="pageFinancial" class="is-tab-page"&gt;
      &lt;div class="is-dock-fill"&gt;
        &lt;div&gt;
          &lt;table class="is-form"&gt;
            &lt;tbody id="afFinancial"&gt;&lt;/tbody&gt;
          &lt;/table&gt;
        &lt;/div&gt;
        &lt;div id="wbAccountSummary"&gt;&lt;/div&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="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;
// Record
var mRecord;
var mRecord_AccountRestructure;
var mRecord_DefaultAllocations;

// Controls
var C = {
  //   General
  lblAccountRestructure: null,
  cboAccount: null,

  lblWorkflow: null,
  cboWorkflow: null,

  lblRestructureDate: null,
  dateRestructureDate: null,
  cboRestructureByWhom: null,
  cboRestructureType: null,
  txtRestructureReason: null,

  lblFee: null,
  chkFeeChargeFee: null,
  numFeeValue: null,

  lblOtherOptions: null,
  chkPrintAdvice: null,
  chkCreateLog: null,

  //   Accruals
  lblAccountBalance: null,
  numBalanceCurrent: null,
  numBalanceCommitted: null,
  numBalanceRestructure: null,

  lblAccrualTransactions: null,
  numAccruedInterest: null,
  chkAccruedInterestCharge: null,
  numAccruedDefaultInterest: null,
  chkAccruedDefaultInterestCharge: null,
  numAccruedOtherInterest: null,
  chkAccruedOtherInterestCharge: null,
  numUnpostedDefaultFees: null,
  chkUnpostedDefaultFeesCharge: null,
  numUnpostedOverLimitFees: null,
  chkUnpostedOverLimitFeesCharge: null,
  numUnpostedFacilityFees: null,
  chkUnpostedFacilityFeesCharge: null,
  numUnpostedStandardTransactions: null,
  chkUnpostedStandardTransactionsCharge: null,
  numBalanceNet: null,

  lblSuspension: null,
  chkSuspendInterest: null,
  chkSuspendDefaultInterest: null,
  chkSuspendDefaultFees: null,
  chkSuspendFacilityFee: null,
  chkSuspendStandardTransactions: null,

  //   Allocations
  tblManualAllocation: null,
  numPnibAllocated: null,
  numPibAllocated: null,
  numIAllocated: null,
  numFnibAllocated: null,
  numFibAllocated: null,

  lblOverdueBalance: null,
  numBalanceOverdueCurrent: null,
  numBalanceOverdueCommitted: null,
  numNetBalanceOverdue: null,
  numAdjustOverdue: null,
  numBalanceOverdue: null,

  //   Financial
  afFinancial: null,
  wbAccountSummary: null,
}

// Form
var frmMain;
var tabWizard;

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

var cmdScheduleCurrent;

var cmdAllocatePnib;
var cmdAllocatePib;
var cmdAllocateI;
var cmdAllocateFnib;
var cmdAllocateFib;

// Other
var mTimer;
var mCalculationTimer;
var mCalculationRequired;
var mReCalcAllocations;

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

  // --------
  // Controls
  // --------
  //   General
  C.lblAccountRestructure = widget.UI.Label("lblAccountRestructure", {});
  C.cboAccount = widget.UI.DBCombo("cboAccount", {
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });

  C.lblWorkflow = widget.UI.Label("lblWorkflow", {});
  C.cboWorkflow = widget.UI.DBCombo("cboWorkflow", {
    allowBlank: true,
    autoReadOnly: false,
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });

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

    onChange: dateRestructureDate_Change,
  });
  C.cboRestructureByWhom = widget.UI.ComboBox("cboRestructureByWhom", {
    allowBlank: false,
    maxLength: 50,
  });
  C.cboRestructureType = widget.UI.InformationListComboBox("cboRestructureType", {
    maxLength: 50,
  });
  C.txtRestructureReason = widget.UI.TextBox("txtRestructureReason", {
    multiLine: true,
    rows: 6,
  });

  C.lblFee = widget.UI.Label("lblFee", {});
  C.chkFeeChargeFee = widget.UI.CheckBox("chkFeeChargeFee", {
    caption: "Charge Fee?",

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

  C.lblOtherOptions = widget.UI.Label("lblOtherOptions", {});
  C.chkPrintAdvice = widget.UI.CheckBox("chkPrintAdvice", {
    caption: "Print Restructure advice?",
  });
  C.chkCreateLog = widget.UI.CheckBox("chkCreateLog", {
    caption: "Create Log?",
  });

  //   Accruals
  C.lblAccountBalance = widget.UI.Label("lblAccountBalance", {});
  C.numBalanceCurrent = widget.UI.NumberBox("numBalanceCurrent", {
    fontBold: true,
    readOnly: true,
  });
  C.numBalanceCommitted = widget.UI.NumberBox("numBalanceCommitted", {
    readOnly: true,
  });
  C.numBalanceRestructure = widget.UI.NumberBox("numBalanceRestructure", {
    fontBold: true,
    readOnly: true,
  });

  C.lblAccrualTransactions = widget.UI.Label("lblAccrualTransactions", {});
  C.numAccruedInterest = widget.UI.NumberBox("numAccruedInterest", {
    onChange: UpdateNetBalance_Pre,
  });
  C.chkAccruedInterestCharge = widget.UI.CheckBox("chkAccruedInterestCharge", {
    caption: "Charge?",

    onChange: UpdateNetBalance_Pre,
  });
  C.numAccruedDefaultInterest = widget.UI.NumberBox("numAccruedDefaultInterest", {
    onChange: UpdateNetBalance_Pre,
  });
  C.chkAccruedDefaultInterestCharge = widget.UI.CheckBox("chkAccruedDefaultInterestCharge", {
    caption: "Charge?",

    onChange: UpdateNetBalance_Pre,
  });
  C.numAccruedOtherInterest = widget.UI.NumberBox("numAccruedOtherInterest", {
    onChange: UpdateNetBalance_Pre,
  });
  C.chkAccruedOtherInterestCharge = widget.UI.CheckBox("chkAccruedOtherInterestCharge", {
    caption: "Charge?",

    onChange: UpdateNetBalance_Pre,
  });
  C.numUnpostedDefaultFees = widget.UI.NumberBox("numUnpostedDefaultFees", {
    onChange: UpdateNetBalance_Pre,
  });
  C.chkUnpostedDefaultFeesCharge = widget.UI.CheckBox("chkUnpostedDefaultFeesCharge", {
    caption: "Charge?",

    onChange: UpdateNetBalance_Pre,
  });
  C.numUnpostedOverLimitFees = widget.UI.NumberBox("numUnpostedOverLimitFees", {
    onChange: UpdateNetBalance_Pre,
  });
  C.chkUnpostedOverLimitFeesCharge = widget.UI.CheckBox("chkUnpostedOverLimitFeesCharge", {
    caption: "Charge?",

    onChange: UpdateNetBalance_Pre,
  });
  C.numUnpostedFacilityFees = widget.UI.NumberBox("numUnpostedFacilityFees", {
    onChange: UpdateNetBalance_Pre,
  });
  C.chkUnpostedFacilityFeesCharge = widget.UI.CheckBox("chkUnpostedFacilityFeesCharge", {
    caption: "Charge?",

    onChange: UpdateNetBalance_Pre,
  });
  C.numUnpostedStandardTransactions = widget.UI.NumberBox("numUnpostedStandardTransactions", {
    readOnly: true,

    onChange: UpdateNetBalance_Pre,
  });
  C.chkUnpostedStandardTransactionsCharge = widget.UI.CheckBox("chkUnpostedStandardTransactionsCharge", {
    caption: "Charge?",

    onChange: UpdateNetBalance_Pre,
  });
  C.numBalanceNet = widget.UI.NumberBox("numBalanceNet", {
    fontBold: true,
    readOnly: true,
  });

  C.lblSuspension = widget.UI.Label("lblSuspension", {});
  C.chkSuspendInterest = widget.UI.CheckBox("chkSuspendInterest", {
    caption: "Interest",
  });
  C.chkSuspendDefaultInterest = widget.UI.CheckBox("chkSuspendDefaultInterest", {
    caption: "Default Interest",
  });
  C.chkSuspendDefaultFees = widget.UI.CheckBox("chkSuspendDefaultFees", {
    caption: "Default and Over Limit Fees",
  });
  C.chkSuspendFacilityFee = widget.UI.CheckBox("chkSuspendFacilityFee", {
    caption: "Facility Fee",
  });
  C.chkSuspendStandardTransactions = widget.UI.CheckBox("chkSuspendStandardTransactions", {
    caption: "Standard Transactions",
  });

  //   Allocations
  C.tblManualAllocation = $("#tblManualAllocation");
  C.numPnibAllocated = widget.UI.NumberBox("numPnibAllocated", {
    blankIfZero: true,

    onChange: UpdateAllocationTotals,
  });
  C.numPibAllocated = widget.UI.NumberBox("numPibAllocated", {
    blankIfZero: true,

    onChange: UpdateAllocationTotals,
  });
  C.numIAllocated = widget.UI.NumberBox("numIAllocated", {
    blankIfZero: true,

    onChange: UpdateAllocationTotals,
  });
  C.numFnibAllocated = widget.UI.NumberBox("numFnibAllocated", {
    blankIfZero: true,

    onChange: UpdateAllocationTotals,
  });
  C.numFibAllocated = widget.UI.NumberBox("numFibAllocated", {
    blankIfZero: true,

    onChange: UpdateAllocationTotals,
  });

  C.lblOverdueBalance = widget.UI.Label("lblOverdueBalance", {});
  C.numBalanceOverdueCurrent = widget.UI.NumberBox("numBalanceOverdueCurrent", {
    fontBold: true,
    readOnly: true,
  });
  C.numBalanceOverdueCommitted = widget.UI.NumberBox("numBalanceOverdueCommitted", {
    readOnly: true,
  });
  C.numNetBalanceOverdue = widget.UI.NumberBox("numNetBalanceOverdue", {
    fontBold: true,
    readOnly: true,
  });
  C.numAdjustOverdue = widget.UI.NumberBox("numAdjustOverdue", {
    onChange: numAdjustOverdue_Change,
  });
  C.numBalanceOverdue = widget.UI.NumberBox("numBalanceOverdue", {
    fontBold: true,

    onButtonClick: numBalanceOverdue_ButtonClick,
    onChange: numBalanceOverdue_Change,
  });
  C.numBalanceOverdue.ButtonsDefine([{ id: "Clear", tooltipText: "Clear Overdue", icon: "Clear" }]);

  //   Financial
  C.afFinancial = widget.UI.AccountFinancial("afFinancial", {
    visible: false, // Hide until first calculated
    isRestructure: true,
    onAction: afFinancial_Action,
    onChange: afFinancial_Change,
  });
  C.wbAccountSummary = widget.UI.PreviewPane("wbAccountSummary", {});

  // Create Widget form
  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(function() { Form_ExecuteAction("Cancel"); });
  cmdBack.click(function() { tabWizard_Move(-1); });
  cmdNext.click(function() { tabWizard_Move(1); });
  cmdFinish.click(function() { Form_ExecuteAction("Finish"); });

  cmdScheduleCurrent = $("#cmdScheduleCurrent");
  cmdScheduleCurrent.click(function() { ShowSchedule(true); });

  cmdAllocatePnib = $("#cmdAllocatePnib");
  cmdAllocatePib = $("#cmdAllocatePib");
  cmdAllocateI = $("#cmdAllocateI");
  cmdAllocateFnib = $("#cmdAllocateFnib");
  cmdAllocateFib = $("#cmdAllocateFib");
  cmdAllocatePnib.click(function() { AllocateBalanceTo("PNIB"); });
  cmdAllocatePib.click(function() { AllocateBalanceTo("PIB"); });
  cmdAllocateI.click(function() { AllocateBalanceTo("I"); });
  cmdAllocateFnib.click(function() { AllocateBalanceTo("FNIB"); });
  cmdAllocateFib.click(function() { AllocateBalanceTo("FIB"); });

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // Defaults

  // Other

  // 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_AccountRestructure = null;
  mRecord_DefaultAllocations = null;
  mCalculationRequired = true;
  mReCalcAllocations = true;

  // Hide content
  frmMain.Visible(false);

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

  // Load Initialisation details
  widget.GetString("GetInitialisationInfo", {},
    // Success
    function (data) {
      mRecord = JSON.parse(data);
      mRecord_AccountRestructure = mRecord.AccountRestructureDetails;

      // Global Collections

      // Give Collections ability to lookup by code

      // Enhance lists
      widget.ArrayToCodeDescriptionList(mRecord.PaymentTypeList);

      // Load Fields
      Fields_Load();
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboAccount.RefreshUnbound(mRecord.RecordCode, mRecord.RecordDescription);
    
    C.cboWorkflow.RefreshUnbound(mRecord.WorkflowId, mRecord.WorkflowDescription);
  }

  if (mRecord_AccountRestructure) {
    // General
    C.dateRestructureDate.Value(mRecord_AccountRestructure.RestructureDate);        
    C.cboRestructureByWhom.Text(mRecord_AccountRestructure.RestructureByWhom);
    C.cboRestructureType.Text(mRecord_AccountRestructure.RestructureType);
    C.txtRestructureReason.Text(mRecord_AccountRestructure.RestructureReason);

    C.chkFeeChargeFee.Value(mRecord_AccountRestructure.FeeCharge);
    C.numFeeValue.Value(mRecord_AccountRestructure.FeeValue);

    C.chkPrintAdvice.Value(mRecord_AccountRestructure.PrintAdvice &amp;&amp; mRecord.ShowPrintAdvice);
    C.chkCreateLog.Value(mRecord_AccountRestructure.LogCreate);

    // Accruals
    UpdateAccruals();

    // Financial
    C.afFinancial.FromAccountCalcJson(mRecord_AccountRestructure.AccountCalcJson, "", mRecord.RecordCode);
    C.afFinancial.Visible(true);        
  }

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

  // Update Controls
  chkFeeChargeFee_Change();
  numAdjustOverdue_Change();

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // Not used by this HTML Widget
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    widget.SetHeading(mRecord.FormHeading);
  }

  // Information Lists
  if (mRecord) {
    C.cboRestructureType.SetComboFromInformationList("AccountRestructureType");
  }

  // Lists
  if (mRecord) {
    C.cboRestructureByWhom.ListFromCsvString(mRecord.ByWhomList);
  }

  // Controls
  if (mRecord) {
    if (!mRecord.WorkflowId) {
      C.lblWorkflow.VisibleRow(false);
      C.cboWorkflow.VisibleRow(false);
    }
  
    C.dateRestructureDate.MinValue(mRecord.RestructureDateMin);
    C.dateRestructureDate.MaxValue(mRecord.RestructureDateMax);

    // Other Interest
    C.numAccruedOtherInterest.Caption("Accrued " + mRecord.OtherInterestDescription + ":");  
    
    // Fee
    if (mRecord.CanChargeFee) {
      C.numFeeValue.ReadOnly(!mRecord.CanChangeFee);
    }
    else {
      C.lblFee.VisibleRow(false);
      C.chkFeeChargeFee.VisibleRow(false);
    }
  
    // Log generation is not currently supported
    C.chkPrintAdvice.VisibleRow(mRecord.ShowPrintAdvice);
    C.chkCreateLog.VisibleRow(false);
    if (!mRecord.ShowPrintAdvice) {
      C.lblOtherOptions.VisibleRow(false);
    }

    // Financial
    C.afFinancial.StdTransWidgetId(mRecord.StdTransWidgetId);
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

  // Resize Tab
  tabWizard_Resize();
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // Mobile optimisations
  if (window.innerWidth &lt; 500) {
    C.wbAccountSummary.Element().css("min-height", "320px");
  }
  else {
    C.wbAccountSummary.Element().css("min-height", "unspecified");
  }

  // General

  // Tab
  tabWizard_Resize();
}

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

function tabWizard_UpdateButtons() {
  // Back, Next, Finish Buttons Valid?
  var tabIndex = tabWizard.SelectedTabIndex();
  cmdBack.prop("disabled", tabIndex &lt;= 0);
  cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 1);
  cmdFinish.prop("disabled", !cmdNext.prop("disabled"));

  // Exceptions
  if (mRecord) {
  }
}

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

    default:
      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 "Accruals":
        // Accruals
        pageAccruals_Refresh();
        break;

      case "Allocations":
        // Allocations
        pageAllocations_Refresh();
        break;

      case "Financial":
        // Financials
        pageFinancial_Refresh();
        break;

      default:
        break;
    }
  }

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

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

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

// ============
// pageAccruals
// ============
function pageAccruals_Refresh() {
  // Hide content
  frmMain.Visible(false);

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

  // Update Accruals
  var params = CreateFinishParameters();  
  params.initialAccrualsLoad = true;
  
  widget.GetString("AccrualsRefresh", params, pageAccruals_Refresh_Done, function(errorMessage) {
    // Unblock
    widget.UI.Unblock();
    
    // Error
    widget.UI.MsgBoxAlert(errorMessage);
    
    // Move back a page
    tabWizard_Move(-1);
    
    // Show content
    frmMain.Visible(true);
  }); 
}

function pageAccruals_Refresh_Done(data) {
  // Parse
  if (data) data = JSON.parse(data);
  
  // Update
  if (data) {
    mRecord_AccountRestructure.OriginalBalanceFuture = data.OriginalBalanceFuture;
    mRecord_AccountRestructure.OriginalBalance = data.OriginalBalance;
    mRecord_AccountRestructure.AccruedInterest = data.AccruedInterest;
    mRecord_AccountRestructure.AccruedInterestCharge = data.AccruedInterestCharge;
    mRecord_AccountRestructure.AccruedDefaultInterest = data.AccruedDefaultInterest;
    mRecord_AccountRestructure.AccruedDefaultInterestCharge = data.AccruedDefaultInterestCharge;
    mRecord_AccountRestructure.AccruedOtherInterest = data.AccruedOtherInterest;
    mRecord_AccountRestructure.AccruedOtherInterestCharge = data.AccruedOtherInterestCharge;
    mRecord_AccountRestructure.UnpostedDefaultFees = data.UnpostedDefaultFees;
    mRecord_AccountRestructure.UnpostedDefaultFeesCharge = data.UnpostedDefaultFeesCharge;
    mRecord_AccountRestructure.UnpostedOverLimitFees = data.UnpostedOverLimitFees;
    mRecord_AccountRestructure.UnpostedOverLimitFeesCharge = data.UnpostedOverLimitFeesCharge;
    mRecord_AccountRestructure.UnpostedFacilityFees = data.UnpostedFacilityFees;
    mRecord_AccountRestructure.UnpostedFacilityFeesCharge = data.UnpostedFacilityFeesCharge;
    mRecord_AccountRestructure.UnpostedStandardTransactions = data.UnpostedStandardTransactions;
    mRecord_AccountRestructure.UnpostedStandardTransactionsCharge = data.UnpostedStandardTransactionsCharge;
    mRecord_AccountRestructure.SuspendInterest = data.SuspendInterest;
    mRecord_AccountRestructure.SuspendDefaultInterest = data.SuspendDefaultInterest;
    mRecord_AccountRestructure.SuspendDefaultFees = data.SuspendDefaultFees;
    mRecord_AccountRestructure.SuspendFacilityFee = data.SuspendFacilityFee;
    mRecord_AccountRestructure.SuspendStandardTransactions = data.SuspendStandardTransactions;
  }
  
  // Update Controls
  UpdateAccruals();
  
  // Update Balances
  UpdateNetBalance();
  
  // Unblock
  widget.UI.Unblock();
  
  // Show content
  frmMain.Visible(true);
}

// ===============
// Update Accruals
// ===============
function UpdateAccruals() {
  if (mRecord_AccountRestructure) {
    C.numBalanceCurrent.Value(mRecord_AccountRestructure.OriginalBalanceFuture);
    C.numBalanceCommitted.Value(mRecord_AccountRestructure.OriginalBalanceFuture - mRecord_AccountRestructure.OriginalBalance);
    C.numBalanceRestructure.Value(mRecord_AccountRestructure.OriginalBalance);

    C.numAccruedInterest.Value(mRecord_AccountRestructure.AccruedInterest);
    C.chkAccruedInterestCharge.Value(mRecord_AccountRestructure.AccruedInterestCharge);
    C.numAccruedDefaultInterest.Value(mRecord_AccountRestructure.AccruedDefaultInterest);
    C.chkAccruedDefaultInterestCharge.Value(mRecord_AccountRestructure.AccruedDefaultInterestCharge);
    C.numAccruedOtherInterest.Value(mRecord_AccountRestructure.AccruedOtherInterest);
    C.chkAccruedOtherInterestCharge.Value(mRecord_AccountRestructure.AccruedOtherInterestCharge);
    C.numUnpostedDefaultFees.Value(mRecord_AccountRestructure.UnpostedDefaultFees);
    C.chkUnpostedDefaultFeesCharge.Value(mRecord_AccountRestructure.UnpostedDefaultFeesCharge);
    C.numUnpostedOverLimitFees.Value(mRecord_AccountRestructure.UnpostedOverLimitFees);
    C.chkUnpostedOverLimitFeesCharge.Value(mRecord_AccountRestructure.UnpostedOverLimitFeesCharge);
    C.numUnpostedFacilityFees.Value(mRecord_AccountRestructure.UnpostedFacilityFees);
    C.chkUnpostedFacilityFeesCharge.Value(mRecord_AccountRestructure.UnpostedFacilityFeesCharge);
    C.numUnpostedStandardTransactions.Value(mRecord_AccountRestructure.UnpostedStandardTransactions);

    if (mRecord_AccountRestructure.UnpostedStandardTransactions != 0) {
      C.chkUnpostedStandardTransactionsCharge.Value(mRecord_AccountRestructure.UnpostedStandardTransactionsCharge);
    }

    C.chkSuspendInterest.Value(mRecord_AccountRestructure.SuspendInterest);
    C.chkSuspendDefaultInterest.Value(mRecord_AccountRestructure.SuspendDefaultInterest);
    C.chkSuspendDefaultFees.Value(mRecord_AccountRestructure.SuspendDefaultFees);
    C.chkSuspendFacilityFee.Value(mRecord_AccountRestructure.SuspendFacilityFee);
    C.chkSuspendStandardTransactions.Value(mRecord_AccountRestructure.SuspendStandardTransactions);
    
    // Other Updates
    if (C.numBalanceCurrent.Value() == C.numBalanceRestructure.Value()) {
      C.numBalanceCurrent.VisibleRow(false);
      C.numBalanceCommitted.VisibleRow(false);
    }
    else {
      C.numBalanceCurrent.VisibleRow(true);
      C.numBalanceCommitted.VisibleRow(true);
    }

    // Captions
    if (mRecord_AccountRestructure.AccruedInterestSuspended) C.chkAccruedInterestCharge.Caption("Charge (currently suspended)?");
    if (mRecord_AccountRestructure.AccruedDefaultInterestSuspended) C.chkAccruedDefaultInterestCharge.Caption("Charge (currently suspended)?");
    if (mRecord_AccountRestructure.UnpostedDefaultFeesSuspended) C.chkUnpostedDefaultFeesCharge.Caption("Charge (currently suspended)?");
    if (mRecord_AccountRestructure.UnpostedOverLimitFeesSuspended) C.chkUnpostedOverLimitFeesCharge.Caption("Charge (currently suspended)?");
    if (mRecord_AccountRestructure.UnpostedFacilityFeesSuspended) C.chkUnpostedFacilityFeesCharge.Caption("Charge (currently suspended)?");
    if (mRecord_AccountRestructure.UnpostedStandardTransactionsSuspended) C.chkUnpostedStandardTransactionsCharge.Caption("Charge (currently suspended)?");  

    // Blank Tips
    C.numAccruedInterest.BlankTip(mRecord_AccountRestructure.AccruedInterest);
    C.numAccruedDefaultInterest.BlankTip(mRecord_AccountRestructure.AccruedDefaultInterest);
    C.numAccruedOtherInterest.BlankTip(mRecord_AccountRestructure.AccruedOtherInterest);
    C.numUnpostedDefaultFees.BlankTip(mRecord_AccountRestructure.UnpostedDefaultFees);
    C.numUnpostedOverLimitFees.BlankTip(mRecord_AccountRestructure.UnpostedOverLimitFees);
    C.numUnpostedFacilityFees.BlankTip(mRecord_AccountRestructure.UnpostedFacilityFees);
    C.numUnpostedStandardTransactions.BlankTip(mRecord_AccountRestructure.UnpostedStandardTransactions);    
    
    // Other Interest
    if (mRecord_AccountRestructure.AccruedOtherInterestAvailable || mRecord_AccountRestructure.AccruedOtherInterestOriginal != 0) {
      C.chkAccruedOtherInterestCharge.VisibleRow(true);
      C.numAccruedOtherInterest.VisibleRow(true);
    }
    else {
      C.chkAccruedOtherInterestCharge.VisibleRow(false);
      C.numAccruedOtherInterest.VisibleRow(false);
    }

    // Default Fees
    if (mRecord_AccountRestructure.UnpostedDefaultFeesAvailable || mRecord_AccountRestructure.UnpostedDefaultFeesOriginal != 0) {
      C.chkUnpostedDefaultFeesCharge.VisibleRow(true);
      C.numUnpostedDefaultFees.VisibleRow(true);
    }
    else {
      C.chkUnpostedDefaultFeesCharge.VisibleRow(false);
      C.numUnpostedDefaultFees.VisibleRow(false);
    }

    // Over Limit Fees
    if (mRecord_AccountRestructure.UnpostedOverLimitFeesAvailable || mRecord_AccountRestructure.UnpostedOverLimitFeesOriginal != 0) {
      C.chkUnpostedOverLimitFeesCharge.VisibleRow(true);
      C.numUnpostedOverLimitFees.VisibleRow(true);
    }
    else {
      C.chkUnpostedOverLimitFeesCharge.VisibleRow(false);
      C.numUnpostedOverLimitFees.VisibleRow(false);
    }

    // Facility Fees
    if (mRecord_AccountRestructure.UnpostedFacilityFeesAvailable || mRecord_AccountRestructure.UnpostedFacilityFeesOriginal != 0) {
      C.chkUnpostedFacilityFeesCharge.VisibleRow(true);
      C.numUnpostedFacilityFees.VisibleRow(true);
    }
    else {
      C.chkUnpostedFacilityFeesCharge.VisibleRow(false);
      C.numUnpostedFacilityFees.VisibleRow(false);
    }

    // Unposted Transactions
    if (mRecord_AccountRestructure.UnpostedStandardTransactions == 0) {
      C.chkUnpostedStandardTransactionsCharge.VisibleRow(false);
      C.chkUnpostedStandardTransactionsCharge.Value(false);
    }
    else {
      C.chkUnpostedStandardTransactionsCharge.VisibleRow(true);
    }

    // Suspend Options
    if (mRecord.SuspendDefaultFees || mRecord.SuspendDefaultInterest || mRecord.SuspendFacilityFee || mRecord.SuspendInterest || mRecord.SuspendStandardTransactions) {
      C.chkSuspendInterest.ReadOnly(!mRecord.SuspendInterest);
      C.chkSuspendDefaultInterest.ReadOnly(!mRecord.SuspendDefaultInterest);
      C.chkSuspendDefaultFees.ReadOnly(!mRecord.SuspendDefaultFees);
      C.chkSuspendFacilityFee.ReadOnly(!mRecord.SuspendFacilityFee);
      C.chkSuspendStandardTransactions.ReadOnly(!mRecord.SuspendStandardTransactions);
      
      C.lblSuspension.VisibleRow(true);
      C.chkSuspendInterest.VisibleRow(true);
      C.chkSuspendDefaultInterest.VisibleRow(true);
      C.chkSuspendDefaultFees.VisibleRow(true);
      C.chkSuspendFacilityFee.VisibleRow(true);
      C.chkSuspendStandardTransactions.VisibleRow(true);
    }
    else {
      C.lblSuspension.VisibleRow(false);
      C.chkSuspendInterest.VisibleRow(false);
      C.chkSuspendDefaultInterest.VisibleRow(false);
      C.chkSuspendDefaultFees.VisibleRow(false);
      C.chkSuspendFacilityFee.VisibleRow(false);
      C.chkSuspendStandardTransactions.VisibleRow(false);
    }
  }
}

// ===============
// pageAllocations
// ===============
function pageAllocations_Refresh() {
  if (mReCalcAllocations) {
    mRecord_DefaultAllocations = null;

    // Hide content
    frmMain.Visible(false);

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

    // Params
    var params = CreateFinishParameters();
    params.initialAllocationsLoad = true;

    // Get Updated Allocations
    widget.GetString("AllocationsRefresh", params, pageAllocations_Refresh_Done, function(errorMessage) {
      // Unblock
      widget.UI.Unblock();

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

      // Move back a page
      tabWizard_Move(-1);
      
      // Show content
      frmMain.Visible(true);
    });
  }
}

function pageAllocations_Refresh_Done(data) {
  // Parse
  if (data) mRecord_DefaultAllocations = JSON.parse(data);

  // Update Fields
  if (mRecord_DefaultAllocations) {
    C.numBalanceOverdueCurrent.Value(mRecord_DefaultAllocations.BalanceOverdueCurrent);
    C.numBalanceOverdueCommitted.Value(mRecord_DefaultAllocations.BalanceOverdueCommitted);
    C.numNetBalanceOverdue.Value(mRecord_DefaultAllocations.NetBalanceOverdue);
    C.numAdjustOverdue.Value(mRecord_DefaultAllocations.AdjustOverdue);
    C.numBalanceOverdue.Value(mRecord_DefaultAllocations.BalanceOverdue);
  }

  // Update Controls
  if (mRecord_DefaultAllocations) {
    C.numBalanceOverdueCurrent.VisibleRow(mRecord_DefaultAllocations.BalanceOverdueCommitted != 0);
    C.numBalanceOverdueCommitted.VisibleRow(mRecord_DefaultAllocations.BalanceOverdueCommitted != 0);
  }

  // Update Totals
  UpdateAllocationTotals();

  // Reset flag
  mReCalcAllocations = false;

  // Unblock UI
  widget.UI.Unblock();
  
  // Show content
  frmMain.Visible(true);
}

// =============
// pageFinancial
// =============
function pageFinancial_Refresh() {
  // Financial
  if (mCalculationRequired) {
    // Hide content
    frmMain.Visible(false);
  
    // Calculate
    Calculate(false, true);
  }
}

function Calculate(resetFinancial, errorAsSummaryPage) {
  // Block UI
  widget.UI.Block("Calculating, please wait...");

  // Params
  var params = CreateFinishParameters();

  // Resetting
  if (resetFinancial) {
    params.Reset = true;
  }
  if (errorAsSummaryPage) {
    params.ErrorAsSummaryPage = true;
  }

  // Calculate
  widget.GetString("Calculate", params, Calculate_Done, function(errorMessage) {
    // Unblock
    widget.UI.Unblock();

    // Error
    widget.UI.MsgBoxAlert(errorMessage);
    
    // Show content
    frmMain.Visible(true);
  });
}

function Calculate_Done(data) {
  // Parse
  if (data) data = JSON.parse(data);

  var error;

  // Update Account Financial and / or Summary Page
  if (data) {
    error = data.ErrorHtml;
  
    if (error) {
      C.wbAccountSummary.SetContent(error, false);
    }
    else {
      // Clear Promises (so they aren't repetitively added)
      // Any previously added promises will be in the Account Payment Schedule so we don't want to bring them in twice
      C.afFinancial.PromisesClear();
  
      // Refresh Financials
      C.afFinancial.FromAccountCalcJson(data.AccountCalcJson, "", mRecord.RecordCode, data.BalanceOverdue);
  
      // Update Summary
      C.wbAccountSummary.SetContent(data.RestructureSummaryHtml, false);
    }    
  }

  // Reset flag
  if (!error) mCalculationRequired = false;

  // Unblock
  widget.UI.Unblock();
  
  // Show content
  frmMain.Visible(true);
}

// ================
// Allocate Balance
// ================
function AllocateBalanceTo(allocation) {
  // Reset
  C.numPnibAllocated.Value(-mRecord_DefaultAllocations.BalancePrincipalNIB);
  C.numPibAllocated.Value(-mRecord_DefaultAllocations.BalancePrincipalIB);
  C.numIAllocated.Value(-mRecord_DefaultAllocations.BalanceInterest);
  C.numFnibAllocated.Value(-mRecord_DefaultAllocations.BalanceFeeNIB);
  C.numFibAllocated.Value(-mRecord_DefaultAllocations.BalanceFeeIB);

  // Allocate
  switch(allocation) {
    case "PNIB":
      C.numPnibAllocated.Value(mRecord_DefaultAllocations.TotalBalance - mRecord_DefaultAllocations.BalancePrincipalNIB);
      break;

    case "PIB":
      C.numPibAllocated.Value(mRecord_DefaultAllocations.TotalBalance - mRecord_DefaultAllocations.BalancePrincipalIB);
      break;

    case "I":
      C.numIAllocated.Value(mRecord_DefaultAllocations.TotalBalance - mRecord_DefaultAllocations.BalanceInterest);
      break;

    case "FNIB":
      C.numFnibAllocated.Value(mRecord_DefaultAllocations.TotalBalance - mRecord_DefaultAllocations.BalanceFeeNIB);
      break;

    case "FIB":
      C.numFibAllocated.Value(mRecord_DefaultAllocations.TotalBalance - mRecord_DefaultAllocations.BalanceFeeIB);
      break;
  }

  // Update Totals
  UpdateAllocationTotals();
}

// ========================
// Update Allocation Totals
// ========================
function UpdateAllocationTotals() {
  if (mRecord_DefaultAllocations) {
    // New Column
    mRecord_DefaultAllocations.NewPrincipalNIB = (mRecord_DefaultAllocations.BalancePrincipalNIB + C.numPnibAllocated.Value());
    mRecord_DefaultAllocations.NewPrincipalIB = (mRecord_DefaultAllocations.BalancePrincipalIB + C.numPibAllocated.Value());
    mRecord_DefaultAllocations.NewInterest = (mRecord_DefaultAllocations.BalanceInterest + C.numIAllocated.Value());
    mRecord_DefaultAllocations.NewFeeNIB = (mRecord_DefaultAllocations.BalanceFeeNIB + C.numFnibAllocated.Value());
    mRecord_DefaultAllocations.NewFeeIB = (mRecord_DefaultAllocations.BalanceFeeIB + C.numFibAllocated.Value());

    // Totals
    mRecord_DefaultAllocations.TotalBalance = (mRecord_DefaultAllocations.BalancePrincipalNIB + mRecord_DefaultAllocations.BalancePrincipalIB + mRecord_DefaultAllocations.BalanceInterest + mRecord_DefaultAllocations.BalanceFeeNIB + mRecord_DefaultAllocations.BalanceFeeIB);
    mRecord_DefaultAllocations.TotalAllocations = (C.numPnibAllocated.Value() + C.numPibAllocated.Value() + C.numIAllocated.Value() + C.numFnibAllocated.Value() + C.numFibAllocated.Value());
    mRecord_DefaultAllocations.TotalNew = (mRecord_DefaultAllocations.NewPrincipalNIB + mRecord_DefaultAllocations.NewPrincipalIB + mRecord_DefaultAllocations.NewInterest + mRecord_DefaultAllocations.NewFeeNIB + mRecord_DefaultAllocations.NewFeeIB);
  }

  // Calculate
  mCalculationRequired = true

  // Update Controls
  widget.UI.Evaluate(C.tblManualAllocation);
}

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {      
      case "Allocations":
        if (mRecord_DefaultAllocations.TotalNew != mRecord_DefaultAllocations.TotalBalance) {
          Ok = false;
          widget.UI.MsgBoxAlert("Allocations do not match Balance.");
        }
        break;
    
      default:
        // No validation
        validCallback();
        return;
    }
  }

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        var params = CreateFinishParameters();
        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()) {
      default:
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId) {
  switch (actionId.toUpperCase()) {
    case "CANCEL":
      // Cancel
      tabWizard_Cancel();
      break;

    case "FINISH":
      // Finish
      Form_ExecuteAction_Finish();
      break;

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

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Validate
  tabWizard_Validate(function () {
    // Save Fields
    Fields_Save();

    if (mRecord.PromptOnCommit) {
      // Confirm
      var msg, heading;

      heading = "Restructure Account";
      msg = "Are you sure you want to Restructure Account " + mRecord.RecordCode + ", '" + mRecord.RecordDescription + "'?";

      if (C.chkPrintAdvice.Value()) {
        msg += "\n\nNOTE: Once finished, an Advice Document will be generated."
      }

      widget.UI.MsgBoxConfirm(msg, { heading: heading }, Form_ExecuteAction_FinishPost, null);
    }
    else {
      // Commit without prompting
      Form_ExecuteAction_FinishPost();
    }
  });
}

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

  // Create Parameters
  var params = CreateFinishParameters();

  // Finish
  widget.GetString("Finish", params,
    function (data) {
      data = JSON.parse(data);

      // Finalise
      if (data.Warnings) {
        // Unblock UI
        widget.UI.Unblock();

        // Warnings
        var msg;
        msg = "Account '" + mRecord.RecordCode + "' was successfully Restructured but the following warnings were given:";
        widget.UI.MsgBoxAlert(msg + "\n\n" + data.Warnings, {}, function() { Form_ExecuteAction_FinishPost_PrintAdvice(data); });
      }
      else {
        Form_ExecuteAction_FinishPost_PrintAdvice(data);
      }
    },

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

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

function Form_ExecuteAction_FinishPost_PrintAdvice(data) {
  // Print Advice
  // NOTE: Since this is a file download, cannot reliably detect whether it worked or not hence finalise regardless
  if (C.chkPrintAdvice.Value() &amp;&amp; data.DocumentLogPk != 0) {
    widget.DownloadFile("PrintAdvice", { documentLogPk: data.DocumentLogPk });
  }

  // Finalise
  Form_ExecuteAction_FinishPost_Finalise();
}

function Form_ExecuteAction_FinishPost_Finalise() {
  // Refresh Parent
  widget.RefreshParent();

  // Close Form
  widget.Close();

  // Show New/ Updated Account record (after closing Widget to avoid notification on Web)
  if (!mRecord.WorkflowId) {
    widget.ExecuteApplicationShortcutUrl("app://formshow?form=Accounts&amp;id=" + mRecord.RecordCode);
  }  
}

// =================
// Finish Parameters
// =================
function CreateFinishParameters() {
  var params = {
  	restructureDate: C.dateRestructureDate.Value(),
  	restructureByWhom: C.cboRestructureByWhom.Text(),
  	restructureType: C.cboRestructureType.Text(),
  	restructureReason: C.txtRestructureReason.Text(),

  	feeChargeFee: C.chkFeeChargeFee.Value(),
  	feeValue: C.numFeeValue.Value(),

  	printAdvice: C.chkPrintAdvice.Value(),
  	createLog: C.chkCreateLog.Value(),

  	accruedInterest: C.numAccruedInterest.Value(),
  	accruedInterestCharge: C.chkAccruedInterestCharge.Value(),
  	accruedDefaultInterest: C.numAccruedDefaultInterest.Value(),
  	accruedDefaultInterestCharge: C.chkAccruedDefaultInterestCharge.Value(),
  	accruedOtherInterest: C.numAccruedOtherInterest.Value(),
  	accruedOtherInterestCharge: C.chkAccruedOtherInterestCharge.Value(),
  	unpostedDefaultFees: C.numUnpostedDefaultFees.Value(),
  	unpostedDefaultFeesCharge: C.chkUnpostedDefaultFeesCharge.Value(),
  	unpostedOverLimitFees: C.numUnpostedOverLimitFees.Value(),
  	unpostedOverLimitFeesCharge: C.chkUnpostedOverLimitFeesCharge.Value(),
  	unpostedFacilityFees: C.numUnpostedFacilityFees.Value(),
  	unpostedFacilityFeesCharge: C.chkUnpostedFacilityFeesCharge.Value(),
  	unpostedStandardTransactionsCharge: C.chkUnpostedStandardTransactionsCharge.Value(),

  	suspendInterest: C.chkSuspendInterest.Value(),
  	suspendDefaultInterest: C.chkSuspendDefaultInterest.Value(),
  	suspendDefaultFees: C.chkSuspendDefaultFees.Value(),
  	suspendFacilityFee: C.chkSuspendFacilityFee.Value(),
  	suspendStandardTransactions: C.chkSuspendStandardTransactions.Value(),
  }

  // Allocations
  if (mRecord_DefaultAllocations) {
    params.balancePrincipalNIB = mRecord_DefaultAllocations.NewPrincipalNIB;
    params.balancePrincipalIB = mRecord_DefaultAllocations.NewPrincipalIB;
    params.balanceInterest = mRecord_DefaultAllocations.NewInterest;
    params.balanceFeeNIB = mRecord_DefaultAllocations.NewFeeNIB;
    params.balanceFeeIB = mRecord_DefaultAllocations.NewFeeIB;
  }

  // Financial
  params.balanceOverdue = C.numBalanceOverdue.Value();
  params.accountCalcJson = JSON.stringify(C.afFinancial.ToAccountCalc());
  params.promisesJson = JSON.stringify(C.afFinancial.Promises());

  return params;
}

// ===================
// dateRestructureDate
// ===================
function dateRestructureDate_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Calculate
  mCalculationRequired = true
  mReCalcAllocations = true;
}

// ===============
// chkFeeChargeFee
// ===============
function chkFeeChargeFee_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Calculate
  mCalculationRequired = true

  // Fee
  C.numFeeValue.VisibleRow(mRecord.CanChargeFee &amp;&amp; C.chkFeeChargeFee.Value());
}

// ================
// numAdjustOverdue
// ================
function numAdjustOverdue_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Calculate
  mCalculationRequired = true

  // Update
  C.numBalanceOverdue.Value(C.numNetBalanceOverdue.Value() + C.numAdjustOverdue.Value());
}

// =================
// numBalanceOverdue
// =================
function numBalanceOverdue_ButtonClick(source, e) {
  switch(e.id) {
    case "Clear":
      if (C.numBalanceOverdue.Value != 0) {
        C.numAdjustOverdue.Value(-C.numNetBalanceOverdue.Value());
        
        // Update
        numAdjustOverdue_Change();
      }
      break;
  }
}

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

  // Calculate
  mCalculationRequired = true

  // Update
  C.numAdjustOverdue.Value(C.numBalanceOverdue.Value() - C.numNetBalanceOverdue.Value());
}

// ========
// Schedule
// ========
function ShowSchedule(current) {
  // Block
  widget.UI.Block("Retrieving schedule, please wait...");

  // Params
  var params = CreateFinishParameters();
  params.Current = current;

  // Get Schedule
  widget.GetString("GetSchedule", params,
    function(data) {
      // Unblock
      widget.UI.Unblock();

      // Show Schedule
      var params = {
        scheduleJson: data,
        gotoDate: C.dateRestructureDate.Value(),
      }
      widget.UI.Forms.ShowAccountSchedule(params);
    },

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

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

function ShowSchedule_Done(data) {
  // Parse
  if (data) data = JSON.parse(data);

  // Show Schedule
  widget.UI.Forms.ShowAccountSchedule({scheduleJson: data});
}

function UpdateNetBalance_Pre() {
  // Recalculate
  mReCalcAllocations = true;

  // Update Balance
  UpdateNetBalance();
}

// =============
// numBalanceNet
// =============
function UpdateNetBalance() {
  var balance = C.numBalanceRestructure.Value();

  // Accrued Interest
  if (C.chkAccruedInterestCharge.Value()) {
    balance += C.numAccruedInterest.Value();
    C.numAccruedInterest.ReadOnly(false);
  }
  else {
    C.numAccruedInterest.ReadOnly(true);
  }

  // Accrued Default Interest
  if (C.chkAccruedDefaultInterestCharge.Value()) {
    balance += C.numAccruedDefaultInterest.Value()
    C.numAccruedDefaultInterest.ReadOnly(false);
  }
  else {
    C.numAccruedDefaultInterest.ReadOnly(true);
  }

  // Accrued Other Interest
  if (C.chkAccruedOtherInterestCharge.Value()) {
    balance += C.numAccruedOtherInterest.Value();
    C.numAccruedOtherInterest.ReadOnly(false);
  }
  else {
    C.numAccruedOtherInterest.ReadOnly(true);
  }

  // Unposted Default Fees
  if (C.chkUnpostedDefaultFeesCharge.Value()) {
    balance += C.numUnpostedDefaultFees.Value();
    C.numUnpostedDefaultFees.ReadOnly(false);
  }
  else {
    C.numUnpostedDefaultFees.ReadOnly(true);
  }

  // Unposted Over Limit Fees
  if (C.chkUnpostedOverLimitFeesCharge.Value()) {
    balance += C.numUnpostedOverLimitFees.Value();
    C.numUnpostedOverLimitFees.ReadOnly(false);
  }
  else {
    C.numUnpostedOverLimitFees.ReadOnly(true);
  }

  // Unposted Facility Fees
  if (C.chkUnpostedFacilityFeesCharge.Value()) {
    balance += C.numUnpostedFacilityFees.Value();
    C.numUnpostedFacilityFees.ReadOnly(false);
  }
  else {
    C.numUnpostedFacilityFees.ReadOnly(true);
  }

  // Unposted Standard Transactions
  if (C.chkUnpostedStandardTransactionsCharge.Value()) {
    balance += C.numUnpostedStandardTransactions.Value();
  }

  C.numBalanceNet.Value(balance);
}

// ===========
// afFinancial
// ===========
function afFinancial_Action(actionId) {
  switch(actionId) {
    case "PaymentsCleanup":
      // Clean up Payments
      afFinancial_OverridingPaymentsHandling("PaymentsCleanup");
      break;

    case "RegularPaymentsCreate":
      // Create Blank Regular Payments
      afFinancial_OverridingPaymentsHandling("RegularPaymentsCreate");
      break;
      
    case "ScheduleShow":
      // Show Schedule
      ShowSchedule(false);
      break;

    case "Reset":
      // Reset
      widget.UI.MsgBoxConfirm("Are you sure you want to reset all Financial details to as they were pre-Restructure?", { heading: "Reset Financial" },
        function() {          
          Calculate(true, false);
        });
      break;

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

function afFinancial_Change(fieldUpdated) {
  // Clear Summary
  C.wbAccountSummary.Clear();

  // Calculate delayed
  if (mCalculationTimer) {
    window.clearTimeout(mCalculationTimer);
    mCalculationTimer = null;
  }

  if (fieldUpdated) {
    // A named field has been updated that is known to affect other fields so calculate immediately
    Calculate(false, true);
  }
  else {
    // Delayed calculation
    mCalculationTimer = window.setTimeout(function () {
      Calculate(false, true);
      mCalculationTimer = null;
    }, 500);
  }
}

// ============================
// Overriding Payments Handling
// ============================
function afFinancial_OverridingPaymentsHandling(action) {
  // Block
  widget.UI.Block("Updating Overriding Payments, please wait...");
  
  // Save
  Fields_Save();
  
  // Params
  var params = {
    action: action,
    accountRestructureJson: JSON.stringify(CreateFinishParameters()),
    overridingPaymentsJson: C.afFinancial.GetOverridingPaymentsJson(),    
  }
  
  // Create Payments
  widget.GetString("OverridingPaymentsHandling", params, afFinancial_OverridingPaymentsHandling_Done, function(errorMessage) {
    // Unblock
    widget.UI.Unblock();
    
    // Error
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

function afFinancial_OverridingPaymentsHandling_Done(data) {
  // Parse
  if (data) data = JSON.parse(data);
  
  // Set Payments
  C.afFinancial.SetOverridingPayments(data);
  
  // Unblock
  widget.UI.Unblock();
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>y9biBV5AAUWOh4mV5FL1dw</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>true</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <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="StdTransWidgetId" type="List">
            <BlankTip />
            <Caption>Edit Standard Transaction Widget:</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.Scripts</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="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="WorkflowPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="WorkflowItemPk" 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>