<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-05-16T04:52:11.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2024-04-15T04:45:50.2400000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-05-16T04:50:24.8470000</UpdatedUtcDate>
    <ScriptId>CE</ScriptId>
    <Description>Calendar Edit</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_CalendarEdit
Option Explicit On
Option Strict On

' #################################################################
' Calendar Edit form HTML Widget
'
' Version: 1.01 (16/05/2024)
'
' Usage: System-supplied HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  05/03/2024  ISS      J032705   Created
'    1.01  16/05/2024  ISS      J033314   Added support for automatic Calendars
' #################################################################

' Constants
Private Const FORM_KEY As String = "Calendars"

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

' Standard Parameters
Private mCalendarId As String
Private mDuplicateRecordId As String
Private mNonWorkingDayBackgroundColour As String
Private mNonWorkingDayColour 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
    mCalendarId = .GetString("CalendarId") ' Always use Startup Parameters since the Calendar Id may be updated
  End With
  With mCombinedParameters
    mDuplicateRecordId = .GetString("DuplicateRecordId")
    mNonWorkingDayBackgroundColour = .GetString("NonWorkingDayBackgroundColour")
    mNonWorkingDayColour = .GetString("NonWorkingDayColour")
    mPage = .GetString("Page")
    mReadOnly = .GetBoolean("ReadOnly")
  End With

  ' Override Parameters
  If Len(mNonWorkingDayBackgroundColour) = 0 Then
    mNonWorkingDayBackgroundColour = finBL.CloudConnectFunctions.CloudConnectSettings.Theme.ContrastColourBackgroundResolved
  End If
  If Len(mNonWorkingDayColour) = 0 Then
    mNonWorkingDayColour = finBL.CloudConnectFunctions.CloudConnectSettings.Theme.ContrastColourForegroundResolved
  End If
  
  ' 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 "AddNonWorkingDay"
        ' Add a Non-Working Day
        Main = AddNonWorkingDay(returnValue)
        
      Case "SortNonWorkingDays"
        ' Sort Non-Working Days
        Main = SortNonWorkingDays(returnValue)
        
      Case "Finish"
        ' Finish wizard
        Main = Finish(parametersJson, requestInfo, returnValue)

      Case "GetDateInfo"
        ' Get date information
        Main = GetDateInfo(returnValue)
        
      Case "RefreshAutomaticNonWorkingDays"
        ' Refresh automatic non-working days
        RefreshAutomaticNonWorkingDays(parametersJson, 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 Calendar.
''' &lt;/summary&gt;
Private Function GetCalendar(ByRef calendar As finCalendar) As Boolean

  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Create and Load Calendar
  If Success Then
    ' Create Calendar
    calendar = finBL.CreateCalendar()

    ' Load Calendar
    If Len(mDuplicateRecordId) &lt;&gt; 0 Then
      ' New record (by duplicating existing)
      Success = calendar.Load(mDuplicateRecordId)
      If Success Then calendar.Duplicate()
    ElseIf Len(mCalendarId) = 0 Then
      ' New record
    Else
      Success = calendar.Load(mCalendarId)
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Adds a new Non-Working Day.
''' &lt;/summary&gt;
Private Function AddNonWorkingDay(ByRef returnValue As String) As Boolean
  
  Dim Calendar As finCalendar
  Dim CalendarNonWorkingDay As finCalendarNonWorkingDay
  Dim DateFrom As Date
  Dim DateTo As Date
  Dim Description As String
  Dim i As Integer
  Dim NonWorkingDate As Date
  Dim NonWorkingDaysJson As String
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Parameters
  With mCombinedParameters    
    DateFrom = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("DateFrom"))
    DateTo = finBL.HtmlWidgetUtilities.GetDatabaseDateFromJsonUtcDate(.GetDate("DateTo"))
    Description = .GetString("Description")
    NonWorkingDaysJson = .GetString("NonWorkingDaysJson")
  End With
  
  ' Load Calendar
  Success = GetCalendar(Calendar)
  
  ' Populate Non-Working Days
  If Success Then
    Success = Calendar.NonWorkingDays.FromHtmlWidgetJsonString(NonWorkingDaysJson)
  End If
  
  ' Add Non-Working Dates
  If Success Then
    NonWorkingDate = DateFrom    
    
    Do
      ' Delete Date
      i = Calendar.NonWorkingDays.IndexFromDate(NonWorkingDate)
      If i &lt;&gt; -1 Then
        Calendar.NonWorkingDays.RemoveAt(i)
      End If

      ' Increment Date
      NonWorkingDate = NonWorkingDate.AddDays(1)

      ' Quit?
      If DateTo = Nothing OrElse NonWorkingDate &gt; DateTo Then Exit Do
    Loop
    
    ' Add
    NonWorkingDate = DateFrom
    Do
      ' Add Date
      CalendarNonWorkingDay = Calendar.NonWorkingDays.CreateNonWorkingDay()
      With CalendarNonWorkingDay
        .NonWorkingDate = NonWorkingDate
        .Description = Description
      End With
      Calendar.NonWorkingDays.Add(CalendarNonWorkingDay)

      ' Increment Date
      NonWorkingDate = NonWorkingDate.AddDays(1)

      ' Quit?
      If DateTo = Nothing OrElse NonWorkingDate &gt; DateTo Then Exit Do
    Loop
    
    ' Sort Non-Working Days
    Calendar.NonWorkingDays.Sort()
  End If
  
  ' Return new collection
  If Success Then
    returnValue = Calendar.NonWorkingDays.ToHtmlWidgetJsonString()
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Sort Non-Working Days.
''' &lt;/summary&gt;
Private Function SortNonWorkingDays(ByRef returnValue As String) As Boolean
  
  Dim Calendar As finCalendar
  Dim NonWorkingDaysJson As String
  Dim Success As Boolean
  
  ' Assume Success
  Success = True
  
  ' Parameters
  With mCombinedParameters    
    NonWorkingDaysJson = .GetString("NonWorkingDaysJson")
  End With
  
  ' Load Calendar
  Success = GetCalendar(Calendar)
  
  ' Populate Non-Working Days
  If Success Then
    Success = Calendar.NonWorkingDays.FromHtmlWidgetJsonString(NonWorkingDaysJson)
  End If
  
  ' Sort and Return
  If Success Then
    Calendar.NonWorkingDays.Sort()
    returnValue = Calendar.NonWorkingDays.ToHtmlWidgetJsonString()
  End If
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Get information about a specific date.
''' &lt;/summary&gt;
Private Function GetDateInfo(ByRef returnValue As String) As Boolean
  
  Dim Success As Boolean
  Dim DateAsAt As Date
  
  ' Assume Success
  Success = True
  
  ' Params
  With mCombinedParameters
    DateAsAt = finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(.GetDate("DateAsAt"))
  End With
  
  ' Format
  returnValue = Format(DateAsAt, finBL.Settings.DateFormatLongDocumentsResolved)
  
  Return Success
  
