<?xml version="1.0" encoding="utf-8"?><finScript version="1.00" exportedUtcDate="2021-01-10T21:38:23.0000000"><CreatedUserId>Admin</CreatedUserId><CreatedUtcDate>2021-01-06T22:53:40.4590000</CreatedUtcDate><UpdatedUserId>Admin</UpdatedUserId><UpdatedUtcDate>2021-01-10T21:16:22.8040000</UpdatedUtcDate><ScriptId>RATTABE</ScriptId><Description>Rate Table Edit</Description><ScriptType>HtmlWidget</ScriptType><Active>true</Active><AllowUI>false</AllowUI><Category /><Code>' HtmlWidget_RateTableEdit
Option Explicit On
Option Strict On

' #################################################################
' Rate Table Edit form HTML Widget
'
' Version: 1.00 (11/01/2021)
'
' Usage: System-supplied HTML Widget
' #################################################################

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

' Standard Parameters
Private mDuplicateRecordId As String
Private mPage As String
Private mRateTableId As String
Private mReadOnly As Boolean

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

  ' Assume Success
  Main = True

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

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

  ' Get Standard Parameters
  With mStartupParameters
    mRateTableId = .GetString("RateTableId") ' Always use Startup Parameters since the Rate Table Id may be updated
  End With
  With mCombinedParameters
    mDuplicateRecordId = .GetString("DuplicateRecordId")
    mPage = .GetString("Page")
    mReadOnly = .GetBoolean("ReadOnly")
  End With

  ' Validate
  If finBL.CloudConnectFunctions.CloudConnectSettings.ExcludeAdministrationTools Then
    Main = False
    finBL.Error.ErrorBegin("Administration tools are excluded from being accessed from finPOWER Connect Cloud.")
  ElseIf Not finBL.CurrentUser.Permissions.Allow("Admin.RateTables") Then
    Main = False
    finBL.Error.ErrorBegin("You do not have permission to add or update Rate Tables.")
  End If

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

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

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

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

End Function

