<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-10-31T21:36:50.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2023-08-15T23:58:17.7210000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2023-10-31T21:35:05.1220000</UpdatedUtcDate>
    <ScriptId>HW.RESOURCE</ScriptId>
    <Description>Resource Edit</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_ResourceEdit
Option Explicit On
Option Strict On

' #################################################################
' Resource Edit form HTML Widget
'
' Version: 1.00 (01/11/2023)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  01/11/2023  ISS      J031798   Original
' #################################################################

' Constants
Private Const FORM_KEY As String = "Resources"

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

' Standard Parameters
Private mResourceId As String
Private mDuplicateRecordId As String
Private mPage 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
    mResourceId = .GetString("ResourceId") ' Always use Startup Parameters since the Resource Id may be updated
  End With
  With mCombinedParameters
    mDuplicateRecordId = .GetString("DuplicateRecordId")
    mPage = .GetString("Page")
    mReadOnly = .GetBoolean("ReadOnly")
  End With

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

  ' 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 "Download"
        ' Downloads the file attached to the resource, if any
        Main = Download(parametersJson, returnValue)
  
      Case "Finish"
        ' Finish wizard
        Main = Finish(parametersJson, requestInfo, returnValue)

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

     Case "Upload"
       ' Receive new image uploaded by client; Send image info &amp; base64 encoding of image
        Main = Upload(requestInfo, returnValue)
        
      Case Else
        Main = False
        finBL.Error.ErrorBeginFormat("Unhandled event '{0}'", eventId)
    End Select
  End If

End Function

