<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-01-25T22:55:20.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2022-11-06T20:12:09.6070000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2023-01-25T22:54:36.3370000</UpdatedUtcDate>
    <ScriptId>ATST</ScriptId>
    <Description>Account Type Standard Transaction</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_AccountTypeStandardTransaction
Option Explicit On
Option Strict On

' #################################################################
' Account Type Standard Transaction wizard HTML Widget
'
' Version: 1.01 (26/01/2023)
'
' Usage: System-defined HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  08/11/2022  ISS      J029789   Created
'    1.01  11/01/2023  ISS      J030113   Deposit Element Types now support a Basis other than 'Set Value'          
'          23/01/2023  ISS      J030344   Improvements to the initialisation process
'          24/01/2023  ISS      J030092   Updates to support Account Type Promotions
'          26/01/2023  ISS      J030170   'Frequency' list incorrectly showed 'null' prior to an Element being selected
' #################################################################

' Constants
Private Const FORM_KEY As String = "AccountTypeStandardTransaction"

' Common Parameters
Private mAccountTypeId As String
Private mAccountTypeStdTranPk As Integer
Private mDuplicateRecordPk As Integer
Private mIsPromotion As Boolean
Private mPromotionAccountTypeStdTranJson As String
Private mPromotionPk As Integer
Private mPromotionStdTransactionPk 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
    mAccountTypeId = .GetString("AccountTypeId")
    mAccountTypeStdTranPk = .GetInteger("AccountTypeStdTranPk")
    mDuplicateRecordPk = .GetInteger("DuplicateRecordPk")
    mIsPromotion = .GetBoolean("IsPromotion")
    mPromotionAccountTypeStdTranJson = .GetString("PromotionAccountTypeStdTranJson")
    mPromotionPk = .GetInteger("PromotionPk")
    mPromotionStdTransactionPk = .GetInteger("PromotionStdTransactionPk")
    mReadOnly = .GetBoolean("ReadOnly")
  End With

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

    Case "Delete"
      ' Delete Standard Transaction
      Main = Delete(returnValue)

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

''' &lt;summary&gt;
'''  Create finAccountType and finAccountTypeStdTran objects from Web Service properties.
''' &lt;/summary&gt;
''' &lt;returns&gt;
'''  A Boolean value indicating success.
''' &lt;/returns&gt;
Private Function CreateAccountTypeStdTran(parameters As WizardFinishParameters,
                                          ByRef accountType As finAccountType,
                                          ByRef accountTypeStdTran As finAccountTypeStdTran) As Boolean

  Dim Success As Boolean  

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  accountType = finBL.CreateAccountType()
  accountTypeStdTran = Nothing

  ' Load Account Type
  Success = accountType.Load(mAccountTypeId)
  
  ' Validate Promotion
  If Success AndAlso mIsPromotion Then
    If mPromotionPk &lt;&gt; 0 AndAlso Not accountType.Promotions.ExistsPk(mPromotionPk) Then
      Success = False
      finBL.Error.ErrorBegin("Invalid Promotion.")    
    ElseIf mPromotionPk &lt;&gt; 0 AndAlso mPromotionStdTransactionPk &gt; 0 AndAlso Not accountType.Promotions.ItemByPk(mPromotionPk).StandardTransactions.ExistsPk(mPromotionStdTransactionPk) Then
      Success = False
      finBL.Error.ErrorBegin("Invalid Account Type Promotion Standard Transaction.")
    End If
  End If
  
  ' Get Standard Transaction
  If Success Then
    If mIsPromotion Then            
      If mPromotionPk = 0 OrElse mPromotionStdTransactionPk = -1 OrElse (mPromotionStdTransactionPk = 0 AndAlso Len(mPromotionAccountTypeStdTranJson) &lt;&gt; 0) Then
        accountTypeStdTran = accountType.Promotions.CreateAccountTypePromotion().StandardTransactions.CreateAccountTypeStdTran()
      ElseIf mPromotionPk &lt;&gt; 0 AndAlso mPromotionStdTransactionPk = -1 Then
        accountTypeStdTran = accountType.Promotions.ItemByPk(mPromotionPk).StandardTransactions.CreateAccountTypeStdTran()
      Else
        accountTypeStdTran = accountType.Promotions.ItemByPk(mPromotionPk).StandardTransactions.ItemByPk(mPromotionStdTransactionPk)
      End If
      
      ' Update
      If Len(mPromotionAccountTypeStdTranJson) &lt;&gt; 0 Then
        Success = accountTypeStdTran.FromHtmlWidgetJsonString(mPromotionAccountTypeStdTranJson)
      End If
    Else 
      If mAccountTypeStdTranPk = -1 AndAlso mDuplicateRecordPk = 0 Then
        accountTypeStdTran = accountType.StandardTransactions.CreateAccountTypeStdTran()
      ElseIf mAccountTypeStdTranPk = -1 AndAlso mDuplicateRecordPk &lt;&gt; 0 AndAlso accountType.StandardTransactions.ExistsPk(mDuplicateRecordPk) Then
        accountTypeStdTran = accountType.StandardTransactions.ItemByPk(mDuplicateRecordPk).Clone()
      ElseIf accountType.StandardTransactions.ExistsPk(mAccountTypeStdTranPk) Then
        accountTypeStdTran = accountType.StandardTransactions.ItemByPk(mAccountTypeStdTranPk)
      Else
        Success = False
        finBL.Error.ErrorBegin("Failed to retrieve Account Type Standard Transaction. This record may have been deleted by another User.")
      End If
    End If    
  End If

  ' Update Standard Transaction
  If Success AndAlso parameters IsNot Nothing Then
    Success = accountTypeStdTran.FromHtmlWidgetJsonString(parameters.StandardTransactionJson)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Delete Account Type Standard Transaction.