''' &lt;summary&gt;
'''  Load Rate Table.
''' &lt;/summary&gt;
Private Function GetRateTable(ByRef rateTable As finRateTable) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Create and Load Rate Table
  If Success Then
    ' Create Rate Table
    rateTable = finBL.CreateRateTable()

    ' Load Rate Table
    If Len(mDuplicateRecordId) &lt;&gt; 0 Then
      ' New record (by duplicating existing)
      Success = rateTable.Load(mDuplicateRecordId)
      If Success Then rateTable.Duplicate()
    ElseIf Len(mRateTableId) = 0 Then
      ' New record
    Else
      Success = rateTable.Load(mRateTableId)
    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 FormInitialisationInfo As FormInitialisationInfo
  Dim Item As finRateTableItem
  Dim RateTable As finRateTable
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate
  If Not finBL.Settings.AddOns.RateTable Then
    Success = False
    finBL.Error.ErrorBegin("You are not licensed for the Rate Table Add-On.")
  ElseIf Not finBL.CurrentUser.Permissions.Allow("Admin.RateTables") OrElse Not finBL.CurrentUser.Permissions.Allow("Cloud.Form.RateTables") Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to edit Rate Tables.")
  End If

  ' Get Rate Table
  If Success Then
    Success = GetRateTable(RateTable)
  End If

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

      ' Record
      .Pk = RateTable.Pk
      .Timestamp = RateTable.Timestamp

      ' Page Permissions (defined here since they are used below)
      .AllowPageGeneral = True
      .AllowPageRates = True

      ' General
      .RateTableId = RateTable.RateTableId ' Always need to return Rate Table Id
      If .AllowPageGeneral Then
        .Active = RateTable.Active
        .Category = RateTable.Category
        .Description = RateTable.Description
        .Notes = RateTable.Notes
        .PublishDescription = RateTable.PublishDescription
        .RateFormat = RateTable.RateFormatText
      End If

      ' Rates
      If .AllowPageRates Then
        .Rates = New List(Of RateTableItem)
        For Each Item In RateTable.Items
          .Rates.Add(New RateTableItem(Item))
        Next
      End If

      ' Permissions

      ' Lists
      .RateFormatsList = finBL.Enums.isefinRateTableRateFormat_GetList().ToCsvString()

      ' Configuration
      .HideOtherPages = mCombinedParameters.GetBoolean("HideOtherPages", False)
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
    End With
  End If

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

  Return Success

End Function

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

  Dim Item As finRateTableItem
  Dim obj As Object
  Dim RateTable As finRateTable
  Dim RateTableItem As RateTableItem
  Dim RateTableItemTier As RateTableItemTier
  Dim Record As FormInitialisationInfo
  Dim Success As Boolean
  Dim Tier As finRateTableItemTier

  ' Assume Success
  Success = True

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

  ' Get Rate Table
  If Success Then
    Success = GetRateTable(RateTable)
  End If

  ' Validate
  If Success Then
    If Record.Timestamp &lt;&gt; RateTable.Timestamp Then
      Success = False
      finBL.Error.ErrorBegin("This record has been updated by another User.")
    End If
  End If

  ' Update and Save
  ' NOTE: Recheck Permissions in addition to the 'AllowPage' properties before updating to prevent spoofing
  If Success Then
    ' Begin Transaction
    If finBL.Database.TransactionBegin() Then
      ' Update Rate Table
      With RateTable
        ' General
        If Record.AllowPageGeneral Then
          .RateTableId = Record.RateTableId
          .Active = Record.Active
          .Category = Record.Category
          .Description = Record.Description
          .Notes = Record.Notes
          .PublishDescription = Record.PublishDescription
          .RateFormatText = Record.RateFormat
        End If

        ' Rates
        If Record.AllowPageRates Then
          .Items.Clear()
          For Each RateTableItem In Record.Rates
            Item = RateTable.Items.CreateRateTableItem()

            With RateTableItem
              Item.Description = RateTableItem.Description
              Item.Rate = RateTableItem.Rate
              Item.StartDate = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(RateTableItem.StartDate)
              Item.Tiered = RateTableItem.Tiered

              ' Tier Items
              If Item.Tiered Then
                For Each RateTableItemTier In RateTableItem.Tiers
                  Tier = Item.Tiers.CreateRateTableItemTier()

                  With RateTableItemTier
                    Tier.Description = .Description
                    Tier.Rate = .Rate
                    Tier.ValueTo = .ValueTo
                  End With

                  Item.Tiers.Add(Tier)
                Next
              End If
            End With

            .Items.Add(Item)
          Next
        End If
      End With

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

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

  Return Success

End Function

''' &lt;summary&gt;
'''  Validate a Wizard page.
''' &lt;/summary&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 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
  End Select

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

  Return Success

End Function


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

  ' Form
  Public PageId As String
  Public [ReadOnly] As Boolean

  ' Record
  Public Pk As Integer
  Public Timestamp As Integer

  ' General
  Public RateTableId As String
  Public Active As Boolean
  Public Category As String
  Public Description As String
  Public Notes As String
  Public PublishDescription As String
  Public RateFormat As String

  ' Rates
  Public Rates As List(Of RateTableItem)

  ' Permissions
  Public AllowPageGeneral As Boolean
  Public AllowPageRates As Boolean

  ' Lists
  Public RateFormatsList As String

  ' Configuration
  Public HideOtherPages As Boolean
  Public PromptOnSave As Boolean

End Class