''' &lt;summary&gt;
'''  Load Resource.
''' &lt;/summary&gt;
Private Function GetResource(ByRef resource As finResource) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Create and Load Resource
  If Success Then
    ' Create Resource
    resource = finBL.CreateResource()

    ' Load Resource
    If Len(mDuplicateRecordId) &lt;&gt; 0 Then
      ' New record (by duplicating existing)
      Success = resource.Load(mDuplicateRecordId)
      If Success Then resource.Duplicate()
    ElseIf Len(mResourceId) = 0 Then
      ' New record
    Else
      Success = resource.Load(mResourceId)
    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 Resource As finResource
  Dim Success As Boolean
  
  ' Assume Success
  Success = True

  ' Validate
  If Not finBL.CurrentUser.Permissions.Allow("Admin.Resources") OrElse Not finBL.CurrentUser.Permissions.Allow("Cloud.Form.Resources") Then
    Success = False
    finBL.Error.ErrorBegin("You do not have permission to edit Resources.")
  End If
  
  ' Get Resource
  If Success Then
    Success = GetResource(Resource)
  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 = Resource.Pk
      .Timestamp = Resource.Timestamp

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

      ' General page
      .ResourceId = Resource.ResourceId ' Always need to return Resource Id
      If .AllowPageGeneral Then
        .Active = Resource.Active
        .Description = Resource.Description
        .Category = Resource.Category
        .FileName = Resource.OriginalFilename
        .FileType = Resource.ResourceTypeCode
        .ResourceType = Resource.ResourceTypeText
        .AllowDownloadClientPortals = Resource.AllowDownloadClientPortals
        .AllowDownloadUnauthenticated = Resource.AllowDownloadUnauthenticatedHtmlWidgetsAndPortals
        .AllowDefinedOnAccountsApps = Resource.AllowUseOnAccountsAndAccountApplications
        .AllowUseEmailAttachment = Resource.AllowAsEmailAttachment
        .UserFlagA = Resource.UserFlagA
        .UserFlagB = Resource.UserFlagB
        .Notes = Resource.Notes
      End If

      ' Image preview page
      If .AllowPagePreview Then
        .FileDataBase64 = Resource.GetBinaryDataAsBase64()
        .ImageDescription = Resource.ImageDescription
        .IsImage = Resource.IsImage
      End If
    
      ' Other

      ' Permissions

      ' Lists

      ' Configuration
      .AddonPortal = finBL.Settings.AddOns.Portal
      .AddOnAccountApplication = finBL.Settings.AddOns.AccountApplication
      .HideOtherPages = mCombinedParameters.GetBoolean("HideOtherPages", False)
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
      .UserFlagACaption = finBL.Settings.ResourceFlagAResolved
      .UserFlagBCaption = finBL.Settings.ResourceFlagBResolved
    End With
  End If

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

  Return Success

End Function

Public Function Download(parametersJson As String,
                         ByRef returnValue As String) As Boolean
  Dim FileData As Byte()
  Dim FileInfo As finFileDownloadInfo
  Dim obj As Object
  Dim Record As FormInitialisationInfo
  Dim Success As Boolean = True                         
            
  ' Parse Parameters
  If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(FormInitialisationInfo), obj) Then
    Record = DirectCast(obj, FormInitialisationInfo)
  Else
    Success = False
  End If
  
  ' Get File
  If Success Then
    Try
      FileData = finBL.Runtime.TextUtilities.Base64DecodeToByteArray(Record.FileDataBase64)
    Catch
      Success = False
    End Try
  End If    
    
  ' Create File Info
  If Success Then
    FileInfo = finBL.CreateFileDownloadInfo()
    If FileInfo.LoadByteArray(FileData, Record.FileName) Then
      returnValue = FileInfo.ToXmlString()
    Else
      Success = False
    End If
  End If

  Return Success
  
End Function

Public Function Upload(requestInfo As finScriptRequestInfo,
                       ByRef returnValue As String) As Boolean
  Dim obj As Object
  Dim Resource As finResource
  Dim Success As Boolean

  ' Assume Success
  Success = True
  
  ' Serialise
  If Success Then
    Resource = finBL.CreateResource()
    finBL.DebugPrint(requestInfo.Files(0).FileData)
    Success = Resource.LoadResourceFromByteArray(requestInfo.Files(0).FileData, requestInfo.Files(0).FileName)
  End If

  ' Prepare response
  If Success Then
    obj = New With {
      .FileDataBase64 = Resource.GetBinaryDataAsBase64(),
      .FileName = Resource.OriginalFilename,
      .FileType = Resource.ResourceTypeCode,
      .ImageDescription = Resource.ImageDescription,
      .IsImage = Resource.IsImage
    }
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(obj, returnValue)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Finish, i.e., Save Resource.
''' &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 obj As Object
  Dim Record As FormInitialisationInfo
  Dim Resource As finResource
  Dim Success As Boolean

  ' 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 Client Type
  If Success Then
    Success = GetResource(Resource)
  End If

  ' Validate
  If Success Then
    If Record.Timestamp &lt;&gt; Resource.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
    ' Update Client Type
    With Resource
      ' General
      If Record.AllowPageGeneral Then
        .ResourceId = Record.ResourceId
        .Active = Record.Active
        .Description = Record.Description
        .Category = Record.Category
        .AllowDownloadClientPortals = Record.AllowDownloadClientPortals
        .AllowDownloadUnauthenticatedHtmlWidgetsAndPortals = Record.AllowDownloadUnauthenticated
        .AllowUseOnAccountsAndAccountApplications = Record.AllowDefinedOnAccountsApps
        .AllowAsEmailAttachment = Record.AllowUseEmailAttachment
        .UserFlagA = Record.UserFlagA
        .UserFlagB = Record.UserFlagB
        .Notes = Record.Notes
      End If
    End With

    ' Binary data
    If String.IsNullOrEmpty(Record.FileDataBase64) OrElse String.IsNullOrEmpty(Record.FileName) Then
      Resource.ClearResourceData()
    Else
      Success = Resource.LoadResourceFromBase64String(Record.FileDataBase64, Record.FileName)
    End If

    ' Save
    If Success Then
      Success = Resource.Save()
    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;
