<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-12-05T22:03:35.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2023-10-03T19:43:03.6100000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2023-12-05T21:58:46.2370000</UpdatedUtcDate>
    <ScriptId>HWACCAPPQUOTE</ScriptId>
    <Description>Account Application Quote</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountAppQuote
Option Explicit On
Option Strict On

' #################################################################
' Account Application Quote wizard HTML Widget
'
' Version: 1.01 (06/12/2023)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  05/10/2023  ISS      J031033   Created
'    1.01  06/12/2023  ISS      J032539   "Quote Properties" not always saving
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountAppQuote"

' Common Parameters
Private mAccountAppPk As Integer
Private mAccountAppCalculationPk As Integer
Private mReadOnly As Boolean

' 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
    mAccountAppPk = .GetInteger("AccountAppPk")
    mAccountAppCalculationPk = .GetInteger("AccountAppCalculationPk")
    mReadOnly = .GetBoolean("ReadOnly")
  End With
  
  ' Validate
  If Not finBL.CurrentUser.Permissions.Allow("Cloud.Form.AccountApp") Then
    Main = False
    finBL.Error.ErrorBegin("You do not have permission to edit Account Applications.")
  ElseIf mAccountAppPk = 0 Then
    Main = False
    finBL.Error.ErrorBegin("Account Application Pk not specified.")  
  End If

  ' Handle Events
  If Main Then
    Select Case eventId
      Case ""
        ' Main event, i.e., return initial HTML content (excluding html and body tags)
        returnValue = ScriptInfo.TemplateText
  
      Case "Calculate"
        ' Calculate
        Main = Calculate(parametersJson, returnValue)
        
      Case "Delete"
        ' Delete Quote
        Main = Delete(returnValue)
  
      Case "Finish"
        ' Finish wizard
        Main = Finish(parametersJson, requestInfo, returnValue)
  
      Case "GetAccountSchedule"
        ' Get Account Schedule
        Main = GetAccountSchedule(parametersJson, returnValue)
        
      Case "GetInitialisationInfo"
        ' Get Initialisation Information required for this wizard
        Main = GetInitialisationInfo(returnValue)
  
      Case Else
        finBL.Error.ErrorBeginFormat("Unhandled event '{0}'.", eventId)
        Main = False
    End Select
  End If

End Function

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

  Dim Account As finAccount
  Dim AccountApp As finAccountApp
  Dim AccountAppCalc As finAccountAppCalculation
  Dim AccountDetails As AccountDetails
  Dim CalculationFailed As Boolean  
  Dim Html As String
  Dim obj As Object
  Dim Success As Boolean
  
  ' Assume Success
  Success = True

  ' Parse Parameters
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(AccountDetails), obj) Then
    AccountDetails = DirectCast(obj, AccountDetails)
  Else
    Success = False
  End If
  
  ' Create Account Application and associated objects
  If Success Then
    Success = CreateAccountAppCalc(AccountDetails, AccountApp, AccountAppCalc, Account, CalculationFailed)
  End If

  ' Get HTML Summary
  If Success
    If CalculationFailed Then
      Html = finBL.GetHtmlErrorMessage(finBL.Error.Message(True, True))
    Else
      Html = finBL.SummaryPageFunctions.AccountFinancialSummary(False, Account, -1, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
    End If
  End If

  ' Finalise
  If Success Then
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New CalculationDetails(New AccountDetails(Account), Html), returnValue)
  End If

  Return Success

