<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2025-03-07T00:50:52.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2025-03-05T02:00:18.4100000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2025-03-07T00:50:00.1970000</UpdatedUtcDate>
    <ScriptId>HWQIE</ScriptId>
    <Description>Queue Item Edit</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_QueueItemEdit
Option Explicit On
Option Strict On

' #################################################################
' Queue Item Edit form HTML Widget
'
' (C) Copyright Intersoft Systems Limited 2025
'
' Version: 1.00 (07/03/2025)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  07/03/2025  ISS      J035224   Created
' #################################################################

' Constants
Private Const FORM_KEY As String = "Queues"

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

' Standard Parameters
Private mQueueId As String
Private mQueueItemPk As Integer
Private mDuplicateRecordPk As Integer
Private mReadOnly As Boolean

' Other Parameters
Private mSource As String = "QUEUE" ' Potentially for future use

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
    mQueueId = .GetString("QueueId")
    mQueueItemPk = .GetInteger("QueueItemPk") ' Note that Queue Items do not have a unique Id
  End With
  With mCombinedParameters
    mDuplicateRecordPk = .GetInteger("DuplicateRecordPk")
    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 "Finish"
        ' Finish wizard
        Main = Finish(parametersJson, requestInfo, returnValue)

      Case "GetInitialisationInfo"
        ' Get Initialisation Information required for this wizard
        Main = GetInitialisationInfo(returnValue)
        
      Case "WizardValidate"
        ' Wizard Validate
        Main = WizardValidate(parametersJson, returnValue)

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

End Function

''' &lt;summary&gt;
'''  Load Queue.
''' &lt;/summary&gt;
Private Function GetQueueItem(Queue As finQueue,
                        ByRef QueueItem As finQueueItem) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Create and Load Queue Item
  If Success Then
    ' Load Queue Item
    If mDuplicateRecordPk &lt;&gt; 0 Then
      ' TODO: Discuss with paul as to if we allow duplicating queue items and how it should work.
      ' New record (by duplicating existing)
'      Queue.Items()
'      Success = Queue.Load(mDuplicateRecordId)
'      If Success Then Queue.Duplicate()
    ElseIf mQueueItemPk &lt;= 0 Then
      ' Create Queue Item
      QueueItem = Queue.Items.CreateQueueItem()
    Else
      QueueItem = Queue.Items.ItemByPk(mQueueItemPk)
    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 dv As DataView
  Dim ExportFolderTagsList As ISCodeDescriptionList
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Queue As finQueue
  Dim QueueItem As finQueueItem
  Dim sqwb As ISSqlWhereBuilder
  Dim Success As Boolean

  ' Assume Success
  Success = True
  
  ' Initialise
  ExportFolderTagsList = finBL.Runtime.CreateCodeDescriptionList()
  Queue = finBL.CreateQueue()
  sqwb = finBL.Database.CreateSqlWhereBuilder()

  ' Validate

  ' Get Queue
  If Success Then
    Success = Queue.Load(mQueueId)
  End If
  
  ' Get Queue Item
  If Success Then
    Success = GetQueueItem(Queue, QueueItem)
  End If
  
  ' Validate Queue Item
  If Success Then
    If QueueItem Is Nothing Then
      Success = False
      finBL.Error.ErrorBegin("Failed to retrieve Queue Item")
    End If 
  End If

  ' Get Initialisation Info
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Form
      If finBL.Database.IsReadOnly OrElse mReadOnly OrElse Not finBL.CurrentUser.Permissions.Allow("Admin.Queues") Then
        .ReadOnly = True
      Else
        .ReadOnly = False
      End If

      ' Record
      .Pk = QueueItem.Pk
      .Timestamp = Queue.Timestamp

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

      ' General
      If .AllowPageGeneral Then
        .Active = QueueItem.Active
        .ItemName = QueueItem.ItemName
        
        .ItemType = finBL.Enums.iseQueueItemType_ToString(QueueItem.ItemType)
        
        .ItemId = QueueItem.ItemId
      End If
      
      ' Permissions

      ' Lists
      .ListItemType = finBL.Enums.iseQueueItemType_GetList(False, mSource &lt;&gt; "QUEUE").ToCsvString()
      If finBL.Reports.Reports.GetDataView(dv) Then
        .ListReports = finBL.CreateCodeDescriptionList()
        .ListReports.FromDataTable(dv.ToTable(), "ReportId", "Name")
      End If
      
      If finBL.Reports.Queries.GetDataView(dv) Then
        .ListQuerys = finBL.CreateCodeDescriptionList()
        .ListQuerys.FromDataTable(dv.ToTable(), "QueryId", "Name")
      End If
      
      ' Filters
      With sqwb
        .Clear()
        .AppendComparisonIntegerBoolean("AllowStandalone", "=", True)
      End With
      .FilterDocuments = finBL.HtmlWidgetUtilities.EncryptSql(sqwb.SqlWhere)
      
      .FilterScripts = finBL.HtmlWidgetUtilities.EncryptSql(finBL.Scripts.GetDataViewFilterQueues())
      
      ' Collections
      
      ' Configuration
      .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 Queue.
''' &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 Queue As finQueue
  Dim QueueItem As finQueueItem
  Dim Record As FormInitialisationInfo
  Dim Success As Boolean

  ' Assume Success
  Success = True
  
  ' Initialise
  Queue = finBL.CreateQueue()

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

  ' Get Queue
  If Success Then
    Success = Queue.Load(mQueueId)
  End If
  
  ' Get QueueItem
  If Success Then
    Success = GetQueueItem(Queue, QueueItem)
  End If

  ' Validate
  If Success Then
    If Record.Timestamp &lt;&gt; Queue.Timestamp Then
      Success = False
      finBL.Error.ErrorBegin("This record has been updated by another User.")
    ElseIf QueueItem Is Nothing Then
      Success = False
      finBL.Error.ErrorBegin("Failed to retrieve Queue Item")
    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 Queue
      With QueueItem
        ' General
        If Record.AllowPageGeneral Then
          .Active = Record.Active
          .ItemName = Record.ItemName
          
          .ItemType = finBL.Enums.iseQueueItemType_FromString(Record.ItemType)
          
          .ItemId = Record.ItemId
        End If
      End With

      ' Save
      If Success Then
        ' Add the QueueItem to the Queue Item collection
        If mQueueItemPk &lt;= 0 AndAlso Not Queue.Items.ExistsPk(mQueueItemPk) Then
          ' New Item
          Queue.Items.Add(QueueItem)
        End If 
        
        Success = Queue.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 [ReadOnly] As Boolean

  ' Record
  Public Pk As Integer
  Public Timestamp As Integer

  ' General
  Public Active As Boolean
  Public ItemName As String
  
  Public ItemType As String
  
  Public ItemId As String
  
  ' Permissions
  Public AllowPageGeneral As Boolean

  ' Lists
  Public ListItemType As String
  Public ListReports As ISCodeDescriptionList
  Public ListQuerys As ISCodeDescriptionList
  
  ' SQL WHERE filters
  Public FilterDocuments As String
  Public FilterScripts As String

  ' Configuration
  Public PromptOnSave As Boolean