Public Class FormInitialisationInfo

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

  ' Record
  Public Pk As Integer
  Public Timestamp As Integer

  ' General
  Public ResourceId As String
  Public Active As Boolean
  Public Description As String
  Public Category As String
  Public ResourceType As String  
  Public AllowDownloadClientPortals As Boolean
  Public AllowDownloadUnauthenticated As Boolean
  Public AllowDefinedOnAccountsApps As Boolean
  Public AllowUseEmailAttachment As Boolean
  Public UserFlagA As Boolean
  Public UserFlagB As Boolean
  Public Notes As String
  
  ' File
  Public FileDataBase64 As String
  Public FileName As String
  Public FileType As String
  Public ImageDescription As String
  Public IsImage As Boolean

  ' Permissions
  Public AllowPageGeneral As Boolean
  Public AllowPagePreview As Boolean

  ' Lists

  ' Configuration
  Public AddonPortal As Boolean
  Public AddOnAccountApplication As Boolean
  Public HideOtherPages As Boolean
  Public PromptOnSave As Boolean
  Public UserFlagACaption As String
  Public UserFlagBCaption As String

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 edit a Resource.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <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="ImagePreview"&gt;Image Preview&lt;/li&gt;
      &lt;ul&gt;
    &lt;/div&gt;
  &lt;/header&gt;

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

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label&gt;Code and Description&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtResourceId"&gt;Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;
            &lt;input id="txtResourceId"/&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&gt;Category&lt;/label&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;td&gt;&lt;input id="cboCategory"/&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label&gt;Resource Details&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtResourceType"&gt;Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtResourceType"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtFileName"&gt;File Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtFileName"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="fuResourceFile"&gt;Upload File:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;div id="fuResourceFile"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td colspan="2"&gt;
            &lt;button id="cmdClear" class="is-button small"&gt;Clear&lt;/button&gt;
            &lt;button id="cmdDownload" class="is-button small"&gt;Download&lt;/button&gt;
          &lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblOtherOptions"&gt;Other options&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkAllowDownloadClientPortals" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkAllowDownloadUnauthenticated" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkAllowDefinedOnAccountsApps" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkAllowUseEmailAttachment" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkUserFlagA" type="checkbox"/&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkUserFlagB" type="checkbox"/&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 style="height:100%"&gt;
          &lt;td colspan="2" style="height:100%"&gt;&lt;input id="txtNotes"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Image Preview --&gt;
    &lt;div id="pageImagePreview"&gt;
      &lt;div style="display:flex; flex-direction:column; position:absolute; top:0; left:0; right:0; bottom:0; padding:4px"&gt;
        &lt;div&gt;
          &lt;table class="is-form"&gt;
            &lt;colgroup&gt;
              &lt;col /&gt;
            &lt;/colgroup&gt;

            &lt;tr&gt;
              &lt;th&gt;&lt;label id="lblImagePreview"&gt;Image Preview&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;td&gt;&lt;label id="lblImageDetails"&gt;&lt;/label&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;td&gt;
                &lt;img id="imgPreview" style="margin-top:8px;"&gt;&lt;/img&gt;
            &lt;/tr&gt;
          &lt;/table&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;

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


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

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

  cboCategory: null,

  txtResourceType: null,
  txtFileName: null,

  fuResourceFile: null,
  
  lblOtherOptions: null,
  chkAllowDownloadClientPortals: null,
  chkAllowDownloadUnauthenticated: null,
  chkAllowDefinedOnAccountsApps:null,
  chlAllowUseEmailAttachment: null,
  chkUserFlagA: null,
  chkUserFlagB: null,

  txtNotes: null,
  
  // Image Preview
  lblImagePreview: null,
  lblImageDetails: null,
  imgPreview: null,
}

// Form
var frmMain;
var tabDetails;

// Wizard Buttons
var cmdCancel;
var cmdFinish;

// Form buttons
var cmdClear;
var cmdDownload;