End Function

''' &lt;summary&gt;
'''  Refresh automatic non-working days.
''' &lt;/summary&gt;
Private Function RefreshAutomaticNonWorkingDays(parametersJson As String,
                                                ByRef returnValue As String) As Boolean
                        
  Dim Calendar As finCalendar
  Dim obj As Object
  Dim Record As FormInitialisationInfo
  Dim Success As Boolean
  
  ' Assume Success
  Success = True  
  
  ' Get Calendar
  Success = GetCalendar(Calendar)
  
  ' Parse Parameters
  If Success Then    
    If finBL.Runtime.WebUtilities.DeserialiseJsonStringToObject(parametersJson, GetType(FormInitialisationInfo), obj) Then
      Record = DirectCast(obj, FormInitialisationInfo)
    Else
      Success = False
    End If
  End If
  
  ' Update Calendar
  If Success Then
    With Calendar
      .CalendarId = Record.CalendarId
      .Description = Record.Description
      
      .AutomaticCalendar = Record.AutomaticCalendar
      .SetAutomaticCountryDetails(finBL.SupportedCountries.ItemByNameSafe(Record.AutomaticCalendarCountryName).CountryCode, Record.AutomaticCalendarState)
      
      ' Non-Working Days
      Success = .NonWorkingDays.FromHtmlWidgetJsonObject(Record.NonWorkingDays)    
    End With  
  End If
       
  ' Update non-working days
  If Success Then
    If Calendar.AutomaticCalendarResolved Then
      Calendar.AppendAutomaticNonWorkingDays()
    Else 
      Calendar.NonWorkingDays.RemoveAutomatic()
    End If
  End If
  
  ' Return Value
  If Success Then
    returnValue = Calendar.NonWorkingDays.ToHtmlWidgetJsonString()
  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 Calendar As finCalendar
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim Success As Boolean
  Dim strTemp As String

  ' Assume Success
  Success = True

  ' Validate

  ' Get Calendar
  If Success Then
    Success = GetCalendar(Calendar)
  End If

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

      ' Record
      .Pk = Calendar.Pk
      .Timestamp = Calendar.Timestamp

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

      ' General
      .CalendarId = Calendar.CalendarId ' Always need to return Calendar Id
      If .AllowPageGeneral Then
        .Description = Calendar.Description
        .NonWorkingDays = Calendar.NonWorkingDays.ToHtmlWidgetJsonObject()
        
        .AutomaticCalendar = Calendar.AutomaticCalendar
        .AutomaticCalendarCountryName = Calendar.AutomaticCalendarCountryName
        .AutomaticCalendarState = Calendar.AutomaticCalendarState
      End If

      ' Other

      ' Permissions

      ' Lists
      For Each strTemp In finBL.SupportedCountries.GetCountryNamesList(False, False)
        .Countries.Add(New Country(finBL.SupportedCountries.ItemByNameSafe(strTemp)))
      Next 
      
      ' Configuration
      .AddHolidaysHtmlWidgetId = finBL.CloudConnectFunctions.GetAdministrationHtmlWidgetId(isefinCloudConnectAdministrationScriptType.HtmlWidgetCalendarHolidaysAdd, False)
      .HideOtherPages = mCombinedParameters.GetBoolean("HideOtherPages", False)
      .NonWorkingDayBackgroundColour = mNonWorkingDayBackgroundColour
      .NonWorkingDayColour = mNonWorkingDayColour
      .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 Calendar.
''' &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 Calendar As finCalendar
  Dim obj As Object
  Dim Record As FormInitialisationInfo
  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 Calendar
  If Success Then
    Success = GetCalendar(Calendar)
  End If

  ' Validate
  If Success Then
    If Record.Timestamp &lt;&gt; Calendar.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 Calendar
    With Calendar
      ' General
      If Record.AllowPageGeneral Then
        .CalendarId = Record.CalendarId
        .Description = Record.Description
        
        .AutomaticCalendar = Record.AutomaticCalendar
        .SetAutomaticCountryDetails(finBL.SupportedCountries.ItemByNameSafe(Record.AutomaticCalendarCountryName).CountryCode, Record.AutomaticCalendarState)
        
        ' Non-Working Days
        Success = .NonWorkingDays.FromHtmlWidgetJsonObject(Record.NonWorkingDays)
      End If
    End With

    ' Save
    If Success Then
      Success = Calendar.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;