''' &lt;/summary&gt;
Private Function Delete(ByRef returnValue As String) As Boolean

  Dim AccountType As finAccountType
  Dim AccountTypeStdTran As finAccountTypeStdTran
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Create Account and Standard Transaction objects
  Success = CreateAccountTypeStdTran(Nothing, AccountType, AccountTypeStdTran)

  ' Delete and Save
  If Success Then
    ' Remove from collection
    Success = AccountType.StandardTransactions.Remove(AccountTypeStdTran)

    ' Save
    If Success Then
      Success = AccountType.Save()
    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 AccountType As finAccountType
  Dim AccountTypeStdTran As finAccountTypeStdTran
  Dim Index As Integer
  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 Type and Standard Transaction objects
  If Success Then
    Success = CreateAccountTypeStdTran(WizardFinishParameters, AccountType, AccountTypeStdTran)
  End If

  ' If a new Standard Transaction add to collection
  If Success AndAlso mAccountTypeStdTranPk = -1 AndAlso Not mIsPromotion Then
    AccountType.StandardTransactions.Add(AccountTypeStdTran)
  End If

  ' Move?
  If Success AndAlso Not mIsPromotion Then
    Select Case WizardFinishParameters.MoveAction
      Case "MoveTop"
        Index = AccountType.StandardTransactions.IndexOf(AccountTypeStdTran)
        If Index &gt; 0 Then Success = AccountType.StandardTransactions.Move(Index, 0)
    End Select
  End If

  ' Timestamp
  If Success AndAlso Not mIsPromotion Then
    If Not AccountTypeStdTran.IsNew AndAlso AccountTypeStdTran.Timestamp &lt;&gt; WizardFinishParameters.TimeStamp Then
      Success = False
      finBL.Error.ErrorBegin("Cannot update Account Type Standard Transaction. This record may have been updated or deleted by another User.")      
    End If
  End If
  
  ' Save
  If Success AndAlso Not mIsPromotion Then
    Success = AccountType.Save()
  End If

  ' Finalise
  If Success Then
    If mIsPromotion Then
      Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(AccountTypeStdTran.ToHtmlWidgetJsonString()), returnValue)
    Else
      Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(New WizardFinishDetails(""), returnValue)
    End If
  End If

  Return Success

End Function

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

  Dim AccountType As finAccountType
  Dim AccountTypeStdTran As finAccountTypeStdTran
  Dim Element As finElementRO
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim List As ISListReadOnly
  Dim ListOther As ISListReadOnly
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If Not finBL.CurrentUser.Permissions.Allow("Cloud.Form.AccountTypes") Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to edit Account Types.")
  ElseIf Len(mAccountTypeId) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Account Type Id not specified.")
  ElseIf Not mIsPromotion AndAlso (mAccountTypeStdTranPk &lt; -1 OrElse mAccountTypeStdTranPk = 0) Then
    Success = False
    finBL.Error.ErrorBegin("Invalid Account Type Standard Transaction Pk.")
  ElseIf mIsPromotion AndAlso (mPromotionStdTransactionPk &lt; -1 OrElse mPromotionStdTransactionPk = 0) AndAlso Len(mPromotionAccountTypeStdTranJson) = 0 Then
    Success = False
    finBL.Error.ErrorBegin("Invalid Account Type Promotion Standard Transaction Pk.")
  ElseIf mIsPromotion AndAlso mPromotionPk = 0 AndAlso mPromotionStdTransactionPk &gt; 0 Then
    ' This case is allowed - take for instance a Promotion which has been duplicated and currently being editted before a save
'    Success = False
'    finBL.Error.ErrorBegin("A valid Promotion must be specified.")
  End If

  ' Create Account Type and Standard Transaction objects
  If Success Then
    Success = CreateAccountTypeStdTran(Nothing, AccountType, AccountTypeStdTran)
  End If

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

      ' Record
      .IsNew = (Not mIsPromotion AndAlso AccountTypeStdTran.IsNew) OrElse (mIsPromotion AndAlso mPromotionPk = 0)
      .IsPromotion = mIsPromotion
      .Timestamp = AccountTypeStdTran.Timestamp

      ' Account Type Properties
      .AccountTypeId = AccountType.AccountTypeId
      .Description = AccountType.Description

      ' Standard Transaction
      .StandardTransaction = AccountTypeStdTran.ToHtmlWidgetJsonObject()

      ' Global Collections
      For Each Element In finBL.Elements
        If Element.Active Then
          .Elements.Add(New ElementInfo(Element, AccountType))
        End If
      Next

      ' Lists
      If Not AccountTypeStdTran.IsNew OrElse mDuplicateRecordPk &lt;&gt; 0 Then
        List = finBLShared.AccountTypeFunctions.GetAccountTypeStdTranCycleList(AccountType, AccountTypeStdTran.ElementId, ListOther)
        .DefaultCycleList = List.ToCsvString()
        .DefaultCycleListOther = ListOther.ToCsvString()
      End If

      ' First Period
      List = finBL.AccountTypeFunctions.GetAccountTypeStdTranCycleFirstPeriodList(AccountType, ListOther)      
      .CycleFirstPeriodList = List.ToCsvString()
      .CycleFirstPeriodListOther = ListOther.ToCsvString()      

      ' Basis
      .ValueBasisList = finBL.Enums.isefinAccountStdTransValueBasis_ToCodeDescriptionList(AccountType.AccountClass, AccountType.CreditLimitCount).ToJsonObject()

      ' Other
      .ElementFilter = finBL.HtmlWidgetUtilities.EncryptSql(AccountType.StandardTransactions.ElementDataViewFilter())

      ' Configuration
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
      .ShowKey = mCombinedParameters.GetString("ShowKey"): If Len(.ShowKey) = 0 Then .ShowKey = "Advanced"

      ' Finalise Configuration
      If .ReadOnly OrElse .IsNew OrElse mIsPromotion Then
        .CanDelete = False
      Else
        .CanDelete = True
      End If
    End With
  End If

  ' Further Validations
  If Success Then
    If FormInitialisationInfo.ReadOnly AndAlso mAccountTypeStdTranPk = -1 Then
      Success = False
      finBL.Error.ErrorBegin("Cannot add a new Account Type Standard Transaction 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
  Public IsPromotion As Boolean 
  Public Timestamp As Integer

  ' Account Properties
  Public AccountTypeId As String
  Public Description As String

  ' Standard Transaction
  Public StandardTransaction As finAccountTypeStdTran.jsonHtmlWidgetAccountTypeStdTran

  ' Lists
  Public ValueBasisList As Object
  Public CycleFirstPeriodList As String
  Public CycleFirstPeriodListOther As String
  Public DefaultCycleList As String
  Public DefaultCycleListOther As String

  ' List Filters
  Public ElementFilter As String

  ' Global Collections
  Public Elements As New List(Of ElementInfo)

  ' Configuration
  Public CanDelete As Boolean
  Public PromptOnSave As Boolean
  Public [ReadOnly] As Boolean
  Public ShowKey As String

End Class



''' &lt;summary&gt;
'''  Finish Parameters.
''' &lt;/summary&gt;
''' &lt;summary&gt;
'''  Finish Parameters.
''' &lt;/summary&gt;
Public Class WizardFinishParameters
  
  Public MoveAction As String
  Public StandardTransactionJson As String
  Public TimeStamp As Integer
  
End Class



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

  Public StandardTransactionJson As String
  Public Warning As String

  Public Sub New(standardTransactionJson As String)

    Me.StandardTransactionJson = standardTransactionJson

  End Sub
  
End Class



''' &lt;summary&gt;
'''  Simple information about an Element.
''' &lt;/summary&gt;
Public Class ElementInfo

  Public CycleList As String
  Public CycleListOther As String
  Public ElementId As String
  Public ElementType As String
  Public Description As String
  Public TransactionNotes As String
  Public TransactionReference As String
  Public TransactionValue As Decimal

  Public Sub New(element As finElementRO,
                 accountType As finAccountType)

    Dim ListOther As ISListReadOnly

    ' Populate
    With element
      Me.CycleList = finBLShared.AccountTypeFunctions.GetAccountTypeStdTranCycleList(accountType, element.ElementId, ListOther).ToCsvString()
      Me.CycleListOther = ListOther.ToCsvString()
      Me.ElementId = .ElementId
      Me.ElementType = .ElementType.ToString()
      Me.Description = .Description
      Me.TransactionNotes = .TransactionNotes
      Me.TransactionReference = .TransactionReference
      Me.TransactionValue = .TransactionValue
    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 "AccountTypeStandardTransaction".</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="Enter Transaction Details."&gt;Transaction 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"&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="lblElement"&gt;Select the Element to use&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboElement"&gt;Element:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboElement" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr id="trKey" class="advanced"&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 colspan="2"&gt;&lt;label id="lblCycle"&gt;Specify the default Cycle Frequency and First Occurrence&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboCycle"&gt;Frequency:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboCycle" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboCycleFirstPeriod"&gt;First:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;
            &lt;div style="display:flex; flex-directon:row"&gt;
              &lt;div&gt;&lt;input id="cboCycleFirstPeriod" /&gt;&lt;/div&gt;
              &lt;div&gt;&lt;input id="dateCycleFirstDate" /&gt;&lt;/div&gt;
            &lt;/div&gt;
          &lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblBasis"&gt;Select the default Basis and Rate&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboValueBasis"&gt;Basis:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboValueBasis"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numValueCurrency"&gt;Value:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numValueCurrency"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr style="display:none"&gt;
          &lt;th&gt;&lt;label for="numValuePercent"&gt;Percent:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numValuePercent"/&gt;&amp;nbsp;&amp;nbsp;&lt;input id="chkValuePercentPerAnnum" type="checkbox" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr style="display:none"&gt;
          &lt;th&gt;&lt;label for="numMinValue"&gt;Minimum:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numMinValue"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr style="display:none"&gt;
          &lt;th&gt;&lt;label for="numMaxValue"&gt;Maximum:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numMaxValue"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkAllowChange" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblNotes"&gt;Enter the default Transaction Reference and Notes&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtReference"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtNotes"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

  &lt;/div&gt;

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

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