End Function

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

  Dim Account As finAccount
  Dim AccountApp As finAccountApp
  Dim AccountAppCalc As finAccountAppCalculation
  Dim AccountDetails As AccountDetails
  Dim CalculationFailed As Boolean
  Dim obj As Object
  Dim Success As Boolean
  
  ' Assume Success
  Success = True

  ' Parse Parameters
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(AccountDetails), obj) Then
    AccountDetails = DirectCast(obj, AccountDetails)
  Else
    Success = False
  End If
  
  ' Create Account Application and associated objects
  If Success Then
    Success = CreateAccountAppCalc(AccountDetails, AccountApp, AccountAppCalc, Account, CalculationFailed) AndAlso Not CalculationFailed
  End If

  ' Get Schedule
  If Success Then
    response = Account.Calculation.Schedule.ToHtmlWidgetJsonString("Date,ScheduleType,ElementId,Reference,Value,Balance,Notes")
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Create finAccountAppCalc and associated objects from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateAccountAppCalc(accountDetails As AccountDetails,
                                      ByRef accountApp As finAccountApp,
                                      ByRef accountAppCalc As finAccountAppCalculation,
                                      ByRef account As finAccount,
                                      ByRef calculationFailed As Boolean) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  accountApp = finBL.CreateAccountApp()
  accountAppCalc = Nothing
  account = Nothing
  calculationFailed = False

  ' Validate
  If finBL.CurrentUserInformation.IsAccountAppFilteredOutPk(mAccountAppPk) Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view this Account Application.")
  End If
  
  ' Load Account Application
  If Success Then
    Success = accountApp.LoadPk(mAccountAppPk)
  End If
  
  ' Get Calc
  If Success Then
    ' Find Calc
    If mAccountAppCalculationPk &lt; 0 Then
      ' New
      accountAppCalc = accountApp.Calculations.CreateAccountAppCalculation()
      accountApp.Calculations.Add(accountAppCalc)
    ElseIf accountapp.Calculations.ExistsPk(mAccountAppCalculationPk) Then
      ' Existing
      accountAppCalc = accountApp.Calculations.ItemByPk(mAccountAppCalculationPk)
    Else
      Success = False
      finBL.Error.ErrorBegin("Failed to retrieve Account Application Calculation. This record may have been deleted by another User.")
    End If
  End If

  ' Create Account
  If Success Then
    Success = AccountAppCalc.CreateAccount(Account)
  End If
  
  ' Validate
  If Success Then
    If mAccountAppCalculationPk &lt; 0 AndAlso Account.AccountType Is Nothing Then
      If AccountApp.AccountAppType.DefaultAccountTypePk = 0 Then
        Success = False
        finBL.Error.ErrorBeginFormat("This Quote does not have an Account Type defined, therefore you cannot edit the Financial details." &amp; vbNewLine &amp; vbNewLine &amp; String.Format("Account Application Type '{0}' does not define a default Account Type and no Account Type has been set from the Script.", AccountApp.AccountAppTypeId))
      Else
        ' Initialise Account Type (this only touches the temporary Account, not the Account Application at this stage)
        Success = Not Account.Calculation.LoadAccountTypePk(AccountApp.AccountAppType.DefaultAccountTypePk)
      End If
    End If
  End If
  
  ' Update Account from supplied Account Details
  If Success AndAlso accountDetails IsNot Nothing Then
    With Account
      .AccountTypeId = accountDetails.AccountTypeId
      .AccountTypePromotionId = accountDetails.AccountTypePromotionId
      
      ' Calculation
      .Calculation.FromHtmlWidgetJsonString(AccountDetails.AccountCalcJson)
  
      ' Action
      Select Case AccountDetails.Action
        Case "Reset"
          ' Reset All
          Account.Calculation.ResetToDefaults()
          Account.Calculation.Payments.Clear()
  
        Case "StdTransReset"
          ' Reset Transactions to Defaults
          Account.Calculation.LoadAccountTypeStdTransactions()
      End Select
  
      ' Calculate
      If .Calculation.PaymentRegularOverride = 0 Then
        If Not .Calculation.Calculate() Then
          ' Ignore errors
          calculationFailed = True
        End If
      Else
        If Not .Calculation.CalculateTerm(.Calculation.PaymentRegularOverride) Then
          ' Ignore errors
          calculationFailed = True
        End If
      End If
    End With      
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Delete Quote.
''' &lt;/summary&gt;
Private Function Delete(ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim AccountApp As finAccountApp
  Dim AccountAppCalc As finAccountAppCalculation
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Create Account Application and associated objects
  If Success Then
    Success = CreateAccountAppCalc(Nothing, AccountApp, AccountAppCalc, Account, False)
  End If
  
  ' Delete
  If Success Then
    Success = AccountApp.Calculations.Remove(AccountAppCalc)
  End If
  
  ' Save
  If Success Then
    Success = AccountApp.Save()
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Commit changes.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Private Function Finish(parametersJson As String,
                        requestInfo As finScriptRequestInfo,
                        ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim AccountApp As finAccountApp
  Dim AccountAppCalc As finAccountAppCalculation
  Dim obj As Object
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters
  
  ' Assume Success
  Success = True

  ' Parse Parameters
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(WizardFinishParameters), obj) Then
    WizardFinishParameters = DirectCast(obj, WizardFinishParameters)
  Else
    Success = False
  End If
  
  ' Create Account Application and associated objects
  If Success Then
    Success = CreateAccountAppCalc(WizardFinishParameters.Account, AccountApp, AccountAppCalc, Account, False)
  End If
  
  ' Update
  If Success Then
    With AccountAppCalc
      If Not .KeyLocked Then
        .Key = WizardFinishParameters.Key
        .Name = WizardFinishParameters.Name
        
        .UserInvalid = WizardFinishParameters.UserInvalid
        .UserInvalidReason = WizardFinishParameters.UserInvalidReason
        
        .Notes = WizardFinishParameters.Notes
      End If
    End With
    
    Success = AccountAppCalc.UpdateFromAccount(Account)
  End If
  
  ' Save
  If Success Then
    Success = AccountApp.Save()
  End If

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

  Return Success

End Function

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

  Dim Account As finAccount
  Dim AccountApp As finAccountApp
  Dim AccountAppCalc As finAccountAppCalculation
  Dim AccountClassList As New List(Of isefinAccountClass)
  Dim AccountType As finAccountTypeRO
  Dim CalculationFailed As Boolean  
  Dim FormInitialisationInfo As FormInitialisationInfo  
  Dim ProductType As finProductTypeRO
  Dim ProductTypeIds As New ISList()
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Create Account Application and associated objects
  Success = CreateAccountAppCalc(Nothing, AccountApp, AccountAppCalc, Account, CalculationFailed)

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

      ' Record
      .IsNew = AccountAppCalc.IsNew
      If Not .IsNew  AndAlso Not AccountApp.IsClosed AndAlso AccountApp.Calculations.Count &gt; 1 Then
        Select Case AccountApp.Status 
          Case isefinAccountAppStatus.Incomplete, isefinAccountAppStatus.Reviewing
            .CanDelete = True
        End Select
      End If
      
      ' Quote
      .Name = AccountAppCalc.Name
      .Key = AccountAppCalc.Key
      .KeyLocked = AccountAppCalc.KeyLocked
      
      .UserInvalid = AccountAppCalc.UserInvalid
      .UserInvalidReason = AccountAppCalc.UserInvalidReason
      
      .Notes = AccountAppCalc.Notes
      
      ' Financial &amp; Account
      ' NOTE: Account calculations rely on the Account Application being able to create a finAccount object
      .Account = New AccountDetails(Account)
      If CalculationFailed Then
        .AccountSummaryHtml = finBL.GetHtmlErrorMessage(finBL.Error.Message(True, True))
      Else
        .AccountSummaryHtml = finBL.SummaryPageFunctions.AccountFinancialSummary(False, Account, -1, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
      End If

      ' Global Collections
      If finBL.Settings.AddOns.DepositAccount Then AccountClassList.Add(isefinAccountClass.Deposit)
      If finBL.Settings.AddOns.LoanFRAccount Then AccountClassList.Add(isefinAccountClass.LoanFR)
      If finBL.Settings.AddOns.LoanFTAccount Then AccountClassList.Add(isefinAccountClass.LoanFT)
      If finBL.Settings.AddOns.LoanRCAccount Then AccountClassList.Add(isefinAccountClass.LoanRC)
      For Each ProductType In finBL.ProductTypes
          If finBL.AccountTypes.GetAvailableAccountTypes(ProductType.ProductTypeId, True, AccountClassList, AccountApp.BranchId).Count = 0 Then
            ' No Account Types
          Else
            .ProductTypes.Add(New ProductTypeInfo(ProductType))
            ProductTypeIds.Add(ProductType.ProductTypeId)
          End If
      Next
      
      For Each AccountType In finBL.AccountTypes
        If AccountType.Active AndAlso ProductTypeIds.Exists(AccountType.ProductTypeId)  Then
          If AccountType.AccountClass = isefinAccountClass.Disbursement Then
            ' Do not include Disbursements
          ElseIf finBL.AccountTypeFunctions.IsAccountTypeAvailable(AccountType.AccountTypeId, AccountApp.BranchId, True) Then
            .AccountTypes.Add(New AccountTypeInfo(AccountType))
          End If
        End If
      Next

      ' Lists    
      
      ' Configuration
      .AddOnsPromotions = finBL.Settings.AddOns.Promotions
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
    End With
  End If

  ' Further Validations
  If Success Then
    If FormInitialisationInfo.ReadOnly AndAlso FormInitialisationInfo.IsNew Then
      Success = False
      finBL.Error.ErrorBegin("Cannot add a new Account Application Quote whilst form is Read-Only.")
    End If
  End If

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

  Return Success

End Function



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

  ' Record
  Public IsNew As Boolean
  
  ' Quote
  Public Name As String
  Public Key  As String
  Public KeyLocked As Boolean
  
  Public UserInvalid As Boolean
  Public UserInvalidReason As String
  
  Public Notes As String
  
  ' Account
  Public Account As AccountDetails
  Public AccountSummaryHtml As String

  ' Lists
  Public AccountTypes As New List(Of AccountTypeInfo)
  Public ProductTypes As New List(Of ProductTypeInfo)

  ' Global Collections

  ' Configuration
  Public AddOnsPromotions As Boolean
  Public CanDelete As Boolean
  Public PromptOnSave As Boolean
  Public [ReadOnly] As Boolean

End Class



''' &lt;summary&gt;
'''  Simple information about an Account Type.
''' &lt;/summary&gt;
Public Class AccountTypeInfo

  Public AccountClass As String
  Public AccountTypeId As String
  Public Description As String
  Public HasPromotions As Boolean
  Public Icon As String
  Public ProductTypeId As String
  Public Promotions As Object
  Public PromotionMandatory As Boolean
  'Public ShowFinancialPagePrintQuotation As Boolean

  Public Sub New(accountType As finAccountTypeRO)

    Dim BrokerId As String
    Dim DealerId As String
    Dim Promotion As finAccountTypePromotionRO
    Dim PromotionsList As ISCodeDescriptionList = finBLShared.CreateCodeDescriptionList()

    ' External User details
    Select Case finBLShared.CurrentUserInformation.ExternalPartyType
      Case isefinExternalPartyType.Broker
        BrokerId = finBLShared.CurrentUserInformation.ExternalPartyId
      Case isefinExternalPartyType.Dealer
        DealerId = finBLShared.CurrentUserInformation.ExternalPartyId
    End Select

    With accountType
      Me.AccountClass = .AccountClass.ToString()
      Me.AccountTypeId = .AccountTypeId
      Me.Description = .Description
      If Len(.Icon) = 0 Then
        Me.Icon = "AccountType"
      Else
        Me.Icon = "AccountType_" &amp; .Icon
      End If
      Me.ProductTypeId = .ProductTypeId

      ' Promotion Information
      ' NOTE: HasPromotions must be set to True at this point if the Account Type has ANY active Promotions (unless this is an External User in which case they will never change)
      If finBLShared.Settings.AddOns.Promotions AndAlso .PromotionBasis &lt;&gt; isefinAccountTypePromotionBasis.DoesNotUsePromotions Then
        If Len(BrokerId) &lt;&gt; 0 OrElse Len(DealerId) &lt;&gt; 0 Then
          ' External User
          For Each Promotion In .Promotions.GetAvailablePromotions("", BrokerId, DealerId, New ISList(), True)
            If Not Promotion.Closed Then
              PromotionsList.Add(Promotion.PromotionId, Promotion.Description)
            End If
          Next
        Else
          ' Other
          For Each Promotion In .Promotions
            If Not Promotion.Closed Then
              PromotionsList.Add(Promotion.PromotionId, Promotion.Description)
            End If
          Next
        End If
      End If

      Me.HasPromotions = PromotionsList.Count &lt;&gt; 0      
      Me.Promotions = PromotionsList.ToJsonObject()
      Me.PromotionMandatory = (.PromotionBasis = isefinAccountTypePromotionBasis.MustUsePromotion)

      ' Configuration
      'Me.ShowFinancialPagePrintQuotation = .OptionShowFinancialPagePrintQuotation AndAlso finBL.Documents.Exists(.QuoteDocumentId)
    End With

  End Sub