''' &lt;summary&gt;
'''  Rate Table Item.
''' &lt;/summary&gt;
Public Class RateTableItem

  Public Description As String
  Public Rate As Double
  Public StartDate As Date?
  Public Tiered As Boolean

  ' Tiers
  Public Tiers As New List(Of RateTableItemTier)

  Public Sub New()
  End Sub

  Public Sub New(rateTableItem As finRateTableItem)

    Dim Tier As finRateTableItemTier

    With rateTableItem
      Me.Description = .Description
      Me.Rate = .Rate
      Me.StartDate = finBLShared.HtmlWidgetUtilities.GetJsonUtcDateFromDatabaseDate(.StartDate)
      Me.Tiered = .Tiered
    End With

    ' Tiers
    For Each Tier In rateTableItem.Tiers
      Me.Tiers.Add(New RateTableItemTier(Tier))
    Next

  End Sub

  ' Prevent Serialisation for Not Applicable Properties
  Public Function ShouldSerializeDescription() As Boolean
    Return Len(Me.Description) &lt;&gt; 0
  End Function

End Class


''' &lt;summary&gt;
'''  Rate Table Item Tier.
''' &lt;/summary&gt;
Public Class RateTableItemTier

  Public Description As String
  Public Rate As Double
  Public ValueTo As Decimal

  Public Sub New()
  End Sub

  Public Sub New(tier As finRateTableItemTier)

    With tier
      Me.Description = .Description
      Me.Rate = .Rate
      Me.ValueTo = .ValueTo
    End With

  End Sub

End Class


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

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

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

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

  End Sub

End Class</Code><Language>VisualBasic</Language><Notes>System-supplied HTML Widget to add or edit a Rate Table.</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;!-- Tabs --&gt;
    &lt;div id="tabDetails" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General"&gt;General&lt;/li&gt;
        &lt;li tabId="Rates"&gt;Rates&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:9em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblCodeAndName"&gt;Code and Description&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtRateTableId"&gt;Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtRateTableId"/&gt; &lt;input id="chkActive" type="checkbox"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtDescription"&gt;Description:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtDescription"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblFormatAndCategory"&gt;Rate Format and Category&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRateFormat"&gt;Format:&lt;/label&gt;&lt;/th&gt;
          &lt;th&gt;&lt;input id="cboRateFormat"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboCategory"&gt;Category:&lt;/label&gt;&lt;/th&gt;
          &lt;th&gt;&lt;input id="cboCategory"/&gt;&lt;/th&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblPublishDescription"&gt;Publish Description&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtPublishDescription"&gt;Description:&lt;/label&gt;&lt;/th&gt;
          &lt;th&gt;&lt;input id="txtPublishDescription"/&gt;&lt;/th&gt;
        &lt;/tr&gt;

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



    &lt;!-- Rates --&gt;
    &lt;div id="pageRates"&gt;
      &lt;div class="is-dock-fill" style="display:flex; flex-direction:column; padding:4px;"&gt;
        &lt;div style="flex-grow:0"&gt;
          &lt;table class="is-form"&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label&gt;Rates&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/table&gt;
        &lt;/div&gt;

        &lt;div style="flex-grow:1; position:relative; max-width:1024px"&gt;
          &lt;div id="gridRates" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;

        &lt;div style="flex-grow:0; margin-top:8px"&gt;
          &lt;table class="is-form"&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblTiers"&gt;Tiers&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/table&gt;
        &lt;/div&gt;

        &lt;div style="flex-grow:1; position:relative; max-width:1024px"&gt;
          &lt;div class="is-info-text info"&gt;This rate is not tiered.&lt;/div&gt;
          &lt;div id="gridTiers" class="is-dock-fill"&gt;&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;

  &lt;/div&gt;


  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdActions"/&gt;
    &lt;button id="cmdCancel" class="is-button"&gt;Cancel&lt;/button&gt;
    &lt;button id="cmdFinish" class="is-button ok"&gt;Save&lt;/button&gt;
  &lt;/footer&gt;

&lt;/div&gt;


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

var mOriginalJson;

// Controls
var C = {
  //   General
  lblCodeAndName: null,
  txtRateTableId: null,
  txtDescription: null,
  chkActive: null,

  lblFormatAndCategory: null,
  cboRateFormat: null,
  cboCategory: null,

  lblPublishDescription: null,
  txtPublishDescription: null,

  txtNotes: null,

  //   Rates
  gridRates: null,
  gridTiers: null,
}

// Form
var frmMain;
var tabDetails;

// Buttons
var cmdCancel;
var cmdFinish;