&lt;/div&gt;

&lt;script&gt;
// Record
var mRecord;
var mRecord_StdTran;

// Global Collections
var mElements;

// Controls
var C = {
  // General
  lblElement: null,
  cboElement: null,
  trKey: null,
  txtKey: null,

  lblCycle: null,
  cboCycle: null,
  cboCycleFirstPeriod: null,
  dateCycleFirstDate: null,

  lblBasis: null,
  cboValueBasis: null,
  numValueCurrency: null,
  numValuePercent: null,
  chkValuePercentPerAnnum: null,
  numMinValue: null,
  numMaxValue: null,
  chkAllowChange: null,

  lblNotes: null,
  txtReference: null,
  txtNotes: null,
}

// Form
var frmMain;
var tabWizard;

// Other
var mElement;
var mValueData;

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

var cmdAdvanced;

// Other
var mAdvancedVisible = false;
var mHasAdvancedOptions = false;

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

  // --------
  // Controls
  // --------
  //   General
  C.lblElement = widget.UI.Label("lblElement", {});
  C.cboElement = widget.UI.DBCombo("cboElement", {
    allowBlank: false,
    maxLength: 20,
    width: widget.UI.FIELD_WIDTH_CODE_20,
    onChange: cboElement_Change,
  });
  C.trKey = $("#trKey");
  C.txtKey = widget.UI.TextBox("txtKey", {
    maxLength: 10,
  });

  C.lblCycle = widget.UI.Label("lblCycle", {});
  C.cboCycle = widget.UI.DateCycleComboBox("cboCycle", {
    allowBlank: false,
    isFrequency: true,
    onChange: cboCycle_Change,
  });
  C.cboCycleFirstPeriod = widget.UI.DateCycleComboBox("cboCycleFirstPeriod", {
    allowBlank: false,
    isFrequency: false,
    onChange: cboCycleFirstPeriod_Change,
  });
  C.dateCycleFirstDate = widget.UI.DateBox("dateCycleFirstDate", {
    allowBlank: false,
  });  

  C.lblBasis = widget.UI.Label("lblBasis", {});
  C.cboValueBasis = widget.UI.ComboBox("cboValueBasis", {
    allowBlank: false,
    onChange: cboValueBasis_Change,
    width: "16em",
  });

  C.lblNotes = widget.UI.Label("lblNotes", {});
  C.txtReference = widget.UI.TextBox("txtReference", {
    maxLength: 20,
  });
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    multiLine: true,
    rows: 3,
    maxLength: 255,
  });
  C.numValueCurrency = widget.UI.NumberBox("numValueCurrency", {
    readOnly: false,
    decimals: -1,
    minValue: -999999999999,
    maxValue: 999999999999,
  });
  C.numValuePercent = widget.UI.NumberBox("numValuePercent", {
    allowBlank: true,
    decimals: 4,
    minValue: 0,
    maxValue: 100,
    percentage: true,
  });
  C.chkValuePercentPerAnnum = widget.UI.CheckBox("chkValuePercentPerAnnum", {
    caption: "Per Annum?"
  });
  C.numMinValue = widget.UI.NumberBox("numMinValue", {
    readOnly: false,
    decimals: -1,
    minValue: -999999999999,
    maxValue: 999999999999,
  });
  C.numMaxValue = widget.UI.NumberBox("numMaxValue", {
    readOnly: false,
    decimals: -1,
    minValue: -999999999999,
    maxValue: 999999999999,
  });
  C.chkAllowChange = widget.UI.CheckBox("chkAllowChange", {
    caption: "Allow changes whilst Quote?",
  });

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

  cmdAdvanced = $("#cmdAdvanced");
  cmdAdvanced.click(function () {
    // Toggle Advanced
    mAdvancedVisible = !mAdvancedVisible;

    // Update Controls
    if (mAdvancedVisible) {
      // Showing
      $("body").addClass("advanced-visible");
      cmdAdvanced.attr("showing", true);
      C.lblElement.Text("Select the Element and optionally a Key to identify the Transaction");
    }
    else {
      // Not showing
      $("body").removeClass("advanced-visible");
      cmdAdvanced.attr("showing", false);
      C.lblElement.Text("Select the Element to identify the Transaction");
    }

    // Force resize
    tabWizard_Resize()
  });

  // 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;
  mRecord_StdTran = 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_StdTran = mRecord.StandardTransaction;

      // Global Collections
      mElements = mRecord.Elements;

      // Give Collections ability to lookup by code
      widget.ArrayAllowLookupById(mElements, "ElementId");

      // 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 &amp;&amp; !mRecord.IsPromotion) actions.push({ groupId: "Other", actionId: "MoveTop", caption: "Promote Transaction to top of List", icon: "Move_Up" });
      frmMain.ActionsDefine(actions, "cmdActions", Form_ExecuteAction);

      // Load Fields
      Fields_Load();
    },

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // Determine Element Type
    // NOTE: mElement is generally set in cboElement_Change but we need it sooner than that
    var element = mElements.GetItem(mRecord_StdTran.ElementId);
    var elementType = element ? element.ElementType : "";

    // General
    C.cboElement.Text(mRecord_StdTran.ElementId);
    C.txtKey.Text(mRecord_StdTran.Key);

    C.cboCycle.Text(mRecord_StdTran.Cycle);
    C.cboCycleFirstPeriod.Text(mRecord_StdTran.CycleFirstPeriod);
    C.dateCycleFirstDate.Value(mRecord_StdTran.CycleFirstDate);

    C.cboValueBasis.Text(mRecord_StdTran.ValueBasisText);
    C.numValueCurrency.Value(mRecord_StdTran.ValueCurrency);
    C.numValuePercent.Value(mRecord_StdTran.ValuePercent);
    C.chkValuePercentPerAnnum.Value(mRecord_StdTran.ValuePercentPerAnnum);
    C.numMinValue.Value(mRecord_StdTran.MinValue);
    C.numMaxValue.Value(mRecord_StdTran.MaxValue);
    C.chkAllowChange.Value(mRecord_StdTran.AllowChange);

    C.txtReference.Text(mRecord_StdTran.Reference);
    C.txtNotes.Text(mRecord_StdTran.Notes);

    // Reverse Value; so this is a Transfer From (rather than to)
    if (mRecord_StdTran.ValueCurrency &amp;&amp; mRecord.AccountClass == "Deposit" &amp;&amp; elementType == "Transfer") {
      C.numValueCurrency.Value(mRecord_StdTran.ValueCurrency * -1);
    }
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  mRecord_StdTran.ElementId = C.cboElement.Text();
  mRecord_StdTran.Key = C.txtKey.Text();

  mRecord_StdTran.Cycle = C.cboCycle.Text();
  mRecord_StdTran.CycleFirstPeriod = C.cboCycleFirstPeriod.Text();
  mRecord_StdTran.CycleFirstDate = C.dateCycleFirstDate.Value();

  mRecord_StdTran.ValueBasisText = C.cboValueBasis.Text();
  mRecord_StdTran.ValueCurrency = C.numValueCurrency.Value();
  mRecord_StdTran.ValuePercent = C.numValuePercent.Value();
  mRecord_StdTran.ValuePercentPerAnnum = C.chkValuePercentPerAnnum.Value();
  mRecord_StdTran.MinValue = C.numMinValue.Value();
  mRecord_StdTran.MaxValue = C.numMaxValue.Value();
  mRecord_StdTran.AllowChange = C.chkAllowChange.Value();

  mRecord_StdTran.Reference = C.txtReference.Text();
  mRecord_StdTran.Notes = C.txtNotes.Text();
}

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

  // Lists
  if (mRecord) {
    C.cboElement.RefreshFromStandardRange("Elements", mRecord.ElementFilter);
    
    if (mRecord.DefaultCycleList) C.cboCycle.ListFromCsvString(mRecord.DefaultCycleList);
    if (mRecord.DefaultCycleListOther) C.cboCycle.ListOtherFromCsvString(mRecord.DefaultCycleListOther);
    if (mRecord.CycleFirstPeriodList) C.cboCycleFirstPeriod.ListFromCsvString(mRecord.CycleFirstPeriodList);
    if (mRecord.CycleFirstPeriodListOther) C.cboCycleFirstPeriod.ListOtherFromCsvString(mRecord.CycleFirstPeriodListOther);

    C.cboValueBasis.ListFromCollection(mRecord.ValueBasisList, "Description");
  }

  // Check for Advanced options
  mHasAdvancedOptions = false;
  if (mRecord) {
    if (mRecord.ShowKey.toUpperCase() == "ADVANCED") mHasAdvancedOptions = true;

    switch(mRecord.ShowKey.toUpperCase()) {
      case "TRUE":
        C.lblElement.Text("Select the Element and optionally a Key to identify the Transaction");
        C.txtKey.VisibleRow(true);
        break;

      case "FALSE":
        C.lblElement.Text("Select the Element to identify the Transaction");
        C.txtKey.VisibleRow(false);
        break;

      case "ADVANCED":
        C.lblElement.Text("Select the Element to identify the Transaction");
        C.trKey.addClass("advanced");
        break;
    }
  }

  // Controls
  if (mRecord) {
    cboElement_Change();
    cboCycle_Change();    
    cboValueBasis_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("Save");
  }

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

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      C.txtKey.WidthResizeFromParent();
      C.txtReference.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 "General":
        pageGeneral_Refresh();
        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()) {
      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 Transaction?", {}, Form_ExecuteAction_DeletePost);
  });
}

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

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

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

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

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