// Other

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

  // --------
  // Controls
  // --------
  //   General
  C.txtResourceId = widget.UI.TextBox("txtResourceId", {
    allowBlank: false,
    maxLength: 20,
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.chkActive = widget.UI.CheckBox("chkActive", {
    caption: "Active?",
  });
  C.txtDescription = widget.UI.TextBox("txtDescription", {
    allowBlank: false,
    maxLength: 50,
  });
  C.cboCategory = widget.UI.InformationListComboBox("cboCategory", {
    allowBlank: true,
    limitToList: false,
    maxLength: 40,
    width: "24em",
  });

  C.txtResourceType = widget.UI.TextBox("txtResourceType", {
    readOnly: true,
    allowBlank: true,
    maxLength: 10,
    width: "8em",
  });
  C.txtFileName = widget.UI.TextBox("txtFileName", {
    readOnly: true,
    allowBlank: true,
    maxLength: 100,
  });

  C.fuResourceFile = widget.UI.FileUpload("fuResourceFile", {
    allowFile: true,
    allowDocumentManager: false,
    allowResource: false,
    maxFiles: 1,
    onChange: fuResourceFile_Change,
  });

  C.lblOtherOptions = widget.UI.Label("lblOtherOptions", {
    tooltipText: "'Client Portals' includes Portals and External Web Applications that allow for authentication of Clients. \n 'Unauthenticated HTML Widgets and Portals' includes externally hosted HTML Widgets, unauthenticated Portals and any other unauthenticated access by Web Services."
  });
  C.chkAllowDownloadClientPortals = widget.UI.CheckBox("chkAllowDownloadClientPortals", {
    caption: "Allow download by Client Portals?",
  });

  C.chkAllowDownloadUnauthenticated = widget.UI.CheckBox("chkAllowDownloadUnauthenticated", {
    caption: "Allow download by unauthenticated HTML Widgets and Portals?",
  });

  C.chkAllowDefinedOnAccountsApps = widget.UI.CheckBox("chkAllowDefinedOnAccountsApps", {
    caption: "Allow Resource to be defined on Accounts and Applications?",
  });

  C.chkAllowUseEmailAttachment = widget.UI.CheckBox("chkAllowUseEmailAttachment", {
    caption: "Allow use as an Email attachment?",
  });

  C.chkUserFlagA = widget.UI.CheckBox("chkUserFlagA", {
    caption: "User Flag A",
  });

  C.chkUserFlagB = widget.UI.CheckBox("chkUserFlagB", {
    caption: "User Flag B",
  });

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


  // Image Preview
  C.lblImagePreview = widget.UI.Label("lblImagePreview", {});
  C.lblImageDetails = widget.UI.Label("lblImageDetails", {
    style: "normal"
  });
  C.imgPreview = $("#imgPreview");

  // 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);
  //cmdFinish.click(function() { Form_ExecuteAction("Finish"); });

  // Handle Form Buttons
  cmdClear = $("#cmdClear");
  cmdClear.click(cmdClear_Click);
  cmdDownload = $("#cmdDownload");
  cmdDownload.click(cmdDownload_Click);

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

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

  // Load Fields
  Fields_Load();

  // Save Fields (so UserData is in correct format for mOriginalJson)
  Fields_Save();

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

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.txtResourceId.Text(mRecord.ResourceId);
    C.chkActive.Value(mRecord.Active);
    C.txtDescription.Text(mRecord.Description);
    C.cboCategory.Text(mRecord.Category);
    C.txtResourceType.Text(mRecord.ResourceType);
    C.txtFileName.Text(mRecord.FileName);
    C.chkAllowDownloadClientPortals.Value(mRecord.AllowDownloadClientPortals);
    C.chkAllowDownloadUnauthenticated.Value(mRecord.AllowDownloadUnauthenticated);
    C.chkAllowDefinedOnAccountsApps.Value(mRecord.AllowDefinedOnAccountsApps);
    C.chkAllowUseEmailAttachment.Value(mRecord.AllowUseEmailAttachment);
    C.chkUserFlagA.Value(mRecord.UserFlagA);
    C.chkUserFlagB.Value(mRecord.UserFlagB);
    C.txtNotes.Text(mRecord.Notes);
    C.lblImageDetails.Text(mRecord.ImageDescription);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

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

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

  mRecord.Category = C.cboCategory.Text();
  mRecord.FileName = C.txtFileName.Text();
  mRecord.AllowDownloadClientPortals = C.chkAllowDownloadClientPortals.Value();
  mRecord.AllowDownloadUnauthenticated = C.chkAllowDownloadUnauthenticated.Value();
  mRecord.AllowDefinedOnAccountsApps = C.chkAllowDefinedOnAccountsApps.Value();
  mRecord.AllowUseEmailAttachment = C.chkAllowUseEmailAttachment.Value();
  mRecord.UserFlagA = C.chkUserFlagA.Value();
  mRecord.UserFlagB = C.chkUserFlagB.Value();
  mRecord.Notes = C.txtNotes.Text();
}

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

  // Lists
  if (mRecord) {
    // Categories
    C.cboCategory.SetComboFromInformationList("ResourceCategories", true);
  }

  // Controls
  if (mRecord) {
    C.chkAllowDownloadClientPortals.VisibleRow(mRecord.AddonPortal);
    C.chkAllowDefinedOnAccountsApps.Caption("Allow Resource to be defined on Accounts" + (mRecord.AddOnAccountApplication ? " and Applications?" : "?"))
    C.chkAllowDownloadUnauthenticated.Caption("Allow download by unauthenticated HTML Widgets" + (mRecord.AddonPortal ? " and Portals?" : "?"))
    C.chkUserFlagA.Caption(mRecord.UserFlagACaption);
    C.chkUserFlagB.Caption(mRecord.UserFlagBCaption);
  }

  // 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();
    pageImagePreview_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();

    // Is Dirty?
    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();
  }
}

// ==============
// Control events
// ==============
function cmdClear_Click() {
  mRecord.FileDataBase64 = "";
  mRecord.FileName = "";
  mRecord.FileType = "";
  mRecord.ImageDescription = "";
  mRecord.IsImage = false;
  C.fuResourceFile.Clear();

  pageGeneral_Refresh();
  pageImagePreview_Refresh();
}

function cmdDownload_Click() {
  Form_ExecuteAction("DOWNLOAD");
}