// Other

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

  // --------
  // Controls
  // --------
  //   General
  C.lblCodeAndName = widget.UI.Label("lblCodeAndName", {});
  C.txtRateTableId = widget.UI.TextBox("txtRateTableId", {
    allowBlank: false,
    maxLength: 10,
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  C.txtDescription = widget.UI.TextBox("txtDescription", {
    allowBlank: false,
    maxLength: 50,
  });
  C.chkActive = widget.UI.CheckBox("chkActive", {
    caption: "Active?",
  });

  C.lblFormatAndCategory = widget.UI.Label("lblFormatAndCategory", {
    tooltipText: "The Rate Format can be either Percent, Currency, Rate0 (0 decimal places), Rate2 (2 decimal places) or Rate4 (4 decimal places).",
  });
  C.cboRateFormat = widget.UI.ComboBox("cboRateFormat", {
    allowBlank: false,
    limitToList: true,
    maxLength: 20,
    width: "10em"
  });
  C.cboCategory = widget.UI.InformationListComboBox("cboCategory", {
    maxLength: 50,
  });

  C.lblPublishDescription = widget.UI.Label("lblPublishDescription", {
    tooltipText: "The description to use when publishing documents e.g., Account Contracts.",
  });
  C.txtPublishDescription = widget.UI.TextBox("txtPublishDescription", {
    blankTip: "[Id], [Desc]; as published by us from time to time (current annual base rate is [Rate]);",
    multiLine: true,
    rows: 2,
  });

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

  //   Rates

  // Grids
  C.gridRates = widget.UI.Grid("gridRates", {
    docked: true,
    stickyHeader: true,
    rowNumbering: true,
    allowAddRows: true,
    allowMultiRowSelect: true,
    maxNewRows: 200,

    onAction: gridRates_Action,
    onAfterRowActivate: gridRates_AfterRowActivate,
    onBeforeCellUpdate: gridRates_BeforeCellUpdate,
    onInitialiseRow: gridRates_InitialiseRow,
    onRowAdd: gridRates_RowAdd,
  });
  C.gridTiers = widget.UI.Grid("gridTiers", {
    docked: true,
    stickyHeader: true,
    rowNumbering: true,
    allowAddRows: true,
    allowMultiRowSelect: true,
    maxNewRows: 200,

    onAction: gridTiers_Action,
    onAfterRowActivate: gridTiers_AfterRowActivate,
    onBeforeCellUpdate: gridTiers_BeforeCellUpdate,
    onInitialiseRow: gridTiers_InitialiseRow,
    onRowAdd: gridTiers_RowAdd,
  });


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

  // Create Tabs
  tabDetails = new widget.UI.Tabs("tabDetails", {
    style: "normal",
    onSelectedTabChanged: tabDetails_Refresh,
  });

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

  // Disable Close Button (this causes the 'FormClose' notification action to be invoked instead)
  widget.DisableCloseButton();
  widget.ActionNotificationHandle(Widget_NotificationHandler)

  // Handle Wizard Buttons
  cmdCancel = $("#cmdCancel");
  cmdFinish = $("#cmdFinish");
  cmdCancel.click(tabDetails_Cancel);
  cmdFinish.click(Form_ExecuteAction_Finish);

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // 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
    Record_Load_Done,

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

function Record_Load_Done(data) {
  // Initialise
  mRecord = JSON.parse(data);
  mRecord_Rates = mRecord.Rates;
  mRecord_Tiers = null;

  // Set Tab
  if (mRecord &amp;&amp; mRecord.PageId) {
    tabDetails.SelectedTabId(mRecord.PageId);

    // Hide other Pages
    if (mRecord.HideOtherPages) {
      tabDetails.ShowSingleTab(mRecord.PageId);
    }
  }
  else {
    tabDetails.SelectedTabId("General");
  }

  // Page Permissions
  if (!mRecord.AllowPageGeneral) tabDetails.TabVisible("General", false);
  if (!mRecord.AllowPageRates) tabDetails.TabVisible("Rates", false);

  // Load Fields
  Fields_Load();

  // Save original JSON for Form_IsDirty
  Fields_Save();
  mOriginalJson = JSON.stringify(mRecord);

  // Define Actions
  var actions = [];
  frmMain.ActionsDefine(actions, "cmdActions", Form_ExecuteAction);
}

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.txtRateTableId.Text(mRecord.RateTableId);
    C.txtDescription.Text(mRecord.Description);
    C.chkActive.Value(mRecord.Active);

    C.cboRateFormat.Text(mRecord.RateFormat);
    C.cboCategory.Text(mRecord.Category);

    C.txtPublishDescription.Text(mRecord.PublishDescription);

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

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabDetails_Refresh();
  tabDetails_Resize();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // General
  mRecord.RateTableId = C.txtRateTableId.Text();
  mRecord.Description = C.txtDescription.Text();
  mRecord.Active = C.chkActive.Value();

  mRecord.RateFormat = C.cboRateFormat.Text();
  mRecord.Category = C.cboCategory.Text();

  mRecord.PublishDescription = C.txtPublishDescription.Text();

  mRecord.Notes = C.txtNotes.Text();

  // Rates
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    if (mRecord.RateTableId) {
      widget.SetHeading("Rate Table (" + mRecord.RateTableId + ")");
    }
    else {
      widget.SetHeading("New Rate Table");
    }
  }

  // Lists
  if (mRecord) {
    C.cboRateFormat.ListFromCsvString(mRecord.RateFormatsList);
    C.cboCategory.SetComboFromInformationList("RateTableCategories", true, null, true);
  }

  // Controls
  if (mRecord) {
    // Tags
    // NOTE: We never use the Description portion since we only want To insert the unresolved value at this point
    var tagsList = [];
    tagsList.push({ caption: "Rate Table Id", value: "[Id]" });
    tagsList.push({ caption: "Rate Table Description", value: "[Desc]" });
    tagsList.push({ caption: "Current Rate", value: "[Rate]" });
    C.txtPublishDescription.TagsListDefine(tagsList);
  }

  // Pages
  if (mRecord) {
    // NOTE: Even though many pages are updated in tabDetails_Refresh, we must update them here to ensure controls are hidden since this is not a wizard and all pages are validated on "Finish"
    pageGeneral_Refresh();
    pageRates_Refresh();
  }

  // Read-Only?
  if (mRecord &amp;&amp; mRecord.ReadOnly) {
    cmdFinish.prop("disabled", true);
    frmMain.FormReadOnly(C, true);
  }

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

  // Resize Tab
  tabDetails_Resize();
}