End Class



''' &lt;summary&gt;
'''  Simple information about a Product Type.
''' &lt;/summary&gt;
Public Class ProductTypeInfo

  Public AccountTypesList As New List(Of String)
  Public Caption As String
  Public DefaultAccountTypeId As String
  Public Icon As String
  Public ProductTypeId As String

  Public Sub New(productType As finProductTypeRO)

    Dim AccountType As finAccountTypeRO

    With productType
      Me.Caption = .Description
      If Len(.Icon) = 0 Then
        Me.Icon = "ProductType"
      Else
        Me.Icon = "AccountType_" &amp; .Icon
      End If
      Me.ProductTypeId = .ProductTypeId
      Me.DefaultAccountTypeId = .DefaultAccountTypeId
    End With

    ' Available Account Types
    For Each AccountType In finBLShared.AccountTypes.GetAvailableAccountTypes(productType.ProductTypeId, False, Nothing, "")
      If AccountType.Active Then
          If AccountType.AccountClass = isefinAccountClass.Disbursement OrElse AccountType.AccountClass = isefinAccountClass.LoanRC Then
            ' Do not include Disbursement or Revolving Credit Accounts since this is a 'Quote'
          Else
            Me.AccountTypesList.Add(AccountType.AccountTypeId)
          End If
      End If
    Next

  End Sub

End Class



''' &lt;summary&gt;
'''  Finish Parameters.
''' &lt;/summary&gt;
''' &lt;summary&gt;
'''  Finish Parameters.
''' &lt;/summary&gt;
Public Class WizardFinishParameters
  
  ' Properties
  Public Name As String
  Public Key  As String
  
  Public UserInvalid As Boolean
  Public UserInvalidReason As String
  
  Public Notes As String
  
  ' Account
  Public Account As AccountDetails
  
End Class



''' &lt;summary&gt;
'''  Account Details (to keep this similar to the New Account Widget).
''' &lt;/summary&gt;
Public Class AccountDetails

  ' General
  Public AccountTypeId As String
  Public AccountTypeIdOriginal As String ' Tracks changes of Account Type
  Public AccountTypePromotionId As String
  Public ProductTypeId As String ' Makes initialisation easier since we don't need to look this up from the Account Type
  
  ' Internal Use only
  Public Action As String
  
  ' Objects
  Public AccountCalcJson As String

  Public Sub New()
  End Sub

  Public Sub New(account As finAccount)

    With account
      ' General
      Me.AccountTypeId = .AccountTypeId
      Me.AccountTypeIdOriginal = .AccountTypeId
      Me.AccountTypePromotionId = .AccountTypePromotionId
      Me.ProductTypeId = .AccountType.ProductTypeId
      
      ' Calculation
      ' NOTE: Include configuration details but not schedule
      Me.AccountCalcJson = .Calculation.ToHtmlWidgetJsonString(True, False, True, Nothing)
    End With
  End Sub