function fuResourceFile_Change(sender, e) {
  if (C.fuResourceFile.GetFileData().length != 0) {
    // Load file information; merge into mRecord
    widget.UploadFiles("Upload", {}, C.fuResourceFile.GetFileData(),
      // Success
      function (data) {
        data = JSON.parse(data);
        
        // update mRecord elements with values from data
        mRecord = {...mRecord, ...data};
        
        pageGeneral_Refresh();
      },
  
      // Fail
      function (message) {
        // remove file item 
        cmdClear_Click();
      
        widget.UI.MsgBoxAlert("fail: " + message);
      }
    );
  }
}

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

    case "ImagePreview":
      break;
  }
}

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

    case "ImagePreview":
      pageImagePreview_Refresh();
      break;

    default:
      break;
  }

  // Resize
  tabDetails_Resize();

  // Focus
  switch (tabDetails.SelectedTabId()) {
    default:
      tabDetails.FocusFirst();
      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));

  // 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.txtResourceId.Text());
    },

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

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

// ===========
// pageGeneral
// ===========
function pageGeneral_Refresh() {
  if (!mRecord) return;
  // Controls
  if (mRecord.FileDataBase64 &amp;&amp; mRecord.FileDataBase64.length != 0) {
    C.fuResourceFile.VisibleRow(false);
    C.txtFileName.Text(mRecord.FileName);
    C.txtFileName.VisibleRow(true);
    C.txtResourceType.Text(mRecord.FileType);
    cmdClear.show();
    cmdDownload.show();
  } 
  else {
    C.fuResourceFile.VisibleRow(true);
    C.txtFileName.VisibleRow(false);
    C.txtResourceType.Text("None");
    cmdClear.hide();
    cmdDownload.hide();
  }

  // hide preview if resource is not an image or no resource selected  
  tabDetails.TabVisible("ImagePreview", mRecord.IsImage);
}

// ================
// pageImagePreview
// ================
function pageImagePreview_Refresh() {

  if (!mRecord) return;

  // Controls
  if (mRecord.FileDataBase64.length != 0) {
    if (mRecord.IsImage){
      C.imgPreview.show();
      if (mRecord.FileType == "SVG") {
        C.imgPreview.attr("src", "data:image/svg+xml;base64, " + mRecord.FileDataBase64);
      }
      else {  
        C.imgPreview.attr("src", "data:image/png;base64, " + mRecord.FileDataBase64);
      }    
    } 
    else {
      C.imgPreview.hide();
    }
    C.lblImageDetails.Text(mRecord.ImageDescription);
  } 
  else {
    C.imgPreview.hide();
    C.lblImageDetails.Text("No file selected.");
  }
}

// ===============
// Validate Wizard
// ===============
function tabDetails_Validate(validCallback) {
  // Validate
  var Ok = tabDetails.Validate(true);

  // Other client-side validation
  if (Ok) {
    switch (tabDetails.SelectedTabId()) {
      case "General":
        if (C.fuResourceFile.GetFileData().length == 0) {
          Ok = false;
          widget.UI.MsgBoxAlert("No file selected.");
        }
        break;
        
      default:
        // No validation
        validCallback();
        return;
    }
  }

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

    switch (tabDetails.SelectedTabId()) {
      case "General":
        break;

      default:
        break;
    }

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

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

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

function tabDetails_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 tabDetails_Refresh
    switch (tabDetails.SelectedTabId()) {
      case "General":
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}


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

    case "FINISH":
      // Finish
      if (mRecord.ReadOnly) {
        tabWizard_Cancel();
      }
      else {
        Form_ExecuteAction_Finish();
      }
      break;
      
    default:
      window.alert(mViewName + ".Form_ExecuteAction: Unhandled action '" + actionId + "'");
      break;
  }
}

function Form_ExecuteAction_Download() {
  var params = JSON.parse(JSON.stringify(mRecord));

  // Download File
  widget.DownloadFile("Download", params,
    // Success
    function() {
    },

    // Fail
    function(errorMessage) {
      // Error Message
      widget.UI.MsgBoxAlert(errorMessage);
    }
  );
}

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

&lt;/script&gt;
</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>BKuvQRpGqkSwhR10dPjYDg</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Resource</Caption>
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>800</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>HWRESOURCE</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>True</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="ResourceId" type="Range">
            <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>
            <LimitToList>false</LimitToList>
            <MaxLength>10</MaxLength>
            <RangeSingle>true</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>Resources</RangeLookupSource>
            <RangeLookupSqlWhere />
          </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.Resources</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</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>