// ==================
// Move to Top Action
// ==================
function Form_ExecuteAction_MoveTop() {
  // Validate
  tabWizard_Validate(function () {
    // Confirm
    if (mRecord.PromptOnSave) {
      widget.UI.MsgBoxConfirm("Update the Transaction and move it to the top of the list?",
                              { heading: "Update and Promote Transaction" },
                              function () {
                                // Save and Move
                                Form_ExecuteAction_FinishPost("MoveTop");
                              });
    }
    else {
      // Save and Move without prompting
      Form_ExecuteAction_FinishPost("MoveTop");
    }
  });
}

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

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

function Form_ExecuteAction_FinishPost(moveAction) {
  // Disable Form
  if (mRecord.IsPromotion) {
    widget.UI.Block("Updating, please wait...");
  }
  else {
    widget.UI.Block("Committing, please wait...");
  }  

  // Create Parameters
  var params = CreateFinishParameters();

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

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

      // Finalise
      if (data.Warning) {
        widget.UI.MsgBoxAlert("The Transaction 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) {  
  // Not really saving, just passing details back to parent form
  // NOTE: The reason we went through the whole save process was to validate and update details
  if (mRecord.IsPromotion) {
    // Notify parent (e.g., Account Type Promotion wizard) that a new Standard Transaction has been created or an item edited
    // NOTE: This is essential if this wizard needs to be run from a New Account wizard
    widget.ParentNotify("RecordUpdated", data.StandardTransactionJson);

    // Close
    widget.Close();
    return;
  }

  // Close Form
  widget.Close();

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

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

  // Get Element Type
  mElement = mElements.GetItem(C.cboElement.Text());

  // Default when Element changes
  if (e &amp;&amp; mElement) {
    // Update Cycle List
    C.cboCycle.ListFromCsvString(mElement.CycleList);
    C.cboCycle.ListOtherFromCsvString(mRecord.CycleListOther);
    
    // Update Cycle
    switch(mElement.ElementType) {
      case "Deposit":
        C.cboCycle.Text("Opening");
        break;
    }

    switch(mElement.ElementType) {      
      case "PaymentReceived":
      case "Withdrawal":
        if (C.cboCycle.Text().toUpperCase() == "OPENING") {
          C.cboCycle.Text("");
        }
        break;
    }

    // Other defaults
    C.cboValueBasis.Text("Set Value");
    C.numValueCurrency.Value(mElement.TransactionValue);
    C.txtReference.Text(mElement.TransactionReference);
    C.txtNotes.Text(mElement.TransactionNotes);
  }

  // Refresh Page (regardless of whether updated by User)
  pageGeneral_Refresh();
}

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

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

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

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

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

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

function CreateFinishParameters() {
  // Save Fields
  Fields_Save();

  return { StandardTransactionJson: JSON.stringify(mRecord_StdTran), Timestamp: mRecord.Timestamp };
}

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  if (mRecord) {
    // Element-related
    var elementType = mElement ? mElement.ElementType : "";

    // Cycle-related
    switch(C.cboCycle.Text()) {
      case "Opening":
      case "Refinance":
      case "Restructure":
        // Opening
        C.cboCycleFirstPeriod.VisibleRow(false);

        switch(elementType) {
          case "Cost":
          case "Deposit":
          case "Fee":
          case "Journal":
            C.cboValueBasis.ReadOnly(false);
            break;

          default:
            C.cboValueBasis.ReadOnly(true);
            C.cboValueBasis.Text("Set Value");
            break;
        }
        break;

      case "Once":
        // Once
        C.cboCycleFirstPeriod.VisibleRow(true);
        C.cboValueBasis.ReadOnly(false);
        break;

      default:
        // Other
        C.cboCycleFirstPeriod.VisibleRow(true);
        C.cboValueBasis.ReadOnly(false);
        break;
    }

    // Cycle First Period-related
    switch(C.cboCycleFirstPeriod.Text().toUpperCase()) {
      case "ON DATE":
        C.dateCycleFirstDate.Visible(true);
        break;

      default:
        C.dateCycleFirstDate.Visible(false);
        break;
    }

    // Value Basis-related
    var valueBasis = C.cboValueBasis.ListIndex() == -1 ? "" : mRecord.ValueBasisList[C.cboValueBasis.ListIndex()].Code;
    switch(valueBasis) {
      case "PercentBalance":
      case "PercentCreditLimit":
      case "PercentCreditLimit2":
      case "PercentCreditLimit3":
      case "PercentRegularPayment":
      case "PercentTotalAdvances":
        C.numValueCurrency.VisibleRow(false);
        C.numValuePercent.VisibleRow(true);
        C.numMinValue.VisibleRow(true);
        C.numMaxValue.VisibleRow(true);
        break;

      default:
        C.numValueCurrency.VisibleRow(true);
        C.numValuePercent.VisibleRow(false);
        C.numMinValue.VisibleRow(false);
        C.numMaxValue.VisibleRow(false);
        break;
    }

    // Refinance Element cannot be edited
    if (elementType == "Refinance") {
      C.cboElement.ReadOnly(true);
      C.cboCycle.ReadOnly(true);
      C.numValueCurrency.ReadOnly(true);
    }
  }

  // Advanced Button visible?
  if (mRecord &amp;&amp; !mHasAdvancedOptions) {
    // Hide button
    cmdAdvanced.hide();

    // Remove advanced section styling for everything
    $("tr").removeClass("advanced");
  }
  else if (mAdvancedVisible) {
    // Showing
    $("body").addClass("advanced-visible");
    cmdAdvanced.attr("showing", true);
  }
  else {
    // Not showing
    $("body").removeClass("advanced-visible");
    cmdAdvanced.attr("showing", false);
  }
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>Ibb5cykm0U+cCZDKn74w2g</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="ShowKey" type="List">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>Advanced</Value>
            <Visible>true</Visible>
            <List>True,False,Advanced</List>
            <LimitToList>true</LimitToList>
            <MaxLength>8</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ReadOnly" type="Boolean">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>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="AccountTypeId" 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.AccountTypes</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AccountTypeStdTranPk" type="Number">
            <BlankTip />
            <Caption>Standard Transaction Pk</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>For 'Quote' Accounts, this should be the 0-based index of the item in the collection</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="DuplicateRecordPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>For 'Quote' Accounts, this should be the 0-based index of the item in the collection</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="IsPromotion" type="Boolean">
            <BlankTip />
            <Caption>Is Promotion?</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="PromotionPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="PromotionStdTransactionPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="PromotionAccountTypeStdTranJson" type="Text">
            <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>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>