End Class



''' &lt;summary&gt;
'''  Calculation details.
''' &lt;/summary&gt;
Public Class CalculationDetails

  Public Account As AccountDetails
  Public AccountSummaryHtml As String

  Public Sub New(account As AccountDetails,
                 accountSummaryHtml As String)

    Me.Account = account
    Me.AccountSummaryHtml = accountSummaryHtml

  End Sub

End Class



''' &lt;summary&gt;
'''  Finish details.
''' &lt;/summary&gt;
Public Class WizardFinishDetails

  Public Warning As String

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

Used as a finPOWER Connect Cloud compatible version for editing an Account Application Quote.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;style type="text/less"&gt;
/* 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;
    height:50%;
    flex-grow:1;
    flex-shrink:0;
  }

  &gt; div:last-child {
    position:relative;
    overflow:auto;
    height:50%;
    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;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="Properties" tooltipText="Properties of this Account Application Quote."&gt;Quote Properties&lt;/li&gt;
        &lt;li tabId="AccountType" tooltipText="Specify Account Type details for this Quote."&gt;Account Type&lt;/li&gt;
        &lt;li tabId="Financial" tooltipText="Specify Financial details for this Quote."&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;!-- Properties --&gt;
    &lt;div id="pageProperties"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblQuoteProperties"&gt;Specify a Key and Name for this Quote&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtKey"&gt;Key:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtKey"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblQuoteInvalid"&gt;Indicate whether this Quote is Invalid&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkUserInvalid" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td colspan="2" class="indent1"&gt;&lt;input id="txtUserInvalidReason"/&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label&gt;Notes&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="txtNotes"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;


    &lt;!-- Account Type --&gt;
    &lt;div id="pageAccountType" 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="lblProductType"&gt;Select a Product&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;div id="blProductTypes"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblAccountType"&gt;Select an Account Type&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountType"&gt;Account Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountType"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountTypePromotion"&gt;Promotion:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountTypePromotion"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/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="cmdActions"/&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_Account;

// Global Collections
var mAccountTypes;
var mProductTypes;

// Controls
var C = {
  //   Quote
  lblQuoteProperties: null,
  txtKey: null,
  txtName: null,
  
  lblQuoteInvalid: null,
  chkUserInvalid: null,
  txtUserInvalidReason: null,
  
  txtNotes: null,
  
  //   Account Type
  lblProductType: null,
  blProductTypes: null,

  lblAccountType: null,
  cboAccountType: null,
  cboAccountTypePromotion: null,
  
  //   Financial
  afFinancial: null,
  wbAccountSummary: null,
}

// Form
var frmMain;
var tabWizard;

// Other

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

// Other
var mAccountType;
var mAccountTypePromotionChanged = false;
var mCalculationTimer;
var mProductType;
var mRecalcRequired = false;

// ==========
// Initialise
// ==========
$(function () {
  // Mobile optimisations
  var currencyWidth = "20em";
  $(window).resize(Form_Resize);

  // --------
  // Controls
  // --------
  //   Quote
  C.lblQuoteProperties = widget.UI.Label("lblQuoteProperties", {});
  C.txtKey = widget.UI.TextBox("txtKey", {
    changeWhileTyping: true, // So blank tip on Name can update instantly
    maxLength: 20,
    width: widget.UI.FIELD_WIDTH_CODE_20,
    
    onChange: txtKey_Change
  });
  C.txtName = widget.UI.TextBox("txtName", {
    maxLength: 50,
  });
  
  C.lblQuoteInvalid = widget.UI.Label("lblQuoteInvalid", {});
  C.chkUserInvalid = widget.UI.CheckBox("chkUserInvalid", {
    caption: "Quote is Invalid and should not be used",
    
    onChange: chkUserInvalid_Change,
  });
  C.txtUserInvalidReason = widget.UI.TextBox("txtUserInvalidReason", {
    blankTip: "Reason",
    maxLength: 100,
  });
  
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
    rows: 6,
  });
  
  // Account Type
  C.lblProductType = widget.UI.Label("lblProductType", {});
  C.blProductTypes = widget.UI.ButtonList("blProductTypes", {
    allowBlank: false,

    onChange: blProductTypes_Change
  });
  
  C.lblAccountType = widget.UI.Label("lblAccountType", {});
  C.cboAccountType = widget.UI.DBCombo("cboAccountType", {
    allowBlank: false,
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboAccountType_Change,
  });
  C.cboAccountTypePromotion = widget.UI.DBCombo("cboAccountTypePromotion", {
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onChange: cboAccountTypePromotion_Change,
  });
  
  //   Financial
  C.afFinancial = widget.UI.AccountFinancial("afFinancial", {
    visible: false, // Hide until first calculated
    onAction: afFinancial_Action,
    onChange: afFinancial_Change,
  });
  C.wbAccountSummary = widget.UI.PreviewPane("wbAccountSummary", {});
  
  // Create Widget form
  // NOTE: Hide by default for a cleaner startup
  frmMain = new widget.UI.Form("frmMain", { visible: false });

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

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

  // Reset
  Form_Reset();
});

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

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

  // Resize
  Form_Resize();

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

// ===========
// Load Record
// ===========
function Record_Load() {
  // Initialise
  mRecord = null;
  mRecord_Account = null;

  // 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_Account = mRecord.Account;
      
      // Global Collections
      mAccountTypes = mRecord.AccountTypes;
      mProductTypes = mRecord.ProductTypes;
      
      // Give Collections ability to lookup by code
      widget.ArrayAllowLookupById(mAccountTypes, "AccountTypeId");
      widget.ArrayAllowLookupById(mProductTypes, "ProductTypeId");

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

      // Skip first tab for existing records
      if (!mRecord.IsNew) tabWizard.SelectedTabId("AccountType");
      
      // Load Fields
      Fields_Load();
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {    
    // Properties
    C.txtKey.Text(mRecord.Key);
    C.txtName.Text(mRecord.Name);
    
    C.chkUserInvalid.Value(mRecord.UserInvalid);
    C.txtUserInvalidReason.Text(mRecord.UserInvalidReason);
    
    C.txtNotes.Text(mRecord.Notes);
    
    // Account Type
    blProductTypes_Refresh();
    C.blProductTypes.SelectedItemId(mRecord_Account.ProductTypeId);
    C.cboAccountType.Text(mRecord_Account.AccountTypeId);
    cboAccountType_Change();
    C.cboAccountTypePromotion.Text(mRecord_Account.AccountTypePromotionId);
    
    // Financial
    C.afFinancial.FromAccountCalcJson(mRecord_Account.AccountCalcJson);
    C.afFinancial.Visible(true);
    C.wbAccountSummary.SetContent(mRecord.AccountSummaryHtml, false);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();
  
  // Finalise
  mAccountTypePromotionChanged = false;
  mRecalcRequired = false;

  // Refresh Tab
  tabWizard_Refresh();
}

// ===========
// Save Fields
// ===========
function Fields_Save(fieldUpdated) {
  // Properties
  mRecord.Key = C.txtKey.Text();
  mRecord.Name = C.txtName.Text();
  
  mRecord.UserInvalid = C.chkUserInvalid.Value();
  mRecord.UserInvalidReason = C.txtUserInvalidReason.Text();
  
  mRecord.Notes = C.txtNotes.Text();

  // Account Type
  mRecord_Account.ProductTypeId = C.blProductTypes.SelectedItemId();
  mRecord_Account.AccountTypeId = C.cboAccountType.Text();
  mRecord_Account.AccountTypePromotionId = C.cboAccountTypePromotion.Text();
  
  // Financial
  var accountCalc = C.afFinancial.ToAccountCalc();
  
  // Update properties not in the AccountFinancial control
  accountCalc.AccountTypePromotionId = C.cboAccountTypePromotion.Text();

  // Set Field Updated (allows calculation to do special stuff like keep dates in sync)
  accountCalc.FieldUpdated = fieldUpdated;

  // Convert to JSON
  mRecord_Account.AccountCalcJson = JSON.stringify(accountCalc);  
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  var heading = "Account Application Quote";
  if (mRecord &amp;&amp; mRecord.IsNew) heading = "New " + heading;
  widget.SetHeading(heading);

  // Lists
  if (mRecord) {
  }

  // Controls
  if (mRecord) {
    // Properties
    if (mRecord.KeyLocked) C.txtKey.ReadOnly(true);
    txtKey_Change();
    chkUserInvalid_Change();
  }

  // Update Buttons
  tabWizard_UpdateButtons();

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

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

  // Resize Tab
  tabWizard_Resize();
}

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

  // Tab
  tabWizard_Resize();
}

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

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

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

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "Properties":
      // Properties
      C.txtName.WidthResizeFromParent();
      C.txtUserInvalidReason.WidthResizeFromParent();
      C.txtNotes.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 "Financial":
        // NOTE: Passing a second parameter as a blank string forces the wait message to appear
        if (mRecalcRequired) Calculate("", ""); 
        break;
        
      default:
        break;
    }
  }

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

  // Special
  switch(tabWizard.SelectedTabId()) {
  }

  // Tweak fields

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

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

  // Resize Wizard
  tabWizard_Resize();

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

// ===============
// Validate Wizard
// ===============
function tabWizard_Validate(validCallback) {
  // Read-Only
  if (mRecord.ReadOnly) {
    // No validation because form is Read Only
    validCallback();
    return;
  }

  // Validate
  var Ok = tabWizard.Validate(true);

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      //case "Properties":
    
      default:
        // No validation
        validCallback();
        return;
    }
  }

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

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

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

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

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

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

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

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

          // Allow callbacks to continue
          return;
        };

        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

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

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

    case "MOVETOP":
      Form_ExecuteAction_MoveTop();
      break;

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

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

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

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

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

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

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

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

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

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

  // Create Parameters
  var params = mRecord;

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

      // Finalise
      if (data.Warning) {
        widget.UI.MsgBoxAlert("The Quote was successfully updated but the following warning was given:\n\n" + data.Warning, {}, Form_ExecuteAction_FinishPost_Finalise);
      }
      else {
        Form_ExecuteAction_FinishPost_Finalise(data);
      }
    },

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

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

function Form_ExecuteAction_FinishPost_Finalise(data) {  
  // Close Form
  widget.Close();

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

// ==============
// blProductTypes
// ==============
function blProductTypes_Refresh() {
  // Build Product Types List
  var buttons = [];
  for(var i = 0; i &lt; mProductTypes.length; i++) {
    var item = mProductTypes[i];

    buttons.push({ id: item.ProductTypeId,
                   caption: item.Caption,
                   icon: item.Icon });
  }
  C.blProductTypes.ButtonsDefine(buttons);

  // Hide?
  if (buttons.length &lt;= 1) {
    C.blProductTypes.VisibleRow(false);
    if (buttons.length == 1) C.blProductTypes.SelectedItemIndex(0);
  }
  else {
    C.blProductTypes.VisibleRow(true);
  }
}

function blProductTypes_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Get Product Type
  mProductType = C.blProductTypes.SelectedItemIndex() == -1 ? null : mProductTypes[C.blProductTypes.SelectedItemIndex()];

  // Refresh Account Types
  cboAccountType_Refresh();
    
  // Reset if User has changed Product Type
  if (sender) {
    if (mProductType &amp;&amp; mProductType.DefaultAccountTypeId) {
      C.cboAccountType.Text(mProductType.DefaultAccountTypeId);
    }
    else {
      C.cboAccountType.Text("");
    }
  }
  cboAccountType_Change();

  // Financial needs refreshing?
  if (sender) mRecalcRequired = true;
}

// ==============
// cboAccountType
// ==============
function cboAccountType_Refresh() {
  var list = [];
  
  // Build list of Account Types for this Product Type
  if (mProductType) {
    for (var i = 0; i &lt; mAccountTypes.length; i++) {
      var item = mAccountTypes[i];
      
      if (item.ProductTypeId == mProductType.ProductTypeId) {
        list.push(item);
      }
    }
  }
  C.cboAccountType.RefreshFromCollection(list, "AccountTypeId", "Description");
}

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

  // Get Account Type
  mAccountType = mAccountTypes.GetItem(C.cboAccountType.Text());

  // Refresh Promotions List
  if (mRecord.AddOnsPromotions) {
    cboAccountTypePromotions_Refresh();
  }
  else {
    C.cboAccountTypePromotion.VisibleRow(false);
  }

  // Financial needs refreshing?
  if (sender) {
    mAccountTypePromotionChanged = true;
    mRecalcRequired = true;
  }
}

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

  // Financial needs refreshing?
  if (sender) {
    mAccountTypePromotionChanged = true;
    mRecalcRequired = true;
  }
}

function cboAccountTypePromotions_Refresh() {
  if (!mAccountType || !mAccountType.HasPromotions) {
    C.cboAccountTypePromotion.VisibleRow(false);
    C.cboAccountTypePromotion.Text("");
  }
  else {
    C.cboAccountTypePromotion.VisibleRow(true);
    C.cboAccountTypePromotion.AllowBlank(!mAccountType.PromotionMandatory);
    C.cboAccountTypePromotion.RefreshFromCodeDescriptionList(mAccountType.Promotions);
  }
}

// ===========
// 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 "Reset":
      // Reset
      widget.UI.MsgBoxConfirm("Are you sure you want to reset all Financial details to their defaults (as defined on the Account Type)?", { heading: "Reset Financial" },
        function() {
          Calculate(null, actionId);
        });
      break;

    case "ScheduleShow":
      // Show Schedule
      ScheduleShow();
      break;

    case "StdTransReset":
      // Reset Standard Transactions
      widget.UI.MsgBoxConfirm("Are you sure you want to reset all Transactions to their defaults (as defined on the Account Type)?", { heading: "Reset Transactions" },
        function() {
          Calculate(null, actionId);
        });
      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(fieldUpdated);
  }
  else {
    // Delayed calculation
    mCalculationTimer = window.setTimeout(function () {
      mCalculationTimer = null;    
      Calculate();
    }, 500);
  }
}

// =======================
// Regular Payments Create
// =======================
function afFinancial_OverridingPaymentsHandling(action) {
  // Block
  widget.UI.Block("Updating Overriding Payments, please wait...");
  
  // Save
  Fields_Save();
  
  // Params
  var params = {
    action: action,
    accountJson: JSON.stringify(mRecord_Account),
    overridingPaymentsJson: C.afFinancial.GetOverridingPaymentsJson(),    
  }
  
  // Create Payments
  widget.GetString("OverridingPaymentsHandling", params, afFinancial_OverridingPaymentsHandling_Done, afFinancial_OverridingPaymentsHandling_Fail0);
}

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

function afFinancial_OverridingPaymentsHandling__Fail(error) {
  // Unblock
  widget.UI.Unblock();
  
  // Error
  widget.UI.MsgBoxAlert(errorMessage);
}

// =========
// Calculate
// =========
function Calculate(fieldUpdated, action) {
  // Save Fields
  Fields_Save(fieldUpdated);

  // Block UI
  if (action) {
    widget.UI.Block("Actioning, please wait...");
  }
  else if(action === "") {
    widget.UI.Block("Calculating, please wait...");
  }
  else {
    // Do not block UI
  }

  // Set Action
  mRecord_Account.Action = action ? action : "";

  // If Account Type or Promotion has changed, force Account Type to recalculate, i.e., apply defaults
  if (mAccountTypePromotionChanged) {
    var accountCalc = JSON.parse(mRecord_Account.AccountCalcJson);
    if (accountCalc.AccountTypeIdOriginal &amp;&amp; accountCalc.AccountTypeIdOriginal.length != 0) {
      accountCalc.AccountTypeIdOriginal = "[[Recalc]]";
    }
    else {
      accountCalc.AccountTypeIdOriginal = "";
    }
    mRecord_Account.AccountCalcJson = JSON.stringify(accountCalc);
  }

  // Calculate
  widget.GetString("Calculate", mRecord_Account, Calculate_Done, Calculate_Fail);
}

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

  // Update record
  mRecord_Account.AccountTypeIdOriginal = data.Account.AccountTypeId;
  mRecord_Account.AccountCalcJson = data.Account.AccountCalcJson;

  // Update Financial
  C.afFinancial.FromAccountCalcJson(data.Account.AccountCalcJson);
  C.afFinancial.Visible(true);

  // No longer needs initialising
  mRecalcRequired = false;
  mAccountTypePromotionChanged = false;

  // Update Summary
  C.wbAccountSummary.SetContent(data.AccountSummaryHtml, false);

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

function Calculate_Fail(error) {
  C.wbAccountSummary.SetContentError(error);

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

// =============
// Show Schedule
// =============
function ScheduleShow() {
  // Block UI
  widget.UI.Block("Fetching Schedule, please wait...");

  // Clear Field Updated and Action
  mRecord_Account.Action = "";
  mRecord_Account.FieldUpdated = "";

  // Calculate
  widget.GetString("GetAccountSchedule", mRecord_Account, ScheduleShow_Done, ScheduleShow_Fail);
}

function ScheduleShow_Done(data) {
  // Unblock UI
  widget.UI.Unblock();

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

function ScheduleShow_Fail(error) {
  // Unblock UI
  widget.UI.Unblock();

  widget.UI.MsgBoxAlert(error);
}

// ======
// txtKey
// ======
function txtKey_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  C.txtName.BlankTip(C.txtKey.Text());
}

// ==============
// chkUserInvalid
// ==============
function chkUserInvalid_Change(sender, e) {
  C.txtUserInvalidReason.VisibleRow(C.chkUserInvalid.Value());
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>Ibb5cykm0U+cCZDKn74w2g</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <Icon />
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>false</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Form options.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>If you do not specify a Default Transaction Type, the Transaction Type selection will be shown regardless of the settings specified below.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ReadOnly" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>These are the Parameters required by this HTML Widget to function correctly.
They are listed here for testing purposes only.</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="AccountAppPk" 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>false</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="AccountAppCalculationPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>Specify -1 to add a new Quote.</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>false</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>