End Class


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

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

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

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

  End Sub

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System-supplied HTML Widget to edit a Queue Item.</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;Queue Item&lt;/div&gt;
    &lt;div class="summary"&gt;Enter Queue Item details.&lt;/div&gt;
  
    &lt;!-- Tabs --&gt;
    &lt;div id="tabWizard" class="is-tabs"&gt;
      &lt;ul&gt;
        &lt;li tabId="General"&gt;Queue Item&lt;/li&gt;
        &lt;li tabId="SavedParameters"&gt;Saved Parameters&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:8em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblItemName"&gt;Enter a Name for this Item&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtItemName"&gt;Name:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtItemName"/&gt; &lt;input id="chkActive" type="checkbox"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblItemType"&gt;Select the Item Type&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboItemType"&gt;Item Type:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboItemType"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr class="ItemTypeControlRow"&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSelectReport"&gt;Select Report&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr class="ItemTypeControlRow"&gt;
          &lt;th&gt;&lt;label for="cboItemReport"&gt;Report:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboItemReport"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr class="ItemTypeControlRow"&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSelectDocument"&gt;Select Document&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr class="ItemTypeControlRow"&gt;
          &lt;th&gt;&lt;label for="cboItemDocument"&gt;Document:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboItemDocument"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr class="ItemTypeControlRow"&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSelectScript"&gt;Select Script&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr class="ItemTypeControlRow"&gt;
          &lt;th&gt;&lt;label for="cboItemScript"&gt;Script:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboItemScript"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr class="ItemTypeControlRow"&gt;
          &lt;th colspan="2"&gt;&lt;label id="lblSelectQuery"&gt;Select Query&lt;/label&gt;&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr class="ItemTypeControlRow"&gt;
          &lt;th&gt;&lt;label for="cboItemQuery"&gt;Query:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboItemQuery"/&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
    
    &lt;!-- Saved Parameters --&gt;
    &lt;div id="pageSavedParameters"&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="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;Save&lt;/button&gt;
  &lt;/footer&gt;

&lt;/div&gt;


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

var mOriginalJson;