// ===========
// Resize Form
// ===========
function Form_Resize() {
  // Mobile Optimisations
  var el = $(".mobile-indent th.indent1, .mobile-indent th.no-indent1");
  if (window.innerWidth &lt; 500) {
    el.addClass("no-indent1").removeClass("indent1");
  }
  else {
    el.addClass("indent1").removeClass("no-indent1");
  }

  // General

  // Tab
  tabDetails_Resize();
}

// ========
// Is Dirty
// ========
function Form_IsDirty() {
  if (mRecord) {
    // Save Fields
    Fields_Save();

    return mOriginalJson != JSON.stringify(mRecord);
  }
  else {
    return false;
  }
}

// ==============
// Wizard Buttons
// ==============
function tabDetails_Cancel() {
  if (Form_IsDirty()) {
    // Confirm
    widget.UI.MsgBoxConfirm("Are you sure you want to close this form without saving your changes?", { heading: "Close Form" }, tabDetails_Cancel_Finalise);
  }
  else {
    // Cancel immediately
    tabDetails_Cancel_Finalise();
  }
}

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

// ==========
// Resize Tab
// ==========
function tabDetails_Resize() {
  switch (tabDetails.SelectedTabId()) {
    case "General":
      // General
      C.txtDescription.WidthResizeFromParent();
      C.txtPublishDescription.WidthResizeFromParent();
      C.txtNotes.WidthResizeFromParent();
      break;

    case "Rates":
      // Rates
      break;
  }
}