''' &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 CalendarId As String
  Public Description As String
  
  Public AutomaticCalendar As Boolean
  Public AutomaticCalendarCountryName As String
  Public AutomaticCalendarState As String
  
  Public NonWorkingDays As List(Of finCalendarNonWorkingDays.jsonHtmlWidgetCalendarNonWorkingDay)

  ' Permissions
  Public AllowPageGeneral As Boolean

  ' Lists
  Public Countries As New List(Of Country)

  ' Configuration
  Public AddHolidaysHtmlWidgetId As String
  Public HideOtherPages As Boolean
  Public NonWorkingDayBackgroundColour As String
  Public NonWorkingDayColour As String
  Public PromptOnSave As Boolean  

End Class


''' &lt;summary&gt;
'''  A supported Country.
''' &lt;/summary&gt;
Public Class Country
  
  Public CountryCode As String
  Public CountryName As String
  Public SupportsStateHolidays As Boolean
  Public TerminologyState As String
  Public States As String
  
  Public Sub New(supportedCountryBase As finSupportedCountryBase)
    
    With supportedCountryBase
      Me.CountryCode = .CountryCode
      Me.CountryName = .CountryName      
      
      If .UseStateHolidays Then
        Me.SupportsStateHolidays = True
        Me.States = .AddressStatesList.ToCsvString()
        Me.TerminologyState = .Terminology(isefinCountryTerminology.AddressState)
      End If
    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 edit a Calendar.</Notes>
    <PermissionKeyExecute />
    <ReferenceLinq>false</ReferenceLinq>
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;style type="text/less"&gt;
  .date-display {
    display:flex;    
    flex-direction:column;
    text-align: center;
    font-weight: bold;
    
    span {
      font-size:15px;
    }
    
    span:first-child {
      padding-bottom:8px;
    }
  }
&lt;/style&gt;