// Controls
var C = {
  // General
  lblItemName: null,
  txtItemName: null,
  chkActive: null,
  
  lblItemType: null,
  cboItemType: null,
  
  lblSelectReport: null,
  cboItemReport: null,
  
  lblSelectDocument: null,
  cboItemDocument: null,
  
  lblSelectScript: null,
  cboItemScript: null,
  
  lblSelectQuery: null,
  cboItemQuery: null,
  
  // Saved Parameters
}

// Form
var frmMain;
var tabWizard;

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

// Other

// ==========
// Initialise
// ==========
$(function () {
  // --------
  // Controls
  // --------
  //   General
  C.lblItemName = widget.UI.Label("lblItemName", {});
  C.txtItemName = widget.UI.TextBox("txtItemName", {
    maxLength: 50,
    allowBlank: false
  });
  C.chkActive = widget.UI.CheckBox("chkActive", {
    caption: "Active?"
  });
  
  C.lblItemType = widget.UI.Label("lblItemType", {});
  C.cboItemType = widget.UI.ComboBox("cboItemType", {
    limitToList: true,
    allowBlank: false,
    
    onChange: cboItemType_Change
  });
  
  C.lblSelectReport = widget.UI.Label("lblSelectReport", {});
  C.cboItemReport = widget.UI.DBCombo("cboItemReport", {
    limitToList: true,
    allowBlank: false,
  });
  
  C.lblSelectDocument = widget.UI.Label("lblSelectDocument", {});
  C.cboItemDocument = widget.UI.DBCombo("cboItemDocument", {
    limitToList: true,
    allowBlank: false,
  });
  
  C.lblSelectScript = widget.UI.Label("lblSelectScript", {});
  C.cboItemScript = widget.UI.DBCombo("cboItemScript", {
    limitToList: true,
    allowBlank: false,
  });
  
  C.lblSelectQuery = widget.UI.Label("lblSelectQuery", {});
  C.cboItemQuery = widget.UI.DBCombo("cboItemQuery", {
    limitToList: true,
    allowBlank: false,
  });

  // Grids

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

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

  // Handle 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");
  cmdBack = $("#cmdBack");
  cmdNext = $("#cmdNext");
  cmdFinish = $("#cmdFinish");
  cmdCancel.click(function() { Form_ExecuteAction("Cancel"); });
  cmdBack.click(function() { tabWizard_Move(-1); });
  cmdNext.click(function() { tabWizard_Move(1); });
  cmdFinish.click(function() { Form_ExecuteAction("Finish"); });

  // Reset
  Form_Reset();
});

// ==========
// Reset Form
// ==========
function Form_Reset() {
  // 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) {
    tabWizard.SelectedTabId(mRecord.PageId);

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

  // Page Permissions
  if (!mRecord.AllowPageGeneral) tabWizard.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.txtItemName.Text(mRecord.ItemName);
    C.chkActive.Value(mRecord.Active);
    
    C.cboItemType.Text(mRecord.ItemType);
    
    // Set Item Id to correct control depending on ItemType
    switch (mRecord.ItemType) {
      case "Report":
        C.cboItemReport.Text(mRecord.ItemId);
        break;
        
      case "Document":
        C.cboItemDocument.Text(mRecord.ItemId);
        break;
        
      case "Script":
        C.cboItemScript.Text(mRecord.ItemId);
        break;
        
      case "Query":
        C.cboItemQuery.Text(mRecord.ItemId);
        break;
    }
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabWizard_Refresh();
  tabWizard_Resize();
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // General
  mRecord.ItemName = C.txtItemName.Text();
  mRecord.Active = C.chkActive.Value();
  
  mRecord.ItemType = C.cboItemType.Text();
  
  // Set ItemId depending on ItemType
  switch (mRecord.ItemType) {
    case "Report":
      mRecord.ItemId = C.cboItemReport.Text();
      break;
      
    case "Document":
      mRecord.ItemId = C.cboItemDocument.Text();
      break;
      
    case "Script":
      mRecord.ItemScript = C.cboItemScript.Text();
      break;
      
    case "Query":
      mRecord.ItemQuery = C.cboItemQuery.Text();
      break;
  }
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  if (mRecord) {
    if (mRecord.Pk) {
      widget.SetHeading("Queue Item");
    }
    else {
      widget.SetHeading("New Queue Item");
    }
  }

  // Lists
  if (mRecord) {
    // Defaults
    C.cboItemType.ListFromCsvString(mRecord.ListItemType);
    C.cboItemReport.RefreshFromCodeDescriptionList(mRecord.ListReports);
    C.cboItemDocument.RefreshFromStandardRange("Documents", mRecord.FilterDocuments, null, (mRecord.ItemType == "Document") ? mRecord.ItemId : null);
    C.cboItemScript.RefreshFromStandardRange("Scripts", mRecord.FilterScripts, null, (mRecord.ItemType == "Script") ? mRecord.ItemId : null);
    C.cboItemQuery.RefreshFromCodeDescriptionList(mRecord.ListQuerys);
  }

  // Controls
  if (mRecord) {
    // Defaults
  
    // Change Events
    cboItemType_Change();
  }

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

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

  // Resize Tab
  tabWizard_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
  tabWizard_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 tabWizard_Cancel() {
  if (Form_IsDirty()) {
    // Confirm
    widget.UI.MsgBoxConfirm("Are you sure you want to close this form without saving your changes?", { heading: "Close Form" }, tabWizard_Cancel_Finalise);
  }
  else {
    // Cancel immediately
    tabWizard_Cancel_Finalise();
  }
}

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

// ==========
// Resize Tab
// ==========
function tabWizard_Resize() {
  switch (tabWizard.SelectedTabId()) {
    case "General":
      // General
      C.txtItemName.WidthResizeFromParent();
      C.cboItemType.WidthResizeFromParent();
      C.cboItemReport.WidthResizeFromParent();
      C.cboItemDocument.WidthResizeFromParent();
      C.cboItemScript.WidthResizeFromParent();
      C.cboItemQuery.WidthResizeFromParent();
      break;
      
    case "SavedParameters":
      break;
  }
}

// ==============
// Update Buttons
// ==============
function tabWizard_UpdateButtons() {
  // Back, Next, Finish Buttons Valid?
  var tabIndex = tabWizard.SelectedTabIndex();
  cmdBack.prop("disabled", tabIndex &lt;= 0);
  cmdNext.prop("disabled", tabIndex &gt;= tabWizard.TabCount() - 1);
  cmdFinish.prop("disabled", !cmdNext.prop("disabled"));

  // Exceptions
  if (mRecord) {
  }
}

// ===========
// 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":
        // Accruals
        pageGeneral_Refresh();
        break;

      default:
        break;
    }
  }

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

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

  // Update Heading
  switch (tabWizard.SelectedTabId()) {
    case "General":
      frmMain.RefreshHeading("Queue Item", "Enter Item details.");
      break;
      
    case "SavedParameters":
      frmMain.RefreshHeading("Saved Parameters", "Saved Parameter details.");
      break;
    
    default:
      frmMain.RefreshHeading(tabWizard.TabCaption(tabWizard.SelectedTabId()), tabWizard.TabTooltipText(tabWizard.SelectedTabId()));
      break;
  }

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

  // Resize Wizard
  tabWizard_Resize();

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

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

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

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

    switch (tabWizard.SelectedTabId()) {
      case "General":
        // General
        var params = CreateFinishParameters();
        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()) {
      default:
        break;
    }

    // Callback
    validCallback();
  }
}

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

  // Enable form
  frmMain.FormEnable();
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId, data) {
  switch(actionId.toUpperCase()) {
    case "CANCEL":
      // Cancel
      tabWizard_Cancel();
      break;
      
    case "FINISH":
      // Finish
      Form_ExecuteAction_Finish();
      break;
      
    default:
      window.alert("Unhandled action '" + actionId + "'");
  }
}

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

  // Validate
  Ok = tabWizard.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.ListReports = null;
  params.ListQuerys = 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.txtQueueId.Text());
    },
    function (data) {
      // Show Error
      widget.UI.MsgBoxAlert(data);

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

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

  // Controls
}

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

// ==============
// Change Events
// ==============
function cboItemType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Hide all "ItemType" controls
  $(".ItemTypeControlRow").hide();

  // Show only necessary controls
  switch (C.cboItemType.Text()) {
    case "Report":
      C.lblSelectReport.VisibleRow(true);
      C.cboItemReport.VisibleRow(true);
      break;
      
    case "Document":
      C.lblSelectDocument.VisibleRow(true);
      C.cboItemDocument.VisibleRow(true);
      break;
      
    case "Script":
      C.lblSelectScript.VisibleRow(true);
      C.cboItemScript.VisibleRow(true);
      break;
      
    case "Query":
      C.lblSelectQuery.VisibleRow(true);
      C.cboItemQuery.VisibleRow(true);
      break;
  }
}

&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <UniqueId>P1lRf2b3Hk6qx9pagvm4oA</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Queue Item</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>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon>Queue</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 />
            <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="QueueItemPk" type="Number">
            <BlankTip />
            <Caption>Queue Item Pk</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>false</GroupDigits>
            <MaxValue />
            <MinValue>0</MinValue>
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="QueueId" type="Range">
            <BlankTip />
            <Caption>Queue Id</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>Queues</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="DuplicateRecordPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>false</GroupDigits>
            <MaxValue />
            <MinValue>0</MinValue>
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </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>