// ===========
// Refresh Tab
// ===========
function tabDetails_Refresh() {
   // Load details
  switch (tabDetails.SelectedTabId()) {
    case "General":
      pageGeneral_Refresh();
      break;

    case "Rates":
      pageRates_Refresh();
      break;

    default:
      break;
  }

  // Resize
  tabDetails_Resize();

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

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId, data) {
  switch(actionId) {
    default:
      window.alert("Unhandled action '" + actionId + "'");
  }
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
   switch(actionId) {
     case "FormClose":
      // Form Close button is disabled so act as if 'Cancel' has been clicked
      tabDetails_Cancel();
      break;
   }
}

// =============
// Finish Action
// =============
function Form_ExecuteAction_Finish() {
  // Assume Success
  var Ok = true;

  // Validate
  Ok = tabDetails.Validate();

  // Prompt
  if (Ok) {
    if (mRecord.PromptOnSave) {
      // Confirm
      widget.UI.MsgBoxConfirm("Are you sure you want to save this record?",
                              { heading: "Save" },
                              Form_ExecuteAction_FinishPost);

    }
    else {
      // Save without prompting
      Form_ExecuteAction_FinishPost();
    }
  }
}

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

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

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

      // Refresh Parent (to show updated details)
      // NOTE: Pass in Record Id just in case this has changed
      widget.RefreshParent(C.txtRateTableId.Text());
    },

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

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

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  if (!mRecord) return;

  // Controls
}

// =========
// pageRates
// =========
function pageRates_Refresh() {
  if (!mRecord) return;

  // Controls
  // NOTE: Grid is refreshed whenever this page is shown to account for changes in the Rate Format
  gridRates_Refresh();
}

// =========
// gridRates
// =========
function gridRates_Refresh() {
  // Add Columns
  C.gridRates.ClearColumns();
  C.gridRates.AddColumnBoolean("Tiered", { caption: "Tiered", allowEdit: true });
  C.gridRates.AddColumnDate("StartDate", { caption: "Start Date", allowEdit: true });
  C.gridRates.AddColumnDouble("Rate", { caption: "Rate", decimals: GetRateDecimalPlaces(), allowEdit: true });
  C.gridRates.AddColumnString("Description", { caption: "Description", allowEdit: true });

  // Actions
  var actions = [];
  actions.push({ actionId: "DuplicateRow", tooltipText: "Duplicate the current row", icon: "Duplicate" });
  actions.push({});
  actions.push({ actionId: "DeleteRow", tooltipText: "Remove row(s)", icon: "Delete" });
  C.gridRates.Actions().Define(actions);

  // Refresh
  C.gridRates.VirtualDataRefresh(mRecord_Rates);

  // Activate First Row
  C.gridRates.ActivateFirstDataRow();
}

function gridRates_InitialiseRow(e) {
  var item = mRecord_Rates[e.row.listIndex];

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

  // Read-Only/ Not Applicable states
  e.row.cells.Rate.notApplicable = item.Tiered;

  // Validation colouring
  /*
  e.row.invalid = false;
  */
}

function gridRates_BeforeCellUpdate(e) {
  var item = mRecord_Rates[e.row.listIndex];

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

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

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

    case "Tiered":
      item.Tiered = e.newValue;

      // Show/ Hide Tiers
      gridRates_AfterRowActivate();
      break;
  }

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

function gridRates_RowAdd(e) {
  // Create item
  var item = {
    Description: "",
    Rate: 0,
    StartDate: null,
    Tierd: false,

    // Collections
    Tiers: [],
  };

  // Add
  mRecord_Rates.push(item);
}