&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;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;div style="display:flex; flex-direction:column; position:absolute; top:0; left:0; right:0; bottom:0; padding:4px"&gt;
        &lt;div style="flex-grow:0"&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="lblCodeAndName"&gt;Code and Description&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="txtCalendarId"&gt;Code:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="txtCalendarId"/&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="lblAutomationOptions"&gt;Automation options&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;input id="chkAutomaticCalendar" type="checkbox" /&gt;&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboAutomaticCalendarCountryCode"&gt;Country:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboAutomaticCalendarCountryCode"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;th&gt;&lt;label for="cboAutomaticCalendarState"&gt;State:&lt;/label&gt;&lt;/th&gt;
              &lt;td&gt;&lt;input id="cboAutomaticCalendarState"/&gt;&lt;/td&gt;
            &lt;/tr&gt;
            
            &lt;tr&gt;
              &lt;th colspan="2"&gt;&lt;label id="lblCalendarDetails"&gt;Calendar Details&lt;/label&gt;&lt;/th&gt;
            &lt;/tr&gt;        
          &lt;/table&gt;
        &lt;/div&gt;
        
        &lt;div style="position:relative; flex-grow:1; display:flex; flex-directon:row"&gt;
          &lt;div style="position:relative; flex-grow:0"&gt;
            &lt;div class="calendar-area" style="flex-grow:0; width:320px"&gt;
              &lt;div id="calCalendar"&gt;&lt;/div&gt;
              &lt;div style="text-align:center; padding:8px"&gt;&lt;button id="cmdToday" class="is-button"&gt;Today&lt;/button&gt;&lt;/div&gt;
              &lt;div id="calCalendarInfo" class="date-display"&gt;&lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
          &lt;div style="position:relative; flex-grow:1"&gt;
            &lt;div id="gridNonWorkingDays" class="is-dock-fill"&gt;&lt;/div&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="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;!-- frmAddNonWorkingDay BEGIN --&gt;
&lt;div id="frmAddNonWorkingDay"  class="is-widget-form-body" style="display:none"&gt;
  &lt;table class="is-form"&gt;
    &lt;colgroup&gt;
      &lt;col style="width:10em" /&gt;
      &lt;col /&gt;
    &lt;/colgroup&gt;

    &lt;tr&gt;
      &lt;th colspan="2"&gt;&lt;label id="lblNonWorkingDate"&gt;Non-Working Date&lt;/label&gt;&lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;&lt;label for="dateFrom"&gt;Date:&lt;/label&gt;&lt;/th&gt;
      &lt;td&gt;&lt;input id="dateFrom"/&gt;&amp;nbsp;&amp;nbsp;to&amp;nbsp;&amp;nbsp;&lt;input id="dateTo"/&gt;&lt;/td&gt;
    &lt;/tr&gt;
    
    &lt;tr&gt;
      &lt;th colspan="2"&gt;&lt;label id="lblDescription"&gt;Non-Working Day Description&lt;/label&gt;&lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;&lt;label for="txtNonWorkingDayDesc"&gt;Description:&lt;/label&gt;&lt;/th&gt;
      &lt;td&gt;&lt;input id="txtNonWorkingDayDesc"/&gt;&lt;/td&gt;
    &lt;/tr&gt;    
  &lt;/table&gt;
&lt;/div&gt;
&lt;!-- frmAddNonWorkingDay END --&gt;

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

var mOriginalJson;

// Controls
var C = {
  //   General
  lblCodeAndName: null,
  txtCalendarId: null,
  txtDescription: null,
  
  lblAutomationOptions: null,
  chkAutomaticCalendar: null,
  cboAutomaticCalendarCountryCode: null,
  cboAutomaticCalendarState: null,
  
  lblCalendarDetails: null,
  calCalendar: null,
  calCalendarInfo: null,
    
  gridNonWorkingDays: null,
  
  //   frmAddNonWorkingDay
  lblNonWorkingDate: null,
  dateFrom: null,
  dateTo: null,
  
  lblDescription: null,
  txtNonWorkingDayDesc: null,
}

// Form
var frmMain;
var tabDetails;

// Buttons
var cmdCancel;
var cmdFinish;

var cmdToday;

// Other
var mForm_AddNonWorkingDay;
var mMarkers;

