<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-01-16T23:43:50.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2022-03-24T03:31:48.1330000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2023-01-16T23:43:23.0520000</UpdatedUtcDate>
    <ScriptId>WAR</ScriptId>
    <Description>Account Refinance</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountRefinance
Option Explicit On
Option Strict On

' #################################################################
' Account Refinance wizard HTML Widget
'
' Version: 1.06 (17/01/2023)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.04  23/04/2021  ISS                Updated
'    1.05  23/03/2022  ISS      J028149   Removed obsoleted Account Type Promotion Functions
'    1.06  17/01/2023  ISS      J030030   Improved Refinance calculation
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountRefinance"

' Common Parameters
Private mAccountId As String

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

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

    Case "GetPromotions"
      ' Get Promotions
      Main = GetPromotions(parametersJson, returnValue)

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

    Case "Form_AccountSummary_Refresh"
      ' Get updated Summary Page
      Main = Form_AccountSummary_Refresh(parametersJson, returnValue)

    Case "Form_RefinanceSummary_Refresh"
      ' Get updated Summary Page
      Main = Form_RefinanceSummary_Refresh(parametersJson, returnValue)

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

End Function

Private Function GetAccountTypeInfo(account As finAccount) As List(Of AccountTypeInfo)

  Dim AccountType As finAccountTypeRO
  Dim AccountTypeInfoList As List(Of AccountTypeInfo)

  AccountTypeInfoList = New List(Of AccountTypeInfo)

  For Each AccountType In finBL.AccountTypes
    If AccountType.Active AndAlso AccountType.ProductTypePk = account.ProductTypePk AndAlso AccountType.OptionAllowRefinanceInto Then
      AccountTypeInfoList.Add(New AccountTypeInfo(finBL, account, AccountType))
    End If
  Next

  Return AccountTypeInfoList

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 AccountClose As finAccountClose
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean
  Dim swb As ISSqlWhereBuilder

  ' Assume Success
  Success = True

  ' Validate
  If Len(mAccountId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Account Id not specified.")
  ElseIf finBL.CurrentUserInformation.IsAccountFilteredOut(mAccountId) Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to view this record.")
  ElseIf Not finBL.CurrentUser.Permissions.Allow("Account.Loan.Close.Refinanced") Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to Refinance a Loan Account.")
  ElseIf finBL.Database.IsReadOnly Then
    Success = False
    finBL.Error.ErrorBegin("Access denied. Database is Read-Only.")
  End If

  ' Create Account Close object
  If Success Then
    Success = Me.CreateAccountClose(Nothing, AccountClose)
  End If

  ' Validate Account
  If Success Then
    Select Case AccountClose.Account.AccountClass
      Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
      Case Else
        Success = False
        finBL.Error.ErrorBegin("Invalid class of Account.")
    End Select
  End If

  ' Create Refinance Account object
  If Success Then
    Success = Me.CreateAccountRefinance(AccountClose, Nothing, Account)
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Account
      .AccountId = AccountClose.Account.AccountId
      .AccountName = AccountClose.Account.Name
      .AccountTypeId = AccountClose.Account.AccountTypeId
      .AccountTypePromotionId = AccountClose.Account.AccountTypePromotionId
      .CloseDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(AccountClose.CloseDate)
      .CloseNote = AccountClose.CloseNote

      ' Refinance
      .RefinanceAccountTypeId = Account.Calculation.AccountTypeId
      .RefinanceAccountTypePromotionId = Account.Calculation.AccountTypePromotionId
      .RefinancePaymentCycle = Account.Calculation.PaymentCycle
      .RefinanceTermCycle = Account.Calculation.TermCycle
      .RefinanceTermNumberOfPayments = Account.Calculation.TermNumberOfPayments

      ' Account Summary
      .AccountSummaryHtml = finBL.SummaryPageFunctions.AccountCloseSummary(False, AccountClose, "General", 0, CreateScriptContextData())

      ' Permissions

      ' Lists
      swb = finBL.Database.CreateSqlWhereBuilderForDataView()
      With swb
        .AppendComparisonIntegerBoolean("Active" , "=", True)
        .AppendComparisonInteger("ProductTypePk", "=", AccountClose.Account.ProductTypePk)
        .AppendComparisonIntegerBoolean("OptionAllowRefinanceInto" , "=", True)
      End With
      .AccountTypeFilter = swb.SqlWhere
      .AccountTypeInfoList = Me.GetAccountTypeInfo(AccountClose.Account)
      .CloseNoteInformationListId = AccountClose.Account.ProductType.AccountCloseNoteRefinanceInformationListIdResolved

      ' Configuration
      .AddOnsPromotions = finBL.Settings.AddOns.Promotions
      .PromptOnCommit = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnCommit
    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 Promotions.
''' &lt;/summary&gt;
Public Function GetPromotions(parametersJson As String,
                              ByRef response As String) As Boolean

  Dim AccountClose As finAccountClose
  Dim obj As Object
  Dim Promotion As finAccountTypePromotionRO
  Dim Promotions As ISCodeDescriptionList
  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 Close object
  If Success Then
    Success = Me.CreateAccountClose(WizardFinishParameters, AccountClose)
  End If

  ' Get Promotions
  If Success Then
    Promotions = finBL.Runtime.CreateCodeDescriptionList()

    For Each Promotion In finBL.AccountTypes(WizardFinishParameters.RefinanceAccountTypeId).Promotions.GetAvailablePromotions(AccountClose.Account)
      Promotions.Add(Promotion.PromotionId, Promotion.Description)
    Next
  End If

  ' Response
  If Success Then
    response = Promotions.ToJsonString()
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Create Context Data for Scripts.
''' &lt;/summary&gt;
Private Function CreateScriptContextData() As ISKeyValueList

  CreateScriptContextData = finBL.CreateKeyValueList()
  With CreateScriptContextData
    .SetObject("Target", ScriptInfo.Target)
    .SetBoolean("HighDpi", finBL.HighDpi)
    .SetString("FormKey", FORM_KEY)
    .SetString("FormRecordMode", iseFormRecordMode.Loaded.ToString())
  End With

End Function

''' &lt;summary&gt;
'''  Create a finAccountClose object from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateAccountClose(parameters As WizardFinishParameters,
                                    ByRef accountClose As finAccountClose) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Initialise
  accountClose = finBL.CreateAccountClose()

  ' Update
  If Success Then
    With accountClose
      ' Load Account
      Success = .AccountLoad(mAccountId)

      ' Update
      If Success Then
        ' General
        .CloseMethod = isefinAccountCloseMethod.Refinanced

        ' Parameters
        If parameters IsNot Nothing Then
          .CloseDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(parameters.CloseDate)
          .CloseNote = parameters.CloseNote
        End If

        ' Calculate
        Success = .Calculate()
      End If

      ' Update Account Close for Refinance
      If Success Then
        .ClosePending = True
        .RefinanceOption = isefinAccountCloseRefinanceOption.NewAccount
        .RefinanceAccountTypeId = .Account.AccountTypeId
        .RefinanceAccountTypePromotionId = .Account.AccountTypePromotionId

        ' Parameters
        If parameters IsNot Nothing Then
          .RefinanceAccountTypeId = parameters.RefinanceAccountTypeId
          .RefinanceAccountTypePromotionId = parameters.RefinanceAccountTypePromotionId
        End If
      End If
    End With
  End If

  Return Success

End Function

Private Function CreateAccountRefinance(accountClose As finAccountClose,
                                        parameters As WizardFinishParameters,
                                        ByRef account As finAccount) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Account
  If Success Then
    If parameters Is Nothing Then
      Success = AccountClose.CreateRefinanceAccount(account)
    Else 
      With parameters
        Success = AccountClose.CreateRefinanceAccountHtmlWidget(account, .AdditionalAdvance, .PaymentCycle, .TermNumberOfPayments, .TermCycle)
      End With  
      
      ' Calculate
      Success = account.Calculation.Calculate()
    End If      
  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 AccountClose As finAccountClose
  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

  ' Begin Database Transaction
  If Success Then
    If finBL.Database.TransactionBegin Then
      ' Create Account Close object
      Success = Me.CreateAccountClose(WizardFinishParameters, AccountClose)

      ' Commit Account Close
      If Success Then
        With WizardFinishParameters
          Success = AccountClose.ExecuteCommitRefinanceHtmlWidget(.AdditionalAdvance, .PaymentCycle, .TermNumberOfPayments, .TermCycle)
        End With        
      End If      

      ' Open Account
      If Success Then
        Success = finBL.AccountFunctions.StatusQuoteToOpen(AccountClose.RefinancedAccountId)
      End If

      ' Commit/ Rollback
      If Success Then
        finBL.Database.TransactionCommit()
      Else
        finBL.Database.TransactionRollback()
      End If
    Else
      Success = False
    End If
  End If

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

  Return Success

End Function

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

  Dim ConfirmList As List(Of String)
  Dim Data As Object
  Dim FailedControlId As String
  Dim FailedMessage As String
  Dim PageId As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  ' NOTE: Use the module mCombinedParameters since this contains Startup and event Parameters in a single Key/Value List
  With mCombinedParameters
    PageId = .GetString("PageId")
  End With

  ' Validate Page
  Select Case PageId
    Case "General"
      ' General
      If WizardValidate_General(parametersJson, ConfirmList) Then
        Data = ConfirmList
      Else
        Success = False
      End If

    Case "Refinance"
      ' Refinance
  End Select

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

  Return Success

End Function

Private Function WizardValidate_General(parametersJson As String,
                                        ByRef confirmList As List(Of String)) As Boolean

  Dim AccountClose As finAccountClose
  Dim obj As Object
  Dim PendingWithdrawals As Decimal
  Dim Success As Boolean
  Dim WizardFinishParameters As WizardFinishParameters

  ' Assume Success
  Success = True

  ' Initialise ByRef
  confirmList = New List(Of String)()

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

  ' Create Account Close object
  If Success Then
    Success = Me.CreateAccountClose(WizardFinishParameters, AccountClose)
  End If

  If Success Then
    With AccountClose.Account
      ' Check Pending Withdrawals
      If .AccountType.CreditLimitUsePendingWithdrawals Then
        .GetPendingWithdrawals(PendingWithdrawals)
        If PendingWithdrawals &lt;&gt; 0 Then
          confirmList.Add("Pending withdrawals of " &amp; finBL.FormatCurrency(PendingWithdrawals, True) &amp; " exist.")
        End If
      End If
    End With
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Account Summary.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Public Function Form_AccountSummary_Refresh(parametersJson As String,
                                            ByRef response As String) As Boolean

  Dim AccountClose As finAccountClose
  Dim AccountSummaryHtml As String
  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 Close object
  If Success Then
    Success = Me.CreateAccountClose(WizardFinishParameters, AccountClose)
  End If

  ' Get Summary
  If Success Then
    AccountSummaryHtml = finBL.SummaryPageFunctions.AccountCloseSummary(False, AccountClose, "General", 0, CreateScriptContextData())
  End If

  ' Create Response
  If Success Then
    obj = New With { .AccountSummaryHtml = AccountSummaryHtml }
  End If

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Refinance Summary.
''' &lt;/summary&gt;
''' &lt;param name="parametersJson"&gt;
'''  A JSON formatted WizardFinishParameters object.
''' &lt;/param&gt;
Public Function Form_RefinanceSummary_Refresh(parametersJson As String,
                                              ByRef response As String) As Boolean

  Dim Account As finAccount
  Dim AccountClose As finAccountClose
  Dim obj As Object
  Dim RefinanceSummaryHtml As String
  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 Close object
  If Success Then
    Success = Me.CreateAccountClose(WizardFinishParameters, AccountClose)
  End If
  
  ' Create Refinance Account object
  If Success Then
    Success = Me.CreateAccountRefinance(AccountClose, WizardFinishParameters, Account)
  End If

  ' Get Summary
  If Success Then
    RefinanceSummaryHtml = finBL.SummaryPageFunctions.AccountFinancialSummary(False, Account, -1, CreateScriptContextData())
  End If

  ' Create Response
  If Success Then
    obj = New With { .RefinanceSummaryHtml = RefinanceSummaryHtml }
  End If

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

  Return Success

End Function

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

  ' Account
  Public AccountId As String
  Public AccountName As String
  Public AccountTypeId As String
  Public AccountTypePromotionId As String
  Public CloseDate As Date
  Public CloseNote As String

  ' Refinance
  Public RefinanceAccountTypeId As String
  Public RefinanceAccountTypePromotionId As String
  Public RefinancePaymentCycle As String
  Public RefinanceTermCycle As String
  Public RefinanceTermNumberOfPayments As Integer

  ' Account Summary
  Public AccountSummaryHtml As String

  ' Lists
  Public AccountTypeFilter As String
  Public AccountTypeInfoList As New List(Of AccountTypeInfo)
  Public CloseNoteInformationListId As String

  ' Configuration
  Public AddOnsPromotions As Boolean
  Public PromptOnCommit As Boolean

End Class


''' &lt;summary&gt;
'''  Validation details.
''' &lt;/summary&gt;
Public Class WizardValidateResponse

  Public Data As Object
  Public FailedMessage As String
  Public FailedControlId As String

  Public Sub New(data As Object,
                 failedMessage As String,
                 failedControlId As String)

    Me.Data = data
    Me.FailedMessage = failedMessage
    Me.FailedControlId = failedControlId

  End Sub

End Class


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

  ' General
  Public AdditionalAdvance As Decimal
  Public CloseDate As Date
  Public CloseNote As String
  Public RefinanceAccountTypeId As String
  Public RefinanceAccountTypePromotionId As String
  Public PaymentCycle As String
  Public TermCycle As String
  Public TermNumberOfPayments As Integer

End Class


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

  Public Sub New()
  End Sub

End Class


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

  Public AccountTypeId As String
  Public AllowAdditionalAdvance As Boolean
  Public HasPromotions As Boolean
  Public PaymentCycle As String
  Public PaymentCycleLimitToList As Boolean
  Public PaymentCycleList As String
  Public TermCycle As String
  Public TermCycleLimitToList As Boolean
  Public TermCycleList As String
  Public TermEntryMethodNumberOfPayments As Boolean
  Public TermEntryMethodTerm As Boolean
  Public TermNumberOfPayments As Integer

  Public Sub New(finBL As ISfinSupport,
                 account As finAccount,
                 accountType As finAccountTypeRO)

    With accountType
      Me.AccountTypeId = .AccountTypeId
      Me.AllowAdditionalAdvance = Len(.RefinanceAdvanceElementId) &lt;&gt; 0
      Me.HasPromotions = (finBL.Settings.AddOns.Promotions AndAlso .Promotions.GetAvailablePromotions(account).Count &lt;&gt; 0)
      Me.PaymentCycle = .PaymentCycle
      Me.PaymentCycleLimitToList = .PaymentCycleLimitToList
      Me.PaymentCycleList = .PaymentCycleListResolved
      Me.TermCycle =.Term
      Me.TermCycleLimitToList = .TermLimitToList
      Me.TermCycleList = .TermListResolved
      Me.TermEntryMethodNumberOfPayments = (.TermEntryMethod = isefinAccountTermEntryMethod.NumberOfPayments)
      Me.TermEntryMethodTerm = (.TermEntryMethod = isefinAccountTermEntryMethod.Term)
      Me.TermNumberOfPayments = .TermNumberOfPayments
    End With

  End Sub

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

Used as a finPOWER Connect Cloud compatible version of the form "AccountRefinance".

NOTE: This is a much simplified version of the wizard.</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content" style="visibility:hidden"&gt;

  &lt;!-- Form Header --&gt;
  &lt;header&gt;
    &lt;div class="header"&gt;&lt;/div&gt;
    &lt;div class="summary"&gt;&lt;/div&gt;
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General" tooltipText="Review Loan Account to Refinance."&gt;Account Details&lt;/li&gt;
        &lt;li tabId="Refinance"&gt;Refinance Details&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

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

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblAccount"&gt;Account&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRecord"&gt;Account:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRecord" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblOptions"&gt;Enter the Refinance date&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateClose"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="dateClose" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboCloseNote"&gt;Note:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboCloseNote" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblAccountSummary"&gt;Account Summary&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr style="height:100%"&gt;
          &lt;th colspan="2" style="height:100%"&gt;&lt;div id="wbAccountSummary"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Refinance --&gt;
    &lt;div id="pageRefinance"&gt;
      &lt;table class="is-form" style="height:100%"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:9em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblRefinance"&gt;Enter Refinance details&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;tr&gt;
          &lt;th&gt;&lt;label for="numAdditionalAdvance"&gt;Extra Advance:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numAdditionalAdvance"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numNumberOfPayments"&gt;No. Payments:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numNumberOfPayments"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboPaymentCycle"&gt;Frequency:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboPaymentCycle"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboTermCycle"&gt;Term:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboTermCycle"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblRefinanceSummary"&gt;Refinance Summary&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr style="height:100%"&gt;
          &lt;th colspan="2" style="height:100%"&gt;&lt;div id="wbRefinanceSummary"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

  &lt;/div&gt;

  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;span class="is-info-text wizard-footer" style="display:none"&gt;Startup Tooltip&lt;/span&gt;

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

&lt;/div&gt;



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

// Controls
var C = {
  // General
  lblAccount: null,
  cboRecord: null,

  lblOptions: null,
  dateClose: null,
  cboCloseNote: null,

  lblAccountSummary: null,
  wbAccountSummary: null,

  lblRefinance: null,
  cboAccountType: null,
  cboAccountTypePromotion: null,
  numAdditionalAdvance: null,
  numNumberOfPayments: null,
  cboPaymentCycle: null,
  cboTermCycle: null,

  lblRefinanceSummary: null,
  wbRefinanceSummary: null,
}

// Form
var frmMain;
var tabWizard;

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

// Other
var mAccountTypeInfo;
var mPromotions;
var mRefreshTimer;

// ==========
// Initialise
// ==========
$(function () {

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

  C.lblOptions = widget.UI.Label("lblOptions", {});
  C.dateClose= widget.UI.DateBox("dateClose", {
    allowBlank: false,
    onChange: dateClose_Change,
  });
  C.cboCloseNote = widget.UI.InformationListComboBox("cboCloseNote", {
    allowBlank: true,
    maxLength: 50,
  });

  C.lblAccountSummary = widget.UI.Label("lblAccountSummary", {});
  C.wbAccountSummary = widget.UI.PreviewPane("wbAccountSummary", {});

  // Refinance
  C.lblRefinance = widget.UI.Label("lblRefinance", {});
  C.cboAccountType = widget.UI.DBCombo("cboAccountType", {
    allowBlank: false,
    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: pageRefinance_Change,
  });
  C.numAdditionalAdvance = widget.UI.NumberBox("numAdditionalAdvance", {
    decimals: -1,
    minValue: 0.00,
    maxValue: 999999999.99,

    onChange: pageRefinance_Change,
  });
  C.numNumberOfPayments = widget.UI.NumberBox("numNumberOfPayments", {
    decimals: 0,
    blankIfZero: true,
    width: "4em",

    onChange: pageRefinance_Change,
  });
  C.cboPaymentCycle = widget.UI.DateCycleComboBox("cboPaymentCycle", {
    allowBlank: false,
    isFrequency: true,

    onChange: pageRefinance_Change,
  });
  C.cboTermCycle = widget.UI.DateCycleComboBox("cboTermCycle", {
    allowBlank: false,
    isFrequency: false,

    onChange: pageRefinance_Change,
  });

  C.lblRefinanceSummary = widget.UI.Label("lblRefinanceSummary", {});
  C.wbRefinanceSummary = widget.UI.PreviewPane("wbRefinanceSummary", {});

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

  // Resize
  Form_Resize();

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

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

  // Hide content
  frmMain.Visible(false);

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

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

      // Give Collections ability to lookup by code
      widget.ArrayAllowLookupById(mRecord.AccountTypeInfoList, "AccountTypeId");

      // Load Fields
      Fields_Load();
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboRecord.RefreshUnbound(mRecord.AccountId, mRecord.AccountName);

    C.dateClose.Value(mRecord.CloseDate);
    C.cboCloseNote.Text(mRecord.CloseNote);

    C.wbAccountSummary.SetContent(mRecord.AccountSummaryHtml, false);

    // Refinance
    C.cboAccountType.Text(mRecord.RefinanceAccountTypeId);
    C.cboAccountTypePromotion.Text(mRecord.RefinanceAccountTypePromotionId);
    C.numNumberOfPayments.Value(mRecord.RefinanceTermNumberOfPayments);
    C.cboPaymentCycle.Text(mRecord.RefinancePaymentCycle);
    C.cboTermCycle.Text(mRecord.RefinanceTermCycle);
  }

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

  // Update Controls
  if (mRecord) {
    if (!mRecord.AddOnsPromotions) C.cboAccountTypePromotion.VisibleRow(false);
  }

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

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

// =============
// Update Fields
// =============
function Fields_Update() {
  // Information Lists

  // Lists
  if (mRecord) {
    C.cboCloseNote.SetComboFromInformationList(mRecord.CloseNoteInformationListId, true, null, true);
    C.cboAccountType.RefreshFromStandardRange("AccountTypes", mRecord.AccountTypeFilter);
  }

  // Controls
  cboAccountType_Change();

  // Update Buttons
  tabWizard_UpdateButtons();

  // 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, 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 (tabWizard.TabCount() != 1) cmdFinish.prop("disabled", !cmdNext.prop("disabled"));
}

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

    case "Refinance":
      C.cboAccountType.WidthResizeFromParent();
      C.cboAccountTypePromotion.WidthResizeFromParent();
      C.cboPaymentCycle.WidthResizeFromParent();
      C.cboTermCycle.WidthResizeFromParent();
      C.wbRefinanceSummary.ResizeFromParent();
      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 "Refinance":
        // General
        pageRefinance_Refresh();

      default:
        break;
    }
  }

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

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

  // Tweak fields

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "Refinance":
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), "Refinance Account '" + mRecord.AccountId + "', " + mRecord.AccountName + ".");
      break;

    default:
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;
  }

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

  // Resize Wizard
  tabWizard_Resize();

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

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

  // Other client-side validation
  if (Ok) {
    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        if (mRefreshTimer) {
          widget.UI.MsgBoxInfo("Account has not been recalculated.\n\nPlease ensure you have reviewed Account information before proceeding.");
          Ok = false;
        }
        break;

      case "Refinance":
        // Refinance
        if (mRefreshTimer) {
          widget.UI.MsgBoxInfo("Refinance has not been recalculated.\n\nPlease ensure you have reviewed information before completing the Refinance.");
          Ok = false;
        }
        break;

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

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

    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 "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 () {
    if (mRecord.PromptOnCommit) {
      // Confirm
      var heading = "Refinance Account";
      var message = "Are you sure you want to Refinance Account '" + mRecord.AccountId + "', " + mRecord.AccountName + "?";

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

function Form_ExecuteAction_FinishPost() {
  // 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.Warning) {
        widget.UI.MsgBoxAlert("The Refinance was successful but the following warning was given:\n\n" + data.Warning, {}, function () { Form_ExecuteAction_FinishPost_Finalise(data); });
      }
      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();
}

// =========
// dateClose
// =========
function dateClose_Change(source, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Preview
  wbAccountSummary_Refresh();
}

// ================
// wbAccountSummary
// ================
function wbAccountSummary_Refresh() {
  // Update Controls
  C.wbAccountSummary.Clear();

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

  // Refresh after 250ms
  mRefreshTimer = window.setTimeout(function () {
    widget.GetString("Form_AccountSummary_Refresh", CreateFinishParameters(),
      function(data) { wbAccountSummary_Refresh_Done(data); },
      wbAccountSummary_Refresh_Fail);
  }, 250);
}

function wbAccountSummary_Refresh_Done(data) {
  // Clear Timer
  mRefreshTimer = null;

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

    // Update Record
    mRecord.AccountSummaryHtml = o.AccountSummaryHtml;

    // Load Fields
    C.wbAccountSummary.SetContent(mRecord.AccountSummaryHtml, false);
  }
}

function wbAccountSummary_Refresh_Fail(data) {
  widget.UI.MsgBoxAlert(data);
}

// =============
// pageRefinance
// =============
function pageRefinance_Refresh() {
  // Get Account Type
  mAccountTypeInfo = mRecord.AccountTypeInfoList.GetItem(C.cboAccountType.Text());

  // Update Page
  if (mAccountTypeInfo) {
    // Initialise Values
    C.numNumberOfPayments.Value(mAccountTypeInfo.TermNumberOfPayments);
    C.cboPaymentCycle.Text(mAccountTypeInfo.PaymentCycle);
    C.cboTermCycle.Text(mAccountTypeInfo.TermCycle);

    // Additional Advance
    C.numAdditionalAdvance.VisibleRow(mAccountTypeInfo.AllowAdditionalAdvance);

    // Number of Payments Entry
    if (mAccountTypeInfo.TermEntryMethodNumberOfPayments) {
      C.numNumberOfPayments.VisibleRow(true);
      C.cboPaymentCycle.VisibleRow(true);

      C.cboPaymentCycle.AllowBlank(!mAccountTypeInfo.PaymentCycleLimitToList);
      C.cboPaymentCycle.ListFromCsvString(mAccountTypeInfo.PaymentCycleList);
    }
    else {
      C.numNumberOfPayments.VisibleRow(false);
      C.cboPaymentCycle.VisibleRow(false);
    }

    // Term Entry
    if (mAccountTypeInfo.TermEntryMethodTerm) {
      C.cboTermCycle.VisibleRow(true);

      C.cboTermCycle.AllowBlank(!mAccountTypeInfo.TermCycleLimitToList);
      C.cboTermCycle.ListFromCsvString(mAccountTypeInfo.TermCycleList);
    }
    else {
      C.cboTermCycle.VisibleRow(false);
    }
  }
  else {
    C.numAdditionalAdvance.VisibleRow(false);
    C.numNumberOfPayments.VisibleRow(false);
    C.cboPaymentCycle.VisibleRow(false);
    C.cboTermCycle.VisibleRow(false);
  }

  // Update Preview
  wbRefinanceSummary_Refresh();
}

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

  // Get Account Type
  mAccountTypeInfo = mRecord.AccountTypeInfoList.GetItem(C.cboAccountType.Text());

  // Refresh Promotions List
  if (mRecord.AddOnsPromotions) cboAccountTypePromotions_Refresh();

  // Refresh Page
  pageRefinance_Refresh();
}

// ========================
// cboAccountTypePromotions
// ========================
function cboAccountTypePromotions_Refresh() {
  C.cboAccountTypePromotion.Text("");

  if (!mAccountTypeInfo || !mAccountTypeInfo.HasPromotions) {
    C.cboAccountTypePromotion.VisibleRow(false);
  }
  else {
    C.cboAccountTypePromotion.VisibleRow(true);
    C.cboAccountTypePromotion.AllowBlank(!mAccountTypeInfo.PromotionMandatory);

    // Create Parameters
    var params = CreateFinishParameters();

    widget.GetString("GetPromotions", params,
    function(data) {
      mPromotions = JSON.parse(data);
      C.cboAccountTypePromotion.RefreshFromCollection(mPromotions, "Code", "Description");
    },

    function(error) {
      widget.UI.MsgBoxAlert(error);
    });
  }
}

// =====================
// numAdditionalAdvance, numNumberOfPayments, cboPaymentCycle, cboTermCycle
// =====================
function pageRefinance_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Preview
  wbRefinanceSummary_Refresh();
}

// ================
// wbRefinanceSummary
// ================
function wbRefinanceSummary_Refresh() {
  // Update Controls
  C.wbRefinanceSummary.Clear();

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

  // Refresh after 500ms
  mRefreshTimer = window.setTimeout(function () {
    widget.GetString("Form_RefinanceSummary_Refresh", CreateFinishParameters(),
      function(data) { wbRefinanceSummary_Refresh_Done(data); },
      wbRefinanceSummary_Refresh_Fail);
  }, 500);
}

function wbRefinanceSummary_Refresh_Done(data) {
  // Clear Timer
  mRefreshTimer = null;

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

    // Update Record
    mRecord.RefinanceSummaryHtml = o.RefinanceSummaryHtml;

    // Load Fields
    C.wbRefinanceSummary.SetContent(mRecord.RefinanceSummaryHtml, false);
  }
}

function wbRefinanceSummary_Refresh_Fail(data) {
  widget.UI.MsgBoxAlert(data);
}

function CreateFinishParameters() {
  // Create Parameters
  var params = {
    CloseDate: C.dateClose.Value(),
    CloseNote: C.cboCloseNote.Text(),
    RefinanceAccountTypeId: C.cboAccountType.Text(),
    RefinanceAccountTypePromotionId: C.cboAccountTypePromotion.Text(),
    AdditionalAdvance: C.numAdditionalAdvance.Value(),
    TermNumberOfPayments: C.numNumberOfPayments.Value(),
    PaymentCycle: C.cboPaymentCycle.Text(),
    TermCycle: C.cboTermCycle.Text(),
  }

  return params;
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>Tagae+Q1kk+nq+E9SA54sg</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption />
    <HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</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="" 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="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>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>