function gridRates_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "DELETEROW":
      // Delete Row(s)
      // NOTE: This action is also called automatically by the grid if delete is pressed and a row but no cells are selected
      C.gridRates.RemoveSelectedRowsAndCollectionItems();
      C.gridRates.Focus();

      // Refresh Buttons
      gridRates_RefreshButtons();
      break;

    case "DUPLICATEROW":
      // Duplicate Row
      var item = mRecord_Rates[C.gridRates.ActiveDataRowListIndex()];
      var newItem = JSON.parse(JSON.stringify(item));
      newItem.StartDate = null;
      mRecord_Rates.push(newItem);

      // Refresh Grid
      C.gridRates.VirtualDataRefresh(mRecord_Rates);
      C.gridRates.ActivateLastDataRow();
      break;

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

function gridRates_RefreshButtons() {
  if (C.gridRates.ActiveDataRowListIndex() == -1) {
    C.gridRates.Actions().SetEnabled("DeleteRow", false);
    C.gridRates.Actions().SetEnabled("DuplicateRow", false);
  }
  else {
    C.gridRates.Actions().SetEnabled("DeleteRow", true);
    C.gridRates.Actions().SetEnabled("DuplicateRow", true);
  }

  C.gridRates.RefreshButtons();
}

function gridRates_AfterRowActivate(e) {
  // Refresh Buttons
  gridRates_RefreshButtons();

  // Refresh Tiers
  // NOTE: Do not use e.row.listIndex since this may be been called from BeforeCellUpdate when Tiered is updated
  var item = mRecord_Rates[C.gridRates.ActiveDataRowListIndex()];
  if (!item || !item.Tiered) {
    mRecord_Tiers = null;
    C.gridTiers.Visible(false);
  }
  else {
    mRecord_Tiers = item.Tiers;
    gridTiers_Refresh()
    C.gridTiers.Visible(true);
  }
}

// =========
// gridTiers
// =========
function gridTiers_Refresh() {
  // Add Columns
  C.gridTiers.ClearColumns();
  C.gridTiers.AddColumnCurrency("ValueFrom", { caption: "From", width: "8em", allowEdit: false });
  C.gridTiers.AddColumnCurrency("ValueTo", { caption: "To", width: "8em", allowEdit: true });
  C.gridTiers.AddColumnDouble("Rate", { caption: "Rate", decimals: GetRateDecimalPlaces(), allowEdit: true });
  C.gridTiers.AddColumnString("Description", { caption: "Description", allowEdit: true });

  // Actions
  var actions = [];
  actions.push({ actionId: "DeleteRow", tooltipText: "Remove row(s)", icon: "Delete" });
  actions.push({});
  actions.push({ actionId: "RowMoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" });
  actions.push({ actionId: "RowMoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" });
  C.gridTiers.Actions().Define(actions);

  // Refresh
  C.gridTiers.VirtualDataRefresh(mRecord_Tiers);

  // Activate First Row
  C.gridTiers.ActivateFirstDataRow();
}

function gridTiers_InitialiseRow(e) {
  var item = mRecord_Tiers[e.row.listIndex];

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

  // From value
  if (e.row.listIndex &gt; 0) {
    e.row.cells.ValueFrom.value = mRecord_Tiers[e.row.listIndex - 1].ValueTo + 0.01;
  }
  else {
    e.row.cells.ValueFrom.value = "...";
  }

  // Read-Only/ Not Applicable states
  e.row.cells.ValueFrom.readOnly = true;

  // Validation colouring
  /*
  e.row.invalid = false;
  */
}

function gridTiers_BeforeCellUpdate(e) {
  var item = mRecord_Tiers[e.row.listIndex];

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

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

    case "ValueTo":
      item.ValueTo = e.newValue;

      // Must refresh next row to update 'Value From' column
      if (e.row.listIndex &lt; mRecord_Tiers.length - 1) {
        C.gridTiers.RefreshRow(e.row.listIndex + 1);
      }
      break;
  }

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

function gridTiers_RowAdd(e) {
  // Create item
  var item = {
    Description: "",
    Rate: 0,
    ValueTo: 0,
  };

  // Add
  mRecord_Tiers.push(item);
}

function gridTiers_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "DELETEROW":
      // Delete Row(s)
      // NOTE: This action is also called automatically by the grid if delete is pressed and a row but no cells are selected
      C.gridTiers.RemoveSelectedRowsAndCollectionItems();
      C.gridTiers.Focus();

      // Refresh Buttons
      gridTiers_RefreshButtons();
      break;

    case "ROWMOVEDOWN":
      C.gridTiers.RowMoveDown();
      break;

    case "ROWMOVEUP":
      C.gridTiers.RowMoveUp();
      break;

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

function gridTiers_RefreshButtons() {
  if (C.gridTiers.ActiveDataRowListIndex() == -1) {
    C.gridTiers.Actions().SetEnabled("DeleteRow", false);
    C.gridTiers.Actions().SetEnabled("RowMoveUp", false);
    C.gridTiers.Actions().SetEnabled("RowMoveDown", false);
  }
  else {
    C.gridTiers.Actions().SetEnabled("DeleteRow", true);
    C.gridTiers.Actions().SetEnabled("RowMoveUp", C.gridTiers.ActiveDataRowListIndex() &gt; 0);
    C.gridTiers.Actions().SetEnabled("RowMoveDown", C.gridTiers.ActiveDataRowListIndex() &lt; mRecord_Rates.length - 1);
  }

  C.gridTiers.RefreshButtons();
}

function gridTiers_AfterRowActivate(e) {
  // Refresh Buttons
  gridTiers_RefreshButtons();
}


// =======================================
// Get Decimal Places based on Rate Format
// =======================================
function GetRateDecimalPlaces() {
  switch(C.cboRateFormat.Text()) {
    case "Currency":
      return -1;

    case "":
    case "Percent":
      return 4;

    case "Rate0":
      return 0;

    case "Rate2":
      return 2;

    case "Rate4":
      return 4;

    default:
      console.warn("Unhandled Rate Format '" + C.cboRateFormat.Text() + "' in Rate Table Edit widget.");
      return 4;
  }
}
&lt;/script&gt;</TemplateText><TemplateTextBookmarks /><TimeoutSeconds>60</TimeoutSeconds><UniqueId>qYnyGH0KeUiTJQo9QUw5kQ</UniqueId><AllowRefresh>true</AllowRefresh><Caption>Rate Table</Caption><HtmlWidgetMaxHeight>800</HtmlWidgetMaxHeight><HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth><HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling><HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2><HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget><HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery><HtmlWidgetResourceJQueryVersion /><Icon /><JavaScriptDebugger>None</JavaScriptDebugger><RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled><WebServiceName /><WebServiceAllowAnonymous>false</WebServiceAllowAnonymous><WebServiceSendDebugInformation>false</WebServiceSendDebugInformation><ShowInMenu>None</ShowInMenu><ParametersType>Custom</ParametersType><Parameters><ISParameterDefs version="1.00"><Parameters><Parameter name="" type="SectionStart"><BlankTip /><Caption>Form options.</Caption><StandaloneOnly>false</StandaloneOnly><TooltipText /><SectionColumns>1</SectionColumns><Visible>true</Visible></Parameter><Parameter name="HideOtherPages" type="Boolean"><BlankTip /><Caption>Hide pages other than the one being edited?</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>Configuration options.</Caption><StandaloneOnly>false</StandaloneOnly><TooltipText /><SectionColumns>1</SectionColumns><Visible>true</Visible></Parameter><Parameter name="" type="SectionStart"><BlankTip /><Caption>TESTING</Caption><StandaloneOnly>false</StandaloneOnly><TooltipText /><SectionColumns>1</SectionColumns><Visible>true</Visible></Parameter><Parameter name="RateTableId" 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.RateTables</List><LimitToList>false</LimitToList><MaxLength>0</MaxLength><Rows>1</Rows></Parameter><Parameter name="DuplicateRecordId" 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.RateTables</List><LimitToList>false</LimitToList><MaxLength>0</MaxLength><Rows>1</Rows></Parameter><Parameter name="Page" 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>General,Rates</List><LimitToList>false</LimitToList><MaxLength>0</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></Parameters></ISParameterDefs></Parameters></finScript>