// ==========
// Initialise
// ==========
$(function () {
  // --------
  // Controls
  // --------
  //   General
  C.lblCodeAndName = widget.UI.Label("lblCodeAndName", {});
  C.txtCalendarId = widget.UI.TextBox("txtCalendarId", {
    allowBlank: false,
    maxLength: 5,
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });
  C.txtDescription = widget.UI.TextBox("txtDescription", {
    allowBlank: false,
    maxLength: 50,
  });

  C.lblAutomationOptions = widget.UI.Label("lblAutomationOptions", {
    tooltipText: "Automating a Calendar removes the need to perform manual updates for standard holidays for a Country / State combination. Holidays will be automatically respected for the selected Country / State (where applicable) combination.\n\nAny non-standard non-working day / holiday can still be added to automatic Calendars manually."
  });
  C.chkAutomaticCalendar = widget.UI.CheckBox("chkAutomaticCalendar", {
    caption: "Automate Calendar?",
    
    onChange: chkAutomaticCalendar_Change,
  });
  C.cboAutomaticCalendarCountryCode = widget.UI.ComboBox("cboAutomaticCalendarCountryCode", {
    allowBlank: false,
    limitToList: true,
    
    onChange: cboAutomaticCalendarCountryCode_Change,
  });
  C.cboAutomaticCalendarState = widget.UI.ComboBox("cboAutomaticCalendarState", {
    allowBlank: false,
    limitToList: true,
    
    onChange: cboAutomaticCalendarState_Change,
  });

  C.lblCalendarDetails = widget.UI.Label("lblCalendarDetails", {});
  C.calCalendar = widget.UI.Calendar("calCalendar", {
    showButtons: false,    
    valueBorderOnly: true,
    
    onChange: calCalendar_Change,
    onCellDblClick: calCalendar_CellDblClick,
  });
  C.calCalendarInfo = $("#calCalendarInfo");

  //   frmAddNonWorkingDay
  C.lblNonWorkingDate = widget.UI.Label("lblNonWorkingDate", {
    tooltipText: "Optionally enter a 'To Date' to add a range of non-working dates (limited to 90 days)",
  });
  C.dateFrom = widget.UI.DateBox("dateFrom", {
    allowBlank: false,
  });
  C.dateTo = widget.UI.DateBox("dateTo", {});
  
  C.lblDescription = widget.UI.Label("lblDescription", {});
  C.txtNonWorkingDayDesc = widget.UI.TextBox("txtNonWorkingDayDesc", {
    maxLength: 50,
  });

  // Grids
  C.gridNonWorkingDays = widget.UI.Grid("gridNonWorkingDays", {
    allowMultiRowSelect: true,
    docked: true,
    stickyHeader: true,
    showRowSelectors: true,

    onAction: gridNonWorkingDays_Action,
    onAfterRowActivate: gridNonWorkingDays_AfterRowActivate,
    onBeforeCellUpdate: gridNonWorkingDays_BeforeCellUpdate,
    onInitialiseRow: gridNonWorkingDays_InitialiseRow,  
  });

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

  cmdToday = $("#cmdToday");
  cmdToday.click(function() { Form_ExecuteAction("Today"); });

  // 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;
  mMarkers = [];

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

  // Give Collections ability To lookup by code
  widget.ArrayAllowLookupById(mRecord.Countries, "CountryName");

  // 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.txtCalendarId.Text(mRecord.CalendarId);
    C.txtDescription.Text(mRecord.Description);
    
    C.chkAutomaticCalendar.Value(mRecord.AutomaticCalendar);
    C.cboAutomaticCalendarCountryCode.Text(mRecord.AutomaticCalendarCountryName);
    C.cboAutomaticCalendarState.Text(mRecord.AutomaticCalendarState);
    
    // Default calendar to today
    C.calCalendar.Value(new Date());
    
    // Set Markers
    SetMarkers();
  }

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

  // Update Controls
  calCalendar_Change();

  // Update fields
  Fields_Update();

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

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // General
  mRecord.CalendarId = C.txtCalendarId.Text();
  mRecord.Description = C.txtDescription.Text();
  
  mRecord.AutomaticCalendar = C.chkAutomaticCalendar.Value();
  mRecord.AutomaticCalendarCountryName = C.cboAutomaticCalendarCountryCode.Text();
  mRecord.AutomaticCalendarState = C.cboAutomaticCalendarState.Text();
}

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

  // Lists
  if (mRecord) {
    // General
    C.cboAutomaticCalendarCountryCode.ListFromCollection(mRecord.Countries, "CountryName");
  }

  // Controls
  if (mRecord) {
  }

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

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

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

// ===========
// Refresh Tab
// ===========
function tabDetails_Refresh() {
   // Load details
  switch (tabDetails.SelectedTabId()) {
    case "General":
      pageGeneral_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.toUpperCase()) {
    case "TODAY":
      // Reset calendar to today
      C.calCalendar.Value(new Date());
      C.calCalendar.GotoValue();
      
      // Update Controls
      calCalendar_Change();      
      break;
      
    default:
      window.alert("Unhandled action '" + actionId + "'");
  }
}

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

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

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

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

  // Controls
  chkAutomaticCalendar_Change();
  cboAutomaticCalendarCountryCode_Change();
  gridNonWorkingDays_Refresh();
}

// ===========================
// Set Markers on the Calendar
// ===========================
function SetMarkers() {
  if (!mRecord) return;
  
  // Reset
  mMarkers = [];
  
  // Build collection
  for (var i = 0; i &lt; mRecord.NonWorkingDays.length; i++) {
    var item = mRecord.NonWorkingDays[i];
    
    var o = {
      value: new Date(item.NonWorkingDate),
      tooltipText: item.Description,
      colour: mRecord.NonWorkingDayColour,
      backgroundColour: mRecord.NonWorkingDayBackgroundColour,
    }    
    mMarkers.push(o);
  }

  // Update Calendar
  C.calCalendar.MarkersSet(mMarkers);
}

// ===========
// calCalendar
// ===========
function calCalendar_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Show date information
  GetDateInfo(); 
  
  // Update Grid
  if (e) {
    for (var i = 0; i &lt; mRecord.NonWorkingDays.length; i++) {
      var item = mRecord.NonWorkingDays[i];
      
      if (widget.CompareDates(new Date(item.NonWorkingDate), C.calCalendar.Value()) == 0) {
        C.gridNonWorkingDays.ActiveDataRowListIndex(i);
        break;
      }
    }
  }
}

function calCalendar_CellDblClick(sender) {
  if (mRecord.ReadOnly) return;

  // Build a UTC date from the calendar control (as this returns an absolute date, not UTC)
  var date_utc = Date.UTC(C.calCalendar.Value().getFullYear(), C.calCalendar.Value().getMonth(), C.calCalendar.Value().getDate(), 0, 0, 0);
  NonWorkingDayAdd(new Date(date_utc));
}

function GetDateInfo() {
  // Params
  var params = {
    dateAsAt: C.calCalendar.Value(),
  }
  
  // Get Date Info
  widget.GetString("GetDateInfo", params, GetDateInfo_Done, function(errorMessage) {
    C.calCalendarInfo.html(errorMessage);
  });
}

function GetDateInfo_Done(data) {
  var html = "&lt;span&gt;" + widget.UI.HtmlEncode(data) + "&lt;/span&gt;";

  // Non-working day
  for (var i = 0; i &lt; mRecord.NonWorkingDays.length; i++) {
    var item = mRecord.NonWorkingDays[i];
    
    if (widget.CompareDates(new Date(item.NonWorkingDate), C.calCalendar.Value()) == 0) {
      if (item.Description) {
        html += "&lt;span&gt;" + item.Description + "&lt;/span&gt;";  
      }
      else {
        html += "&lt;span&gt;Non-Working Day&lt;/span&gt;";  
      }      
      break;
    }
  }

  C.calCalendarInfo.html(html);
}

// ====================
// chkAutomaticCalendar
// ====================
function chkAutomaticCalendar_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Update Controls
  C.cboAutomaticCalendarCountryCode.VisibleRow(C.chkAutomaticCalendar.Value());
  
  // Change Events
  cboAutomaticCalendarCountryCode_Change();
  
  // Update automatic non-working days
  if (e) RefreshAutomaticNonWorkingDays();
}

// ===============================
// cboAutomaticCalendarCountryCode
// ===============================
function cboAutomaticCalendarCountryCode_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Reset Countrols
  C.cboAutomaticCalendarState.VisibleRow(false);
  
  // Lookup Element Description
  var country = mRecord.Countries.GetItem(C.cboAutomaticCalendarCountryCode.Text());
  if (C.chkAutomaticCalendar.Value() &amp;&amp; country) {
    if (country.SupportsStateHolidays) {
      C.cboAutomaticCalendarState.VisibleRow(true);
      C.cboAutomaticCalendarState.ListFromCsvString(country.States);
      C.cboAutomaticCalendarState.Caption(country.TerminologyState + ":");
    }
    else {
      C.cboAutomaticCalendarState.VisibleRow(false);
    }    
  }
  
  // Refresh non-working days
  if (e) RefreshAutomaticNonWorkingDays();
}

// =========================
// cboAutomaticCalendarState
// =========================
function cboAutomaticCalendarState_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Refresh non-working days
  RefreshAutomaticNonWorkingDays();
}

// ==================================
// Refresh automatic non-working days
// ==================================
function RefreshAutomaticNonWorkingDays() {
  // Create Parameters
  Fields_Save();
  var params = JSON.parse(JSON.stringify(mRecord));
  params.Countries = null;
  
  widget.GetString("RefreshAutomaticNonWorkingDays", params, RefreshAutomaticNonWorkingDays_Done, function(errorMessage) {
    // Error
    widget.UI.MsgBoxAlert(errorMessage);
  })
}

function RefreshAutomaticNonWorkingDays_Done(data) {
  // Update non-working days
  mRecord.NonWorkingDays = JSON.parse(data);
  
  // Refresh Grid
  gridNonWorkingDays_Refresh();
}

// ==================
// gridNonWorkingDays
// ==================
function gridNonWorkingDays_Refresh() {
  // Show columns
  var showManual = false;
  if (C.chkAutomaticCalendar.Value()) {
    for (var i = 0; i &lt; mRecord.NonWorkingDays.length; i++) {
      var item = mRecord.NonWorkingDays[i];

      if (!item.Automatic) showManual = true;
    }
  }

  // Add Columns
  C.gridNonWorkingDays.ClearColumns();
  C.gridNonWorkingDays.AddColumnBoolean("ManualNonWorkingDay", { caption: "Manual", visible: showManual });
  C.gridNonWorkingDays.AddColumnDate("NonWorkingDate", { caption: "Date", allowEdit: !mRecord.ReadOnly, });
  C.gridNonWorkingDays.AddColumnString("Description", { caption: "Description", allowEdit: !mRecord.ReadOnly, });

  // Actions
  if (!mRecord.ReadOnly) {
    var actions = [];
    actions.push({ actionId: "ItemAdd", tooltipText:"Add item", icon: "Grid_Row_Add" });
    actions.push({ actionId: "SelectDelete", tooltipText:"Delete selected row(s)", icon: "Grid_Row_Delete" });
    actions.push({});
    actions.push({ actionId: "Sort", tooltipText:"Sort items into Date order (removing duplicate dates)", icon: "Sort_Ascending" });    
    if (!C.chkAutomaticCalendar.Value()) {
      actions.push({});
      actions.push({ actionId: "DefaultHolidaysAdd", tooltipText:"Add default holidays", icon: "Calendar_Add", caption: "Add Holidays" });
    }    
    C.gridNonWorkingDays.Actions().Define(actions);
  }

  // Refresh
  C.gridNonWorkingDays.VirtualDataRefresh(mRecord.NonWorkingDays);

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

function gridNonWorkingDays_InitialiseRow(e) {
  var item = mRecord.NonWorkingDays[e.row.listIndex];
  
  // Update cells
  e.row.AutoBind(item);
  
  // Manual non-working day?
  e.row.cells.ManualNonWorkingDay.value = !item.Automatic;
  
  // Read only?
  if (item.Automatic) e.row.readOnly = true;
  
  // Styling
  if (C.chkAutomaticCalendar.Value() &amp;&amp; item.Automatic) e.row.inactive = true;
}

function gridNonWorkingDays_Action(actionId) {
  switch (actionId.toUpperCase()) {
    case "ITEMADD":
      NonWorkingDayAdd();
      break;
      
    case "SELECTDELETE":
      var rowDeleted = false;
      var rows = C.gridNonWorkingDays.GetSelectedRowIndexes(true, true);
      
      for (var i = rows.length - 1; i &gt;= 0; i--) {
        var item = mRecord.NonWorkingDays[rows[i]];        
        if (!item.Automatic) {
          rowDeleted = true;
          C.gridNonWorkingDays.RemoveRowAndCollectionItem(rows[i]);
        }
      }       
      
      // If at least row has been deleted, update other information
      if (rowDeleted) {
        // Update Calendar
        SetMarkers();
        
        // Update Captions etc.
        if (C.gridNonWorkingDays.ActiveDataRowListIndex() &gt;= 0) {
          var item = mRecord.NonWorkingDays[C.gridNonWorkingDays.ActiveDataRowListIndex()];
          gridNonWorkingDays_UpdateCalendar(item);
        }  
      }          
      break;
    
    case "SORT":
      gridNonWorkingDays_Action_Sort();
      break;
    
    case "DEFAULTHOLIDAYSADD":
      DefaultHolidaysAdd();
      break;
      
    default:
      break;
  }
}

function gridNonWorkingDays_Action_Sort() {
  // Block UI
  widget.UI.Block("Sorting, please wait...");
  
  // Params
  var params = {
    nonWorkingDaysJson: JSON.stringify(mRecord.NonWorkingDays),
  }
  
  // Sort
  widget.GetString("SortNonWorkingDays", params, gridNonWorkingDays_Action_Sort_Done, function(errorMessage) {
    // Unblock UI
    widget.UI.Unblock();
    
    // Error
    widget.UI.MsgBoxAlert(errorMessage);
  });
}

function gridNonWorkingDays_Action_Sort_Done(data) {
  // Parse
  if (data) mRecord.NonWorkingDays = JSON.parse(data);
  
  // Refresh Grid and Calendar
  SetMarkers();
  gridNonWorkingDays_Refresh();
  
  // Unblock
  widget.UI.Unblock();
}

function gridNonWorkingDays_AfterRowActivate(e) {
  // Select item on the calendar  
  if (e.activatedFromClick) {
    var item = mRecord.NonWorkingDays[e.row.listIndex];
    gridNonWorkingDays_UpdateCalendar(item);
  }
}

function gridNonWorkingDays_UpdateCalendar(item) {
  if (item) {
    // Set calendar
    C.calCalendar.Value(new Date(item.NonWorkingDate));
    C.calCalendar.GotoValue();
    
    // Update Controls
    calCalendar_Change();  
  }
}

function gridNonWorkingDays_BeforeCellUpdate(e) {
  var item = mRecord.NonWorkingDays[e.row.listIndex];
  
  if (!item.Automatic) {
    switch(e.columnKey) {
      case "NonWorkingDate":
        item.NonWorkingDate = e.newValue;
        break;
      
      case "Description":
        item.Description = e.newValue;
        break;
    }
  }  
}

function DefaultHolidaysAdd() {
  // Params
  var params = {
    NonWorkingHolidaysJson: mRecord.NonWorkingDays,
  }

  // Show Widget
  widget.UI.Forms.ShowHtmlWidgetModal(mRecord.AddHolidaysHtmlWidgetId, { startupParametersJson: JSON.stringify(params) }, DefaultHolidaysAdd_Notify);
}

function DefaultHolidaysAdd_Notify(actionId, data) {
  // Handle
  switch(actionId) {
    case "HolidaysUpdated":
      // Parse
      if (data) mRecord.NonWorkingDays = JSON.parse(data);
      
      // Refresh Grid and Calendar
      SetMarkers();
      gridNonWorkingDays_Refresh();
      break;
  }
}

function NonWorkingDayAdd(defaultDate) {
  // Create Modal
  mForm_AddNonWorkingDay = widget.UI.Modal({
    title: "Calendar Non-Working Day",
    height: 300,
    width: 500,

    onAction: NonWorkingDayAdd_Action,
  });

  // Actions
  mForm_AddNonWorkingDay.Actions().Define([{ groupId: "[buttons]", actionId: "Cancel", caption: "Cancel" },
                                       { groupId: "[buttons]", actionId: "Ok", caption: "Add" }, ]);
                                       
  // Show
  mForm_AddNonWorkingDay.Show({contentSourceElement: "frmAddNonWorkingDay"});

  // Reset fields
  if (defaultDate) {
    C.dateFrom.Value(defaultDate);
  }
  else {
    C.dateFrom.Value(null);
  }
  C.dateTo.Value(null);
  C.txtNonWorkingDayDesc.Text("");

  // Focus
  C.dateFrom.Focus();                                       
}

// Handle Actions
function NonWorkingDayAdd_Action(actionId) {
  switch(actionId) {
    case "Cancel":
      mForm_AddNonWorkingDay.Close();
      break;

   case "Ok":
      NonWorkingDayAdd_Action_Ok();
      break;

    default:
      window.alert(actionId);
  }
}

function NonWorkingDayAdd_Action_Ok() {  
  // Validate
  var Ok = true;
  if (!C.dateFrom.Value()) {
    Ok = false;
    C.dateFrom.Focus();
  }
  else if (C.dateTo.Value() &amp;&amp; widget.CompareDates(C.dateFrom.Value(), C.dateTo.Value()) == 1) {
    Ok = false;
    C.dateTo.Focus();
    widget.UI.MsgBoxAlert("'From' date must be before the 'to' date.");
  }
  
  if (Ok) {
    // Block UI
    widget.UI.Block("Initialising, please wait...");
  
    // Params
    var params = {
      dateFrom: C.dateFrom.Value(),
      dateTo: C.dateTo.Value(),
      description: C.txtNonWorkingDayDesc.Text(),
      nonWorkingDaysJson: JSON.stringify(mRecord.NonWorkingDays),
    }
    
    // Add Date
    widget.GetString("AddNonWorkingDay", params, NonWorkingDayAdd_Action_Ok_Done, function(errorMessage) {
      // Unblock UI
      widget.UI.Unblock();
      
      // Error Message
      widget.UI.MsgBoxAlert(errorMessage);
    });
  }  
}

function NonWorkingDayAdd_Action_Ok_Done(data) {
  // Parse
  if (data) mRecord.NonWorkingDays = JSON.parse(data);
  
  // Refresh Grid and Calendar
  SetMarkers();
  gridNonWorkingDays_Refresh();
  
  // Close Modal
  mForm_AddNonWorkingDay.Close();
  
  // Unblock
  widget.UI.Unblock();
}

// ====================
// 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>Nt9VvOr6BEK8a8Pj3XrHyA</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Calendar</Caption>
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1600</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>1200</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>Calendar</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="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="NonWorkingDayColour" type="Text">
            <BlankTip />
            <Caption>Non-working Day Colour</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="NonWorkingDayBackgroundColour" type="Text">
            <BlankTip />
            <Caption>Non-working Day Background Colour</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="CalendarId" 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>Calendars</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.Calendars</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>