<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2024-09-19T03:45:42.0000000">
    <CreatedUserId>ADMIN</CreatedUserId>
    <CreatedUtcDate>2023-05-22T03:22:29.9730000</CreatedUtcDate>
    <UpdatedUserId>ADMIN</UpdatedUserId>
    <UpdatedUtcDate>2024-09-19T03:37:51.8570000</UpdatedUtcDate>
    <ScriptId>LE</ScriptId>
    <Description>Log Edit</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_LogEdit
Option Explicit On
Option Strict On

' #################################################################
' Log Edit form HTML Widget
'
' Copyright (C) Intersoft Systems Limited 2023
'
' Version: 1.06 (19/09/2024)
'
' Usage: System-supplied HTML Widget to handle ALL Log forms
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.00  16/06/2023  ISS      J030841   Created
'    1.01  26/07/2023  ISS      J031423   New option to move "Other" page fields to "General"
'          07/08/2023  ISS      J031727   TESTING Page parameter contained duplicate "ServiceLog" entry
'                      ISS      J031309   Now handles 'Credit Bureau Monitor' page
'                      ISS      J031737   Parameters to default Subject, Log Severity, Action Date, Owner &amp; Delegated Users added
'          22/08/2023  ISS      J031845   Object Reference error for Account Web Mail Logs
'          23/08/2023  ISS      J031867   Print action now respects permission keys
'    1.02  26/09/2023  ISS      J032039   User Logs now assume the current User if no User Id supplied
'          27/09/2023  ISS      J032115   Repeat features added to 'Other' page
'          31/10/2023  ISS      J032246   Subject correctly defaulted from Workflow Item from Workflow Type
'          08/11/2023  ISS      J032385   Workflow Item Pk is now saved to the Log
'          16/11/2023  ISS      J025936   Added "Audit" page
'    1.03  07/03/2024  ISS      J033044   User Logs no longer checking invalid permission key
'          19/03/2024  ISS      J033125   Updated 'Extended' page to size correctly for Decision Outcomes
'          28/03/2024  ISS      J032988   Prompts to print and update Print Status
'          04/04/2024  ISS      J032873   Log date can now be left blank and date will default when saved
'    1.04  07/05/2024  ISS      J032452   Changed Document Manager Validation to use IsAvailableResolved instead of IsAvailable
'          22/05/2024  ISS      J033519   permanently moved the Log Severity Field to the General Page
'          23/05/2024  ISS      J033556   Redirect Banking Interface Summary to ServiceLog page
'          23/05/2024  ISS      J033559   Print button added to Service Log page
'    1.05  04/06/2024  ISS      J033603   Added "RE:" Subject prefix when replying to an existing Log
'          10/07/2024  ISS      J033624   Display original Log notes when replying to an existing Log
'          17/07/2024  ISS      J033877   Added "Summary" tab to display entire thread when replying to an existing Log
'          09/08/2024  ISS      J034062   Make notification actionId case-insensitive
'          22/08/2024  ISS      J033208   Default Log Owner and Delegated User Combo Boxes to active users only
'    1.06  19/09/2024  ISS      J034325   Added additional Permission checks via 'I_finLog.CanSave' function
' #################################################################

' Constants
Private FORM_KEY As String = "" ' Dynamic

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

' Standard Parameters
Private mAccountAppApplicantPk As Integer
Private mAccountAppCollateralItemPk As Integer
Private mObjectNameFriendly As String
Private mObjectType As String
Private mLogObjectType As isefinLogObjectType 
Private mLogType As isefinLogType
Private mPage As String
Private mPk As Integer
Private mRecordId As String
Private mReadOnly As Boolean
Private mReplyToLogPk As Integer
Private mWorkflowId As String
Private mWorkflowItemPk As Integer

Private mDefaultLogSeverityId As String
Private mDefaultSubject As String
Private mDefaultOwnerUserId As String
Private mDefaultDelegatedUserId As String
Private mActionImmediately As Boolean

' Configuration Parameters
Private mPrioritiseOwnerAndDelegated 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 Configuration Parameters
  With mStartupParameters
    mPrioritiseOwnerAndDelegated = .GetBoolean("PrioritiseOwnerAndDelegated", mPrioritiseOwnerAndDelegated)
  End With
  
  ' Get Standard Parameters
  With mCombinedParameters
    mPk = .GetInteger("Id") ' Named Id for compatibility with desktop Log forms
    mObjectType = .GetString("ObjectType")
    If Not [Enum].TryParse(Of isefinLogObjectType)(mObjectType, mLogObjectType) Then
      mLogObjectType =  isefinLogObjectType.Client
    End If
    If Not [Enum].TryParse(Of isefinLogType)(.GetString("LogType"), mLogType) Then
      mLogType = isefinLogType.NormalUser
    End If
    mPage = .GetString("Page")
    Select Case mLogObjectType 
      Case isefinLogObjectType.Account 
        mObjectNameFriendly = "Account"
        mRecordId = .GetString("AccountId")
        
      Case isefinLogObjectType.AccountApp
        mObjectNameFriendly = "Account Application"
        mRecordId = .GetString("AccountAppId")
        mAccountAppApplicantPk = .GetInteger("AccountAppApplicantPk")
        mAccountAppCollateralItemPk = .GetInteger("AccountAppCollateralItemPk")

      Case isefinLogObjectType.Client 
        mObjectNameFriendly = "Client"
        mRecordId = .GetString("ClientId")

      Case isefinLogObjectType.SecurityStmt  
        mObjectNameFriendly = "Security Statement"
        mRecordId = .GetString("SecurityStmtId")

      Case isefinLogObjectType.SecurityStmtItem
        mObjectNameFriendly = "Security Item"
        mRecordId = CStr(.GetInteger("SecurityStmtItemPk"))

      Case isefinLogObjectType.User 
        mObjectNameFriendly = "User"
        mRecordId = .GetString("UserId")
        
        ' Assume Current User?
        If Len(mRecordId) = 0 Then
          mRecordId = finBL.CurrentUser.UserId
        End If
    End Select
    mReadOnly = .GetBoolean("ReadOnly")
    mWorkflowId = .GetString("WorkflowId")
    mWorkflowItemPk = .GetInteger("WorkflowItemPk")
    
    ' NOTE: If this is not the top-level Log in a thread, GetLog will sort this out
    mReplyToLogPk = .GetInteger("ReplyToLogPk")
    
    mDefaultLogSeverityId = .GetString("DefaultLogSeverityId")
    mDefaultSubject = .GetString("DefaultSubject")
    mDefaultOwnerUserId = .GetString("DefaultOwnerUserId")
    mDefaultDelegatedUserId = .GetString("DefaultDelegatedUserId")
    mActionImmediately = .GetBoolean("ActionImmediately")
  End With
  
  ' Form Key is dynamic
  FORM_KEY = mObjectType &amp; "Log"

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

  ' Override Page Id
  If Main Then
    Select Case UCase(mPage)
      Case "BANKING INTERFACE SUMMARY"
        mPage = "ServiceLog"        
      Case "CREDIT BUREAU MONITOR"
        mPage = "ServiceLog"
    End Select
  End If
  
  ' Handle Events
  If Main Then
    Select Case eventId
      Case ""
        ' Main event, i.e., return initial HTML content (excluding html and body tags)
        returnValue = ScriptInfo.TemplateText

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

     Case "GetInitialisationInfo"
        ' Get Initialisation Information required for this wizard
        Main = GetInitialisationInfo(returnValue)
        
      Case "Delete"
        ' Delete Log
        Main = Delete(returnValue)
        
      Case "GetExtendedData"
        ' Get Extended Data
        Main = GetExtendedData(returnValue)

      Case "GetServiceLogSummary"
        ' Get Service Log Summary
        Main = GetServiceLogSummary(returnValue)

      Case "Publish"
        ' Publish Log
        Main = Publish(returnValue)

      Case "SetLogPrinted"
        ' Set the Log as having been Printed
        Main = SetLogPrinted(returnValue)

      Case "Unpublish"
        ' Unpublish Log
        Main = Unpublish(returnValue)

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

End Function

''' &lt;summary&gt;
'''  Load Log.
''' &lt;/summary&gt;
Private Function GetLog(ByRef log As I_finLog,
                        ByRef replyToLogNotes As String) As Boolean

  Dim LogParent As I_finLog
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Validate

  ' Create and Load Log
  If Success Then
    ' Create and Load Log
    If mPk = 0 Then
      ' New Log
      log = finBL.LogUtilities.CreateLog(mLogObjectType, mRecordId)
      With log
        .LogType = mLogType
      End With
      
      ' Sub-objects?
      Select Case mLogObjectType
        Case isefinLogObjectType.AccountApp 
          With DirectCast(log, finAccountAppLog)
            .AccountAppApplicantPk = mAccountAppApplicantPk
            .AccountAppCollateralItemPk = mAccountAppCollateralItemPk
          End With
      End Select
      
      ' Replying?
      If mReplyToLogPk &lt;&gt; 0 Then
        ' Must specify AccountId, ClientId etc
        If finBL.LogUtilities.LoadLog(mLogObjectType, mReplyToLogPk, LogParent) Then
          ' Allow Notes of Log being replied to to be viewed for reference
          replyToLogNotes = LogParent.Notes
        
          log.RecordId = LogParent.RecordId
          mRecordId = log.RecordId
          
          ' Update Subject
          If StrComp("RE:", Microsoft.VisualBasic.Left(LogParent.Subject, 3), CompareMethod.Text) = 0 Then
            log.Subject = LogParent.Subject
          Else
            log.Subject = "RE: " &amp; LogParent.Subject
          End If

          ' If this Log has a parent, that is the REAL Parent for replying
          If LogParent.ParentLogPk &lt;&gt; 0 Then
            mReplyToLogPk = LogParent.ParentLogPk
          End If
        Else
          Success = False
        End If
        
        Log.ParentLogPk = mReplyToLogPk        
      End If
      
      ' Workflow (force from Startup Parameters to prevent clashes with information coming from the UI) - note this is only happening for new Logs
      Log.WorkflowId = mStartupParameters.GetString("WorkflowId")
      Log.WorkflowItemPk = mStartupParameters.GetInteger("WorkflowItemPk")
    Else
      ' Existing Log
      If finBL.LogUtilities.LoadLog(mLogObjectType, mPk, log) Then
        mRecordId = log.RecordId
      Else
        Success = False
      End If
    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 Account As finAccount
  Dim AccountAppLog As finAccountAppLog
  Dim AccountLog As finAccountLog
  Dim CanSave As Boolean
  Dim ChildLog As I_finLog
  Dim ChildLogs As List(Of I_finLog)
  Dim ClientLog As finClientLog
  Dim Document As finDocumentRO
  Dim Element As finElementRO
  Dim ExcludeExtendedDataPage As Boolean
  Dim FormInitialisationInfo As FormInitialisationInfo
  Dim kvl As ISKeyValueList
  Dim List As ISList
  Dim Log As I_finLog
  Dim LogSeverity As finLogSeverityRO 
  Dim Message As String
  Dim ReadUtcDate As Date
  Dim ReplyToLogNotes As String
  Dim SecurityStmtItemLog As finSecurityStmtItemLog
  Dim ServiceLog As finwsServiceLog
  Dim Success As Boolean
  Dim ViewAuditPagePermissionKey As String
  Dim Workflow As finWorkflow
  Dim WorkflowItem As finWorkflowItem

  ' Assume Success
  Success = True

  ' Get Log
  If Success Then
    If GetLog(Log, ReplyToLogNotes) Then
      ' Get specific Logs (since they may contain properties not in I_finLog)
      Select Case mLogObjectType
        Case isefinLogObjectType.Account 
          AccountLog = DirectCast(Log, finAccountLog)

        Case isefinLogObjectType.AccountApp 
          AccountAppLog = DirectCast(Log, finAccountAppLog)

        Case isefinLogObjectType.Client 
          ClientLog = DirectCast(Log, finClientLog)
          
        Case isefinLogObjectType.SecurityStmtItem
          SecurityStmtItemLog = DirectCast(Log, finSecurityStmtItemLog)
      End Select
      
      ' Get Document (used below)
      Document = Log.Document
    Else
      Success = False
    End If
  End If

  ' Can Log be saved?
  If Success Then
    CanSave = Log.CanSave(True, Message)
    
    If Log.IsNew AndAlso (Not CanSave) Then
      Success = False
      finBL.Error.ErrorBegin(Message)
    End If
  End If
  
  ' Get Workflow &amp; Workflow Item
  If Success AndAlso Len(mWorkflowId) &lt;&gt; 0 Then
    Workflow = finBL.CreateWorkflow()
    
    If Workflow.Load(mWorkflowId) Then
      If mWorkflowItemPk &lt;&gt; 0 Then
        WorkflowItem = Workflow.GetItemByPk(mWorkflowItemPk)
        
        If WorkflowItem Is Nothing Then
          Success = False
          finBL.Error.ErrorBegin("Invalid Workflow Item Pk.")
        End If
      End If
    Else 
      Success = False
    End If
  End If
  
  ' Object-Type-specific
  If Success Then
    Select Case mLogObjectType
      Case isefinLogObjectType.SecurityStmtItem
        ViewAuditPagePermissionKey = "SecurityItem.Logs.ViewAuditPage"
        
      Case Else
      ViewAuditPagePermissionKey = mLogObjectType.ToString() &amp; ".Logs.ViewAuditPage"
    End Select
  End If
  
  ' Get Initialisation Info
  ' NOTE: TZ dates are treated like Database date since all we are doing is saying they are in UTC format
  If Success Then
    FormInitialisationInfo = New FormInitialisationInfo()
    With FormInitialisationInfo
      ' Form
      .PageId = mPage
      If finBL.Database.IsReadOnly OrElse mReadOnly OrElse (Not CanSave) Then
        .ReadOnly = True
      Else
        .ReadOnly = False
      End If

      ' Record
      .LogObjectType = mLogObjectType
      .LogType = Log.LogType
      .ObjectNameFriendly = mObjectNameFriendly
      .Pk = Log.Pk
      .ReplyToLogNotes = ReplyToLogNotes
      .ReplyToLogPk = mReplyToLogPk
      .Timestamp = Log.Timestamp
      
      ' Icon
      If Log.LogSeverityPk &lt;&gt; 0 Then
        LogSeverity = finBL.LogSeverities(Log.LogSeverityId)
        If Log.ActionUtcDate &lt;&gt; Nothing AndAlso Log.ActionCompleteUtcDate = Nothing Then
          If Len(LogSeverity.OpenColourBackground) &lt;&gt; 0 Then
            .Icon = "Colour[" &amp; LogSeverity.OpenColourBackground &amp; "]"      
          End If
        Else
          If Len(LogSeverity.CompleteColourBackground) &lt;&gt; 0 Then
            .Icon = "Colour[" &amp; LogSeverity.CompleteColourBackground &amp; "]"            
          End If
        End If
      End If
      
      ' Bookmarking
      .DatabaseReadOnly = finBL.Database.IsReadOnly
      .RecordType = mLogObjectType.ToString() &amp; "Log"
      .Bookmarked = Not Log.IsNew AndAlso finBL.TaskManagerFunctions.UserBookmarkedRecordsListExists(.RecordType, Log.pk)            
      
      ' State
      .HasDocument = Log.HasDocument
      .IsIncomplete = Log.IsIncomplete
      .SupportsDocumentPrint = finBL.DocumentManager.IsAvailableResolved ' NOTE: Since 'Print' is really 'Download', checking Log.Document.SupportsDocumentPrint is not really relevant
      .SupportsDocumentSendEmail = Document IsNot Nothing AndAlso Document.SupportsSendEmail
      Select Case mLogObjectType 
        Case isefinLogObjectType.SecurityStmt, isefinLogObjectType.SecurityStmtItem
          .SupportsReplyViaSms = False
        Case Else
          .SupportsReplyViaSms = finBL.Settings.SmsUseNewInterface 'AndAlso log.ExtendedType = isefinLogExtendedType.Sms          
      End Select

      ' Page Permissions (defined here since they are used below)
      ' NOTE: Not always based on permissions, may be based on Log Type etc
      .AllowPageGeneral = True
      .AllowPageServiceLog = Log.ServiceLog IsNot Nothing
      .AllowPageExtendedData = True
      .AllowPageWebMail = Log.LogType.ToString().StartsWith("WebMail")
      .AllowPageDocument = True
      .AllowPageFee = True
      .AllowPageFeeNew = True
      .AllowPageOther = True
      If mLogObjectType = isefinLogObjectType.Account AndAlso finBL.Settings.AddOns.ExternalParty Then
        If AccountLog.ExternalPartyPk &lt;&gt; 0 Then
          .AllowPageExternalParty = True
        ElseIf Document Is Nothing Then
          .AllowPageExternalParty = finBL.Settings.AccountLogLinkExternalParty
        ElseIf Document.AllowExternalParty &lt;&gt; isefinDocumentAllowExternalParty.None Then
          .AllowPageExternalParty = True
        Else
          .AllowPageExternalParty = False
        End If
      Else
        .AllowPageExternalParty = False
      End If
      .AllowPageAudit = Not Log.IsNew AndAlso (finBL.CurrentUser.IsAdministrator OrElse finBL.CurrentUser.Permissions.Allow(ViewAuditPagePermissionKey))
      If .AllowPageAudit Then
        If mLogObjectType = isefinLogObjectType.User Then
          .AllowViewExtended = finBL.CurrentUser.IsAdministrator AndAlso Len(Log.ExtendedData) &lt;&gt; 0
        Else
          .AllowViewExtended = (finBL.CurrentUser.IsAdministrator OrElse finBL.CurrentUser.Permissions.Allow(mLogObjectType.ToString() &amp; ".Logs.ViewExtendedData")) AndAlso Len(Log.ExtendedData) &lt;&gt; 0
        End If
        .AllowViewParameters = (Log.Parameters IsNot Nothing AndAlso Log.Parameters.Count &lt;&gt; 0)
        .AllowViewHtml = Len(Log.DocumentHtml) &lt;&gt; 0
        .AllowViewAccountData = AccountLog IsNot Nothing AndAlso (finBL.CurrentUser.IsAdministrator OrElse finBL.CurrentUser.Permissions.Allow(mLogObjectType.ToString() &amp; ".Logs.ViewExtendedData")) AndAlso Len(AccountLog.AccountData) &lt;&gt; 0
        .AllowViewUserData = Log.UserData.Count &lt;&gt; 0
      End If
      .AllowPageSummary = True

      ' General
      .RecordId = Log.RecordId
      .RecordDescription = Log.GetRecordDescription()
      Select Case mLogObjectType 
        Case isefinLogObjectType.AccountApp 
          ' Account Application
          .AccountAppApplicantPk = AccountAppLog.AccountAppApplicantPk 
          .AccountAppCollateralItemPk = AccountAppLog.AccountAppCollateralItemPk 
          If Not AccountAppLog.GetApplicantAndCollateralItemDescriptions(.AccountAppApplicantDescription, .AccountAppCollateralItemDescription) Then
            ' Ignore errors
          End If
          
        Case isefinLogObjectType.SecurityStmtItem 
          ' Security Statement Item
          ' NOTE: RecordId was the Security Item Pk but works better as the Security Statement Id
          If Not SecurityStmtItemLog.GetSecurityStmtId(.RecordId, .RecordDescription, .SecurityStmtItemDescription) Then
            ' Ignore errors
          End If
          .SecurityStmtItemPk = SecurityStmtItemLog.SecurityStmtItemPk
      End Select
      If .AllowPageGeneral Then
        .LogTzDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(Log.LogTzDate)
        If Len(.LogSeverityId) = 0 Then .LogSeverityId = Log.LogSeverityId        
        .LogTimeZoneId = Log.LogTimeZoneId
        .Subject = Log.Subject 
        .Notes = Log.Notes
        
        .ActionTzDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(Log.ActionTzDate)
        .ActionTimeZoneId = Log.ActionTimeZoneId
        .ActionCompleteTzDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(Log.ActionCompleteTzDate)
        
        .LogOutcome = Log.LogOutcome
        
        ' Workflow Item
        If WorkflowItem IsNot Nothing Then
          WorkflowItem.GetLogSubjectParts(.Subject, .SubjectInformationListId)
          
          ' General
          .LogSeverityId = WorkflowItem.LogSeverityId          
          .Notes = WorkflowItem.LogNotes
          
          ' Action
          Select Case UCase(WorkflowItem.LogActionPeriod)
            Case ""
              ' Ignore
              
            Case "IMMEDIATE"
              .ActionTimeZoneId = finBL.SettingsUser.TimeZoneIdResolved              
              .ActionTzDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateTimeFromDatabaseDateTime(finBL.TimeZoneFunctions.GetCurrentTimeZoneDateTime(finBL.SettingsUser.TimeZoneIdResolved))
            Case Else
              .ActionTimeZoneId = finBL.SettingsUser.TimeZoneIdResolved  
              .ActionTzDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateTimeFromDatabaseDateTime(finBL.Utilities.DateCycleGetTermEndDate(WorkflowItem.LogActionPeriod, finBL.TimeZoneFunctions.GetCurrentTimeZoneDate(finBL.SettingsUser.TimeZoneIdResolved)))
          End Select
                    
          ' Deletegate to
          Select Case WorkflowItem.LogDelegateAction
            Case isefinWorkflowItemLogDelegateAction.Manager
              Select Case Workflow.WorkflowType.TargetObjectType
                Case isefinWorkflowTargetObjectType.Account: .DelegatedToUserId = Workflow.Account.AccountManagerUserId
                Case isefinWorkflowTargetObjectType.AccountApp: .DelegatedToUserId = Workflow.AccountApp.AccountManagerUserId
                Case isefinWorkflowTargetObjectType.Client: .DelegatedToUserId = Workflow.Client.ClientManagerUserId
              End Select
              
            Case isefinWorkflowItemLogDelegateAction.Role
              .DelegatedToRoleId = WorkflowItem.LogDelegateToRoleId    
              
            Case isefinWorkflowItemLogDelegateAction.User 
              .DelegatedToUserId = WorkflowItem.LogDelegateToUserId   
          End Select
                         
          ' Other
          .AllowPageFee = WorkflowItem.ShowLogFeePage
          .AllowPageFeeNew = .AllowPageFee
          
          ' Also update Log
          Log.WorkflowId = mWorkflowId
          Log.WorkflowItemPk = mWorkflowItemPk
        End If
        
        ' Default Information Lists for Workflows
        If Len(.SubjectInformationListId) = 0 AndAlso Workflow IsNot Nothing Then
          .SubjectInformationListId = "WorkflowLogSubjects"
          
          If Len(.Subject) = 0 Then
            .Subject = finBL.InformationLists(.SubjectInformationListId).DefaultValue
          End If          
        End If
        
        ' Defaults for new Logs
        If Log.IsNew Then        
          ' Log Severity
          If Len(mDefaultLogSeverityId) &lt;&gt; 0 AndAlso finBL.LogSeverities.Exists(mDefaultLogSeverityId) Then
            .LogSeverityId = mDefaultLogSeverityId
          End If          
          
          ' Subject
          If Len(finBL.Runtime.Validation.ValidateString(mDefaultSubject, 50)) &lt;&gt; 0 Then
            .Subject = finBL.Runtime.Validation.ValidateString(mDefaultSubject, 50)
          End If          
          
          ' Action Immediately?
          If mActionImmediately Then
            .ActionTimeZoneId = finBL.SettingsUser.TimeZoneIdResolved              
            .ActionTzDate = finBL.HtmlWidgetUtilities.GetJsonUtcDateTimeFromDatabaseDateTime(finBL.TimeZoneFunctions.GetCurrentTimeZoneDateTime(finBL.SettingsUser.TimeZoneIdResolved))
          End If
        End If
      End If

      ' Service Log
      If .AllowPageServiceLog Then
        ServiceLog = finBL.CreateWsServiceLog(Log.ServiceLog)
        .ServiceLogPageTitle = ServiceLog.ExtendedPageCaption
        .ServiceLogSummaryHtml = ServiceLog.ExtendedHtml
        
        ' Extended Data page is not required if this is an SMS Message Service Log
        If Log.ServiceLog.IsSmsMessaging() AndAlso StrComp(Log.ServiceLog.ServiceType, iseServiceLogServiceType.Messaging.ToString(), CompareMethod.Text) = 0 Then
          ExcludeExtendedDataPage = True
        End If
      End If
      
      ' Extended Data
      If .AllowPageExtendedData AndAlso Not ExcludeExtendedDataPage Then
        If Len(Log.ExtendedData) &lt;&gt; 0 Then
          .ExtendedDataSummaryHtml = finBL.SummaryPageFunctions.LogExtendedDataSummary(False, Log, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY), .ExtendedDataPageTitle, .ExtendedDataSummaryHtml2)
        End If
      End If
      
      ' Web Mail
      If .AllowPageWebMail AndAlso ClientLog IsNot Nothing Then
        ' Web Mail
        ' NOTE: Date Read is in the Log Date Time Zone
        .WebMailStatus = ClientLog.WebMailStatus(ReadUtcDate)
        .WebMailReadTzDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(finBL.TimeZoneFunctions.ConvertUtcToTimeZoneDateTime(ReadUtcDate, log.LogTimeZoneId))
        
        If Log.ExtendedType = isefinLogExtendedType.ClientWebMail Then
          kvl = Log.GetExtendedDataAsKeyValueList()
          ' Related Account Application
          .WebMailRelatedAccountAppId = kvl.GetString("AccountAppId")
          If Len(.WebMailRelatedAccountAppId) &lt;&gt; 0 Then .WebMailRelatedAccountAppName = finBL.AccountAppFunctions.GetRecordDescription(.WebMailRelatedAccountAppId)

          ' Related Account
          .WebMailRelatedAccountId = kvl.GetString("AccountId")
          If Len(.WebMailRelatedAccountId) &lt;&gt; 0 Then .WebMailRelatedAccountName = finBL.AccountFunctions.GetRecordDescription(.WebMailRelatedAccountId)
        End If
      End If
      
      ' Document
      If .AllowPageDocument Then
        .DocumentFileName = Log.DocumentFileName
        .DocumentBookmark = Log.DocumentBookmark
        
        .DocumentId = Log.DocumentId
        If Document IsNot Nothing Then .DocumentDescription = Document.Description
        
        .PublishedTzDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(Log.PublishedTzDate)
        .PublishOnTzDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(Log.PublishOnTzDate)
        .PublishOnTimeZoneId = Log.PublishOnTimeZoneId 
        .DocumentSendEmailText = Log.DocumentSendEmailText
        .PublishResult = Log.PublishResult 
        .PublishStatus = Log.PublishStatus 
        .PublishStatusText = Log.PublishStatusText
        .PublishFailDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(Log.PublishFailDate)
      
        .PrintStatus = Log.PrintStatus 
        .PrintStatusText = Log.PrintStatusText
        .PrintedTzDate = finBL.HtmlWidgetUtilities.GetNullableJsonUtcDateTimeFromDatabaseDateTime(Log.PrintedTzDate)
      End If
    
      ' Fee &amp; Account Details
      If .AllowPageFee AndAlso mLogObjectType = isefinLogObjectType.Account Then
        If AccountLog.HasAccountData Then
          ' Load Account?
          If Account Is Nothing Then
            Account = finBL.CreateAccount()
            Account.LoadPk(AccountLog.AccountPk)
          End If
          
          .AccountDetailsSummaryHtml = finBL.SummaryPageFunctions.AccountLogAccountDetailsSummary(False, Account, AccountLog, finBL.HtmlWidgetUtilities.CreateScriptContextData(ScriptInfo, FORM_KEY))
        End If
        
        .Fee = AccountLog.Fee
        .FeeAccountTransactionPk = AccountLog.FeeAccountTransactionPk
        If AccountLog.Document IsNot Nothing Then .DocumentFeeElementPk = AccountLog.Document.FeeElementPk
        .HasFee = AccountLog.HasFee
        .HasAccountData = AccountLog.HasAccountData
      End If
      
      ' Charge Fee
      If .AllowPageFeeNew AndAlso mLogObjectType = isefinLogObjectType.Account Then
        .ChargeFee = AccountLog.ChargeFee 
        .FeeElementId = AccountLog.FeeElementId
        .FeeReference = AccountLog.FeeReference
        .FeeNotes = AccountLog.FeeNotes
      End If      
      
      ' Other
      If .AllowPageOther Then
        .OwnerUserId = Log.OwnerUserId
        If Len(.DelegatedToUserId) = 0 Then .DelegatedToUserId = Log.DelegatedToUserId
        If Len(.DelegatedToRoleId) = 0 Then .DelegatedToRoleId = Log.DelegatedToRoleId 
          
        ' Repeat
        .CanRepeat = Log.CanRepeat()
        .RepeatUse = Log.RepeatUse
        .RepeatCycle = Log.RepeatCycle
        .RepeatBasis = Log.RepeatBasisText
          
        ' Defaults for new Logs
        If Log.IsNew Then
          ' Owner
          If Len(mDefaultOwnerUserId) &lt;&gt; 0 AndAlso finBL.Users.Exists(mDefaultOwnerUserId) Then
            .OwnerUserId = mDefaultOwnerUserId
          End If
           
          ' Delegated
          If Len(mDefaultDelegatedUserId) &lt;&gt; 0 AndAlso finBL.Users.Exists(mDefaultDelegatedUserId) Then
            .DelegatedToUserId = mDefaultDelegatedUserId
          End If  
        End If        
      End If

      ' External Party
      If .AllowPageExternalParty Then
        .ExternalPartyId = AccountLog.ExternalPartyId
      End If
      
      ' Audit
      If .AllowPageAudit Then
        .ParentLogPk = Log.ParentLogPk
        .SourceText = finBL.Enums.isefinLogSource_ToString(Log.Source)
        If Log.IsExternallyGenerated Then .SourceText &amp;= " (External)"
          
        .ServiceLogPk = Log.ServiceLogPk 
        If Log.ServiceLog IsNot Nothing Then .ServiceLogDescription = Log.ServiceLog.ServiceLogDescription()
        
        If AccountLog IsNot Nothing Then
          .AccountHistoryPk = AccountLog.AccountHistoryPk
        End If
        
        .WorkflowId = Log.WorkflowId
        
        .CreatedDetails = finBL.Utilities.GetUserAndDateHtmlIncludingTimeZone("Created", Log.CreatedUserPk, Log.CreatedUtcDate) &amp; "&lt;br/&gt;"
        .CreatedDetails &amp;= finBL.Utilities.GetUserAndDateHtmlIncludingTimeZone("Updated", Log.UpdatedUserPk, Log.UpdatedUtcDate)
        
        If Log.IsDocumentLog Then
          Select Case .PublishStatus
            Case isefinLogPublishStatus.Failed, isefinLogPublishStatus.Published
              .PublishDetails = finBL.Utilities.GetUserAndDateHtmlIncludingTimeZone("Published", Log.PublishUserPk, Log.PublishedUtcDate)
              
            Case isefinLogPublishStatus.NotIssued
              If Log.PublishUserPk = 0 Then
                .PublishDetails = "Not Issued."
              Else
                .PublishDetails = finBL.Utilities.GetUserAndDateHtmlIncludingTimeZone("Not Issued", Log.PublishUserPk, Log.PublishedUtcDate)
              End If
              
            Case Else
              .PublishDetails = "Not yet published."
          End Select
        End If
        
        Select Case .PrintStatus
          Case isefinLogPrintStatus.Printed
            .PublishDetails = finBL.Utilities.GetUserAndDateHtmlIncludingTimeZone("Printed", Log.PrintedUserPk, Log.PrintedUtcDate)
  
          Case isefinLogPrintStatus.ToPrint
            .PrintedDetails = "Not yet printed."
        End Select        
      End If
      
      ' Summary
      If .AllowPageSummary Then
        If mReplyToLogPk &lt;&gt; 0 Then
          ' Ensure whole conversation thread is available when replying
          .SummaryHtml = GetLogSummary(Log)
        Else
          ' Nothing to show
          .AllowPageSummary = False
        End If
      End If
      
      ' Permissions
      .CanDelete = Not finBL.Database.IsReadOnly AndAlso Log.CanDelete()
      If Log.IsNew Then
        .CanPrintLogDetails = False
      Else
        Select Case mLogObjectType
          Case isefinLogObjectType.Account
            .CanPrintLogDetails = finBL.CurrentUser.Permissions.Allow("Report.Account.AccountLogDetails")
  
          Case isefinLogObjectType.AccountApp
            .CanPrintLogDetails = finBL.CurrentUser.Permissions.Allow("Report.Account Application.AccountAppLogDetails")
  
          Case isefinLogObjectType.Client
            .CanPrintLogDetails = finBL.CurrentUser.Permissions.Allow("Report.Client.ClientLogDetails")
  
          Case isefinLogObjectType.SecurityStmt 
            .CanPrintLogDetails = finBL.CurrentUser.Permissions.Allow("Report.Security Statement.SecurityStmtLogDetails")
            
          Case isefinLogObjectType.SecurityStmtItem
            .CanPrintLogDetails = finBL.CurrentUser.Permissions.Allow("Report.Security Statement.SecurityStmtItemLogDetails")
          
          Case isefinLogObjectType.User
            .CanPrintLogDetails = finBL.CurrentUser.Permissions.Allow("Report.User Security.UserLogDetails")
            
          Case Else
            .CanPrintLogDetails = False
        End Select
      End If
      .CanSave = Not finBL.Database.IsReadOnly AndAlso Log.CanSave(True)

      .CanPublish = Not finBL.Database.IsReadOnly AndAlso finBL.DocumentManager.IsAvailableResolved AndAlso Log.IsDocumentLog AndAlso (Log.PublishStatus = isefinLogPublishStatus.Open OrElse Log.PublishStatus = isefinLogPublishStatus.ToSend) AndAlso Log.Document.SupportsUnattendedPublish
      .CanPrint = Len(Log.DocumentFileName) &lt;&gt; 0 AndAlso .SupportsDocumentPrint
      .CanUnpublish = Not finBL.Database.IsReadOnly AndAlso Log.IsDocumentLog AndAlso Log.PublishedUtcDate &lt;&gt; Nothing AndAlso finBL.CurrentUser.Permissions.Allow(mLogObjectType.ToString() &amp; ".Logs.Unpublish")

      .CanUpdateOwnerUser = Log.CanUpdateOwnerUser()
      .CanUpdateDelegatedToUser = Log.CanUpdateDelegatedToUser()
      .CanUpdateDelegatedToRole = Log.CanUpdateDelegatedToRole()
      
      .CanUpdateNotes = Log.CanUpdateNotes

      If mLogObjectType = isefinLogObjectType.Account Then
        .CanUpdateFee = AccountLog.CanUpdateFee()
        
        ' Can Charge a Fee?
        If AccountLog.IsNew AndAlso AccountLog.CanUpdateFee() Then
          ' Load Account?
          If Account Is Nothing Then
            Account = finBL.CreateAccount()
            Account.LoadPk(AccountLog.AccountPk)
          End If
          
          If Account.Status = isefinAccountStatus.Open Then
            .CanChargeFee = True
            'TODO: This looks incorrect since it isn't assigned to anything!
            '.GetFeeResolved()
          End If
        End If
        .CanViewFeeTransaction = finBL.CurrentUser.Permissions.Allow("Account.Form.Page.Transactions")
      End If

      ' Lists
      Select Case mLogObjectType
        Case isefinLogObjectType.Account 
          ' Account
          .LogOutcomesInformationListId = "AccountLogOutcomes"
          .PublishResultInformationListId = "AccountLogPublishResult"
          .PublishResultFailedInformationListId = "AccountLogFailReasons"
          .PublishResultNotIssuedInformationListId = "AccountLogNotIssuedReason"
          If Len(.SubjectInformationListId) = 0 Then
            .SubjectInformationListId = finBL.AccountFunctions.GetSubjectInformationListIdFromAccountLog(DirectCast(Log, finAccountLog))
          End If          
          
        Case isefinLogObjectType.AccountApp
          ' Account Application
          ' NOTE: Uses many Account lists since there are often no separate list for Account Applications
          .LogOutcomesInformationListId = "AccountLogOutcomes"
          .PublishResultInformationListId = "AccountLogPublishResult"
          .PublishResultFailedInformationListId = "AccountLogFailReasons"
          .PublishResultNotIssuedInformationListId = "AccountLogNotIssuedReason"
          If Len(.SubjectInformationListId) = 0 Then
            .SubjectInformationListId = finBL.AccountAppFunctions.GetSubjectInformationListIdFromAccountAppLog(DirectCast(Log, finAccountAppLog))
          End If

        Case isefinLogObjectType.Client 
          ' Client
          .LogOutcomesInformationListId = "ClientLogOutcomes"
          .PublishResultInformationListId = "ClientLogPublishResult"
          .PublishResultFailedInformationListId = "ClientLogFailReasons"
          .PublishResultNotIssuedInformationListId = "ClientLogNotIssuedReason"
          If Len(.SubjectInformationListId) = 0 Then
            .SubjectInformationListId = finBL.ClientFunctions.GetClientLogSubjectInformationListId(DirectCast(Log, finClientLog).ClientPk, Log.LogType, Log.Source)
          End If          

        Case isefinLogObjectType.SecurityStmt
          ' Security Statement
          .LogOutcomesInformationListId = "SecStmtLogOutcomes"
          If Len(.SubjectInformationListId) = 0 Then
            .SubjectInformationListId = finBL.SecurityStmtFunctions.GetSecurityStmtLogSubjectInformationListId(DirectCast(Log, finSecurityStmtLog).SecurityStmtPk, Log.LogType, Log.Source)
          End If          

        Case isefinLogObjectType.SecurityStmtItem
          ' Security Statement Item
          .LogOutcomesInformationListId = "SecItemLogOutcomes"
          If Len(.SubjectInformationListId) = 0 Then
            .SubjectInformationListId = finBL.SecurityStmtFunctions.GetSecurityStmtItemLogSubjectInformationListId(DirectCast(Log, finSecurityStmtItemLog).SecurityStmtItemPk, Log.LogType, Log.Source)
          End If          

        Case isefinLogObjectType.User
          ' User
          .LogOutcomesInformationListId = ""
          .PublishResultInformationListId = "UserLogPublishResult"
          .PublishResultFailedInformationListId = "UserLogFailReasons"
          .PublishResultNotIssuedInformationListId = "UserLogNotIssuedReason"
          If Len(.SubjectInformationListId) = 0 Then
            .SubjectInformationListId = finBL.UserFunctions.GetUserLogSubjectInformationListId(DirectCast(Log, finUserLog).UserPk, Log.LogType, Log.Source)
          End If          
      End Select
      
      List = New ISList()
      Select Case Log.PublishStatus
        Case isefinLogPublishStatus.Failed, isefinLogPublishStatus.Published
          List.Add(finBL.Enums.isefinLogPublishStatus_ToString(isefinLogPublishStatus.Failed))
          List.Add(finBL.Enums.isefinLogPublishStatus_ToString(isefinLogPublishStatus.Published))

        Case isefinLogPublishStatus.NotIssued, isefinLogPublishStatus.Open, isefinLogPublishStatus.ToSend
          List.Add(finBL.Enums.isefinLogPublishStatus_ToString(isefinLogPublishStatus.NotIssued))
          List.Add(finBL.Enums.isefinLogPublishStatus_ToString(isefinLogPublishStatus.Open))
          List.Add(finBL.Enums.isefinLogPublishStatus_ToString(isefinLogPublishStatus.ToSend))
      End Select
      .PublishStatusList = List.ToCsvString()

      If .CanRepeat Then
        .LogRepeatBasisList = finBL.Enums.isefinLogRepeatBasis_GetList().ToCsvString()
        .LogRepeatCycleList = "Weekly,Fortnightly,Monthly,End of Month,Quarterly,6 Monthly,Yearly"
      End If
      If .SupportsDocumentPrint Then
        .PrintStatusList = finBL.Enums.isefinLogPrintStatus_GetList().ToCsvString()
      End If

      ' Global Collections
      If AccountLog IsNot Nothing Then
        For Each Element In finBL.Elements
          If Element.ElementType = isefinElementType.Fee AndAlso (Element.Active OrElse Element.Pk = AccountLog.FeeElementPk) Then
            .Elements.Add(New ElementInfo(finBL, Element))
          End If
        Next
      End If
      
      ' Application Shortcuts
      If Not Log.IsNew Then
        .ReplyApplicationShortcutUrl = String.Format("app://formshow?form={0}Log&amp;replyToLogPk={1}", mLogObjectType, Log.Pk)
        .ReplySmsApplicationShortcutUrl = String.Format("app://formshow?form=SmsMessage&amp;type={0}&amp;id={1}&amp;parentSourceLogPk={2}", mLogObjectType, finBL.UrlEncode(Log.RecordId), If(Log.ParentLogPk = 0, Log.Pk, Log.ParentLogPk))
        
        If .AllowPageWebMail Then
          .WebMailReplyApplicationShortcutUrl = String.Format("app://formshow?form={0}Log&amp;replyToLogPk={1}&amp;logType=WebMailToClient", mLogObjectType, If(Log.ParentLogPk = 0, Log.Pk, Log.ParentLogPk))          
        End If
      End If

      ' Load Child Logs collection (required in the next block)
      If .CanDelete Then
        Success =  Log.GetChildLogs(ChildLogs)
      End If
      
      ' Information required for Delete Prompts
      If Success AndAlso .CanDelete Then
        ' Has Child Logs?
        .ChildLogCount = ChildLogs.Count

        ' Service Logs?
        .HasServiceLogs = Log.ServiceLogPk &lt;&gt; 0
        If Not .HasServiceLogs Then
          ' Check Child Logs
          For Each ChildLog In ChildLogs
            If ChildLog.ParentLogPk = Log.Pk AndAlso ChildLog.ServiceLogPk &lt;&gt; 0 Then
              .HasServiceLogs = True
              Exit For
            End If
          Next
        End If

        ' Files?
        If finBL.Settings.DocumentManagerAllowLogDeleteFile AndAlso finBL.DocumentManager.IsAvailableResolved Then
          ' Check Log
          If Len(Log.DocumentFileName) &lt;&gt; 0 AndAlso Log.IsDocumentInStandardFolder Then .HasDeletableDocuments = True

          ' Check Child Logs
          If Not .HasDeletableDocuments Then
            For Each ChildLog In ChildLogs
              If ChildLog.ParentLogPk = Log.Pk Then
                If Len(ChildLog.DocumentFileName) &lt;&gt; 0 AndAlso ChildLog.IsDocumentInStandardFolder Then
                  .HasDeletableDocuments = True
                  Exit For
                End If
              End If
            Next
          End If
        End If
      End If
      
      ' Configuration
      .AddOnsWorkflow = finBL.Settings.AddOns.Workflow
      If Document IsNot Nothing Then
        .ExternalPartyFilter = finBL.HtmlWidgetUtilities.EncryptSql(finBL.ExternalParties.GetDataViewFilter(False, isefinExternalPartyType.Other, False, False, True, Document.ExternalPartyCategories))
        .ExternalPartyMandatory = (Document.AllowExternalParty = isefinDocumentAllowExternalParty.Mandatory)
      End If
      .HideOtherPages = False ' Not supported by this form but here for consistency
      .PromptDeleteFile = True
      .PromptOnSave = finBL.CloudConnectFunctions.CloudConnectSettings.PromptOnSave
      .PrioritiseOwnerAndDelegated = mPrioritiseOwnerAndDelegated
    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 Log.
''' &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 AccountLog As finAccountLog                        
  Dim DocumentFileNameResolved As String
  Dim Log As I_finLog
  Dim obj As Object
  Dim Record As FormInitialisationInfo
  Dim Success As Boolean
  Dim Warning As String

  ' 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 Log
  If Success Then
    If GetLog(Log, "") Then
      Select Case mLogObjectType
        Case isefinLogObjectType.Account 
          AccountLog = DirectCast(Log, finAccountLog)
      End Select
    Else
      Success = False
    End If
  End If

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

  ' Upload File to Document Manager?
  If requestInfo.Files.Count = 0 Then
    DocumentFileNameResolved = Record.DocumentFileName
  Else
    Success = finBL.LogUtilities.DocumentFileAdd(mLogObjectType, mRecordId, requestInfo.Files(0).FileData, requestInfo.Files(0).FileName, True, DocumentFileNameResolved)
  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
      With Log
        ' New
        If .IsNew Then
          Select Case Record.LogType
            Case isefinLogType.WebMailToClient
              .LogType = Record.LogType
          End Select
        End If
        
        ' General
        If Record.AllowPageGeneral Then
          .LogTimeZoneId = Record.LogTimeZoneId
          .LogTzDate = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(Record.LogTzDate)
          .LogSeverityId = Record.LogSeverityId          
          .Subject = Record.Subject
          .Notes = Record.Notes

          .ActionTimeZoneId = Record.ActionTimeZoneId 
          .ActionTzDate = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(Record.ActionTzDate)
          .ActionCompleteTzDate = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(Record.ActionCompleteTzDate)
          
          .LogOutcome = Record.LogOutcome
        End If
        
        ' Document
        If Record.AllowPageDocument Then
          .DocumentFileName = DocumentFileNameResolved
          .DocumentBookmark = Record.DocumentBookmark
          
          .PublishStatusText = Record.PublishStatusText
          Select Case .PublishStatus 
            Case isefinLogPublishStatus.ToSend 
              .PublishOnTimeZoneId = Record.PublishOnTimeZoneId ' NOTE: Must be done prior to setting the date
              .PublishOnTzDate = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(Record.PublishOnTzDate)
          End Select

          .DocumentSendEmailText = Record.DocumentSendEmailText
          .PublishFailDate = finBL.HtmlWidgetUtilities.GetDatabaseDateTimeFromJsonUtcDateTime(Record.PublishFailDate)
          .PublishResult = Record.PublishResult
          .PrintStatusText = Record.PrintStatusText
        End If
        
        ' Fee (combined pages)
        If Record.AllowPageFee AndAlso Record.AllowPageFeeNew AndAlso mLogObjectType = isefinLogObjectType.Account Then
          AccountLog.ChargeFee = Record.ChargeFee
          AccountLog.FeeElementId = Record.FeeElementId
          AccountLog.FeeNotes = Record.FeeNotes
          AccountLog.FeeReference = Record.FeeReference
          AccountLog.Fee = Record.Fee          
        End If
        
        ' Other
        If Record.AllowPageOther Then
          .OwnerUserId = Record.OwnerUserId
          .DelegatedToUserId = Record.DelegatedToUserId
          .DelegatedToRoleId = Record.DelegatedToRoleId 
          
          If .CanRepeat() Then
            .RepeatUse = Record.RepeatUse
            .RepeatCycle = Record.RepeatCycle
            .RepeatBasisText = Record.RepeatBasis
          End If
        End If
        
        ' External Party
        If Record.AllowPageExternalParty AndAlso mLogObjectType = isefinLogObjectType.Account Then
          AccountLog.ExternalPartyId = Record.ExternalPartyId
        End If
        
        ' Audit
        If Record.AllowPageAudit Then
          .ParentLogPk = Record.ParentLogPk
          If finBL.Settings.AddOns.Workflow Then
            .WorkflowId = Record.WorkflowId
          End If
        End If
        
        ' Complete?
        ' NOTE: Special flag used by the UI
        If Record.Complete AndAlso .ActionCompleteUtcDate = Nothing AndAlso .ActionUtcDate &lt;&gt; Nothing Then
          .ActionCompleteUtcDate = finBL.TimeZoneFunctions.GetCurrentUtcDateTime()
        End If
        
        ' Printed?
        ' NOTE: Special flag used by the UI
        If Record.Printed Then
          .PrintStatus = isefinLogPrintStatus.Printed
        End If
        
        ' Default Log Date?
        If .LogDate = Nothing Then
          .LogTimeZoneId = finBL.SettingsUser.TimeZoneIdResolved
          .LogUtcDate = finBL.TimeZoneFunctions.GetCurrentUtcDateTime()
        End If
      End With

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

      ' Workflow
      If Success AndAlso mWorkflowItemPk &lt;&gt; 0 Then
        finBL.HtmlWidgetUtilities.WorkflowItemComplete(mStartupParameters, Warning, Log.LogOutcome)
        
        If Len(Warning) &lt;&gt; 0 Then
          Success = False
          finBL.Error.ErrorBegin(Warning)
        End If
      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;
'''  Delete Log.
''' &lt;/summary&gt;
Private Function Delete(ByRef returnValue As String) As Boolean

  Dim DeleteChildLogs As Boolean
  Dim DeleteFiles As Boolean
  Dim Log As i_finLog
  Dim strTemp As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    DeleteChildLogs = .GetBoolean("DeleteChildLogs")
    DeleteFiles = .GetBoolean("DeleteFiles")
  End With
  
  ' Get Log
  If Success Then
    Success = GetLog(Log, "")
  End If

  ' Validate
  If Success Then
    If Not Log.CanDelete(strTemp) Then
      Success = False
      finBL.Error.ErrorBegin(strTemp)
      finBL.Error.ErrorExtend("Failed to Delete Log.")
    End If
  End If

  ' Delete
  If Success Then
    Success = Log.Delete(DeleteChildLogs, DeleteFiles)
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Publish Log.
''' &lt;/summary&gt;
Private Function Publish(ByRef returnValue As String) As Boolean

  Dim Log As i_finLog
  Dim strTemp As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Log
  If Success Then
    Success = GetLog(Log, "")
  End If

  ' Publish
  If Success Then
    If Not Log.Publish(isefinLogPublishType.Publish) Then
      Success = False
      finBL.Error.ErrorBegin(strTemp)
      finBL.Error.ErrorExtend("Failed to Publish Log.")
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Unpublish Log.
''' &lt;/summary&gt;
Private Function Unpublish(ByRef returnValue As String) As Boolean

  Dim Log As i_finLog
  Dim strTemp As String
  Dim Success As Boolean

  ' Assume Success
  Success = True

  ' Get Log
  If Success Then
    Success = GetLog(Log, "")
  End If

  ' Unpublish
  If Success Then
    If Not Log.Unpublish() Then
      Success = False
      finBL.Error.ErrorBegin(strTemp)
      finBL.Error.ErrorExtend("Failed to Unpublish Log.")
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Set the Log as having been Printed.
''' &lt;/summary&gt;
Private Function SetLogPrinted(ByRef returnValue As String) As Boolean

  Dim Log As i_finLog
  Dim LogPk As Integer
  Dim LogObjectType As isefinLogObjectType
  Dim Success As Boolean
  

  ' Assume Success
  Success = True

  ' Get Parameters
  With mCombinedParameters
    LogPk = .GetInteger("LogPk")
    LogObjectType = DirectCast(.GetEnum("LogObjectType", GetType(isefinLogObjectType)), isefinLogObjectType)
  End With

  ' Update Log's Print Status
  If Success Then
    ' Load Log
    If finBL.LogUtilities.LoadLog(LogObjectType, LogPk, Log) Then
      ' Update and Save Log
      With Log
        .PrintStatus = isefinLogPrintStatus.Printed 
        Success = .Save()
      End With
    Else
      Success = False
    End If
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Web Mail Action.
''' &lt;/summary&gt;
Private Function WebMailAction(ByRef returnValue As String) As Boolean

  Dim Action As String
  Dim Log As i_finLog
  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
    Action = .GetString("Action")
  End With
  
  ' Get Log
  If Success Then
    Success = GetLog(Log, "")
  End If

  ' Action
  If Success Then
    Select Case UCase(Action)
      Case "ARCHIVE"
        Success = finBL.ClientFunctions.LogUpdateWebMailArchived(Log.pk, True)
    
      Case "UNARCHIVE"
        Success = finBL.ClientFunctions.LogUpdateWebMailArchived(Log.Pk, False)
        
        Case "READ"
          Success = finBL.ClientFunctions.LogUpdateWebMailRead(Log.pk, "", True)

        Case "UNREAD"
          Success = finBL.ClientFunctions.LogUpdateWebMailRead(Log.pk, "", False)
        
      Case Else
        Success = False
        finBL.Error.ErrorBeginFormat("Unhandled action '{0}'", action)
    End Select
  End If

  ' Error
  If Not Success Then
    finBL.Error.ErrorExtend("Failed to action Client Mail Log.")
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Extended Data.
''' &lt;/summary&gt;
Private Function GetExtendedData(ByRef returnValue As String) As Boolean

  Dim ExtendedType As String
  Dim Log As i_finLog
  Dim Success As Boolean

  ' Assume Success
  Success = True
  
  ' Get Parameters
  With mParameters
    ExtendedType = .GetString("ExtendedType")
  End With
  
  ' Get Log
  If Success Then
    Success = GetLog(Log, "")
  End If
  
  ' Handle
  If Success Then
    Select Case UCase(ExtendedType)
      Case "ACCOUNTDATA"
        returnValue = finBL.HtmlEncode(finBL.Runtime.TextUtilities.XmlIndent(DirectCast(Log, finAccountLog).AccountData), True, True)

      Case "EXTENDED"
        returnValue = finBL.HtmlEncode(finBL.Runtime.TextUtilities.XmlIndent(Log.ExtendedData), True, True)

      Case "HTML"
        returnValue = Log.DocumentHtml

      Case "PARAMETERS"
        returnValue = finBL.Utilities.GetHtmlFromSummaryTable(finBL.Utilities.KeyValueListToSummaryTable(Log.Parameters.ToKeyValueList()), "", False, iseSummaryPageTarget.WebExternal1)

      Case "USERDATA"
        returnValue = finBL.HtmlEncode(Log.UserData.ToXmlString(False, True), True, True)

      Case Else
        Success = False
        finBL.Error.ErrorBeginFormat("Extended Type '{0}' not supported.", ExtendedType)
    End Select
  End If

  ' Error
  If Not Success Then
    finBL.Error.ErrorExtend("Failed to get Extended Data.")
  End If

  Return Success

End Function

''' &lt;summary&gt;
'''  Get Log Summary to allow entire conversation thread to be viewed.
''' &lt;/summary&gt;
Private Function GetLogSummary(log As I_finLog) As String

  Dim Html As String
  Dim Index As Integer
  Dim LogRO As finLogRO
  Dim Logs As finLogs
  Dim ReplyToLogPk As Integer
  Dim Success As Boolean

  ' Assume Success
  Success = True
  
  ' Get Child Logs
  Logs = finBL.CreateLogs()
  Select Case mLogObjectType 
    Case isefinLogObjectType.Account 
      Success = Logs.LoadAccountThread(log.RecordId, If(log.ParentLogPk = 0, log.Pk, log.ParentLogPk))

    Case isefinLogObjectType.AccountApp
      Success = Logs.LoadAccountAppThread(log.RecordId, If(log.ParentLogPk = 0, log.Pk, log.ParentLogPk))

    Case isefinLogObjectType.Client
      Success = Logs.LoadClientThread(log.RecordId, If(log.ParentLogPk = 0, log.Pk, log.ParentLogPk))

    Case isefinLogObjectType.SecurityStmt
      Success = Logs.LoadSecurityStmtThread(log.RecordId, If(log.ParentLogPk = 0, log.Pk, log.ParentLogPk))

    Case isefinLogObjectType.SecurityStmtItem
      Success = Logs.LoadSecurityStmtItemThread(CInt(log.RecordId), If(log.ParentLogPk = 0, log.Pk, log.ParentLogPk))

    Case isefinLogObjectType.User
      Success = Logs.LoadUserThread(log.RecordId, If(log.ParentLogPk = 0, log.Pk, log.ParentLogPk))

    Case Else
  End Select
  
  ' Get HTML
  If Success Then
    ' Find Index
    ' NOTE: Cannot use mReplyToPk since this may have been adjusted to be the original Parent Log
    ReplyToLogPk = mStartupParameters.GetInteger("ReplyToLogPk")
    For Each LogRO In Logs
      If LogRO.Pk = ReplyToLogPk Then
        Index = Logs.IndexOf(LogRO)
        Exit For
      End If
    Next
    
    Html = finBL.SummaryPageFunctions.LogSummary(False, Logs, Index, True, ScriptInfo.ContextData.ToKeyValueList())
  End If
  
  ' Error
  If Success Then
    Return Html
  Else
    finBL.Error.ErrorExtend("Failed to get Log Summary.")
    Return finBL.GetHtmlErrorMessage(finBL.Error.Message(False, False))
  End If

End Function

''' &lt;summary&gt;
'''  Get Service Log Summary.
''' &lt;/summary&gt;
Private Function GetServiceLogSummary(ByRef returnValue As String) As Boolean

  Dim Log As i_finLog
  Dim ServiceLog As finwsServiceLog
  Dim Success As Boolean

  ' Assume Success
  Success = True
  
  ' Get Log
  If Success Then
    Success = GetLog(Log, "")
  End If
  
  ' Service Log
  If Success AndAlso Log.ServiceLog IsNot Nothing Then
    ServiceLog = finBL.CreateWsServiceLog(Log.ServiceLog)
    returnValue = ServiceLog.ExtendedHtml
  End If

  ' Error
  If Not Success Then
    finBL.Error.ErrorExtend("Failed to get Service Log Summary.")
  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 LogObjectType As isefinLogObjectType
  Public LogType as isefinLogType 
  Public Pk As Integer
  Public ObjectNameFriendly As String
  Public ReplyToLogNotes As String
  Public ReplyToLogPk As Integer
  Public Timestamp As Integer
  
  ' Icon
  Public Icon As String
  
  ' Bookmarking
  Public Bookmarked As Boolean  
  Public DatabaseReadOnly As Boolean
  Public RecordType As String
  
  ' State
  Public HasDocument As Boolean
  Public IsIncomplete As Boolean
  Public SupportsDocumentPrint As Boolean
  Public SupportsDocumentSendEmail As Boolean
  Public SupportsReplyViaSms As Boolean
  
  ' General
  Public RecordId As String
  Public RecordDescription As String
  Public AccountAppApplicantPk As Integer
  Public AccountAppApplicantDescription As String
  Public AccountAppCollateralItemPk As Integer
  Public AccountAppCollateralItemDescription As String
  Public LogTzDate As Date?
  Public LogTimeZoneId As String
  Public SecurityStmtItemPk As Integer
  Public SecurityStmtItemDescription As String
  Public Subject As String
  Public Notes As String
  
  Public ActionCompleteTzDate As Date?
  Public ActionTzDate As Date?
  Public ActionTimeZoneId As String
  
  Public LogOutcome As String
  
  ' Service Log
  Public ServiceLogPageTitle As String
  Public ServiceLogSummaryHtml As String
  
  ' Extended Data
  Public ExtendedDataPageTitle As String
  Public ExtendedDataSummaryHtml As String
  Public ExtendedDataSummaryHtml2 As String
  
  ' Web Mail
  Public WebMailStatus As String
  Public WebMailReadTzDate As Date?
  Public WebMailRelatedAccountId As String
  Public WebMailRelatedAccountName As String
  Public WebMailRelatedAccountAppId As String
  Public WebMailRelatedAccountAppName As String
  
  ' Document
  Public DocumentFileName As String
  Public DocumentBookmark As String
  Public DocumentId As String
  Public DocumentDescription As String
  
  Public PublishedTzDate As Date?
  Public PublishOnTzDate As Date?
  Public PublishOnTimeZoneId As String
  Public DocumentSendEmailText As String  
  Public PublishResult As String
  Public PublishStatus As isefinLogPublishStatus
  Public PublishStatusText As String
  Public PublishFailDate As Date?

  Public PrintStatus As isefinLogPrintStatus
  Public PrintStatusText As String
  Public PrintedTzDate As Date?
  
  ' Fee &amp; Account Details
  Public AccountDetailsSummaryHtml As String
  Public DocumentFeeElementPk As Integer
  Public Fee As Decimal
  Public FeeAccountTransactionPk As Integer
  Public HasFee As Boolean
  Public HasAccountData As Boolean
  
  ' Charge Fee
  Public ChargeFee As Boolean
  Public FeeNotes As String
  Public FeeReference As String
  Public FeeElementId As String
  
  ' Other
  Public LogSeverityId As String
          
  Public OwnerUserId As String
  Public DelegatedToUserId As String
  Public DelegatedToRoleId As String
  
  Public CanRepeat As Boolean
  Public RepeatUse As Boolean
  Public RepeatCycle As String
  Public RepeatBasis As String
  
  ' External Party
  Public ExternalPartyId As String
  
  ' Audit
  Public ParentLogPk As Integer
  Public SourceText As String
  
  Public ServiceLogPk As Integer
  Public ServiceLogDescription As String
  
  'Public FeeAccountTransactionPk As Integer ' Already on Fee &amp; Account Details page
  Public AccountHistoryPk As Integer
  
  Public WorkflowId As String
  
  Public CreatedDetails As String
  Public PublishDetails As String
  Public PrintedDetails As String
  
  ' Summary
  Public SummaryHtml As String

  ' Permissions
  Public AllowPageGeneral As Boolean
  Public AllowPageServiceLog As Boolean
  Public AllowPageExtendedData As Boolean
  Public AllowPageWebMail As Boolean
  Public AllowPageDocument As Boolean
  Public AllowPageFee As Boolean
  Public AllowPageFeeNew As Boolean
  Public AllowPageOther As Boolean
  Public AllowPageExternalParty As Boolean
  Public AllowPageAudit As Boolean
  Public AllowPageSummary As Boolean
  Public AllowViewExtended As Boolean
  Public AllowViewParameters As Boolean
  Public AllowViewHtml As Boolean
  Public AllowViewAccountData As Boolean
  Public AllowViewUserData As Boolean
  
  Public CanDelete As Boolean
  Public CanPrintLogDetails As Boolean
  Public CanSave As Boolean

  Public CanPublish As Boolean
  Public CanPrint As Boolean
  Public CanUnpublish As Boolean

  Public CanUpdateNotes As Boolean
  Public CanUpdateOwnerUser As Boolean
  Public CanUpdateDelegatedToUser As Boolean
  Public CanUpdateDelegatedToRole As Boolean

  Public CanViewFeeTransaction As Boolean
  Public CanUpdateFee As Boolean
  Public CanChargeFee As Boolean

  ' Lists
  Public ExternalPartyFilter As String
  Public LogOutcomesInformationListId As String
  Public LogRepeatBasisList As String
  Public LogRepeatCycleList As String
  Public PublishResultInformationListId As String
  Public PublishResultFailedInformationListId As String
  Public PublishResultNotIssuedInformationListId As String
  Public PrintStatusList As String
  Public PublishStatusList As String
  Public SubjectInformationListId As String
  
  ' Global Collections
  Public Elements As New List(Of ElementInfo)
  
  ' Application Shortcuts
  Public ReplyApplicationShortcutUrl As String
  Public ReplySmsApplicationShortcutUrl As String
  Public WebMailReplyApplicationShortcutUrl As String
  
  ' Special
  Public Complete As Boolean
  Public Printed As Boolean
  
  ' Information Required for Delete Prompts
  Public ChildLogCount As Integer
  Public HasDeletableDocuments As Boolean
  Public HasServiceLogs As Boolean
  
  ' Configuration
  Public AddOnsWorkflow As Boolean
  Public ExternalPartyMandatory As Boolean
  Public HideOtherPages As Boolean
  Public PromptDeleteFile As Boolean
  Public PromptOnSave As Boolean
  Public PrioritiseOwnerAndDelegated 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



''' &lt;summary&gt;
'''  Simple information about an Element (Fee Elements only).
''' &lt;/summary&gt;
Public Class ElementInfo

  Public ElementId As String
  Public Description As String
  Public TransactionNotes As String
  Public TransactionReference As String
  Public TransactionValue As Decimal

  Public Sub New(finBL As ISfinSupport,
                 element As finElementRO)

    With element
      Me.ElementId = .ElementId
      Me.Description = .Description 
      Me.TransactionNotes = .TransactionNotes
      Me.TransactionReference = .TransactionReference
      Me.TransactionValue = .TransactionValue
    End With

  End Sub

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>System-supplied HTML Widget to edit a Log for any record type.</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="ServiceLog"&gt;Service Log&lt;/li&gt;
        &lt;li tabId="ExtendedData"&gt;Extended Data&lt;/li&gt;
        &lt;li tabId="WebMail"&gt;Web Mail&lt;/li&gt;
        &lt;li tabId="Document"&gt;Document&lt;/li&gt;
        &lt;li tabId="Fee"&gt;Fee&lt;/li&gt;
        &lt;li tabId="FeeNew"&gt;Charge Fee&lt;/li&gt;
        &lt;li tabId="Other"&gt;Other&lt;/li&gt;
        &lt;li tabId="ExternalParty"&gt;External Party&lt;/li&gt;
        &lt;li tabId="Audit" icon="Shield|Clock"&gt;Audit&lt;/li&gt;
        &lt;li tabId="Summary" summaryPage="true"&gt;Summary&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:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
  
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblLogDetails"&gt;Log details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboRecord"&gt;Record:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRecord" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr style="display:none;"&gt;
          &lt;th&gt;&lt;label for="cboRecordSub1"&gt;Sub1:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRecordSub1" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr style="display:none;"&gt;
          &lt;th&gt;&lt;label for="cboRecordSub2"&gt;Sub2:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRecordSub2" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateLogDate"&gt;Date:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;div id="dateLogDate"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr id="trLogSeverity"&gt;
          &lt;th&gt;&lt;label for="cboLogSeverity"&gt;Severity:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboLogSeverity" /&gt;&lt;/td&gt;
        &lt;/tr&gt;  
              
        &lt;tr id="trSubject"&gt;
          &lt;th&gt;&lt;label for="cboSubject"&gt;Subject:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboSubject" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr style="height:100%"&gt;
          &lt;th&gt;&lt;label for="txtNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td style="height:100%"&gt;&lt;input id="txtNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr id="trReplyToLogNotes"&gt;
          &lt;th&gt;&lt;label for="txtReplyToLogNotes"&gt;Replying&amp;nbsp;To:&amp;nbsp;&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtReplyToLogNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
  
        &lt;tr id="trAction"&gt;&lt;th colspan="2"&gt;&lt;label id="lblAction"&gt;Action details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateAction"&gt;Action:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;div id="dateAction"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="dateActionComplete"&gt;Complete:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;div id="dateActionComplete"&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
  
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblLogOutcome"&gt;Outcome&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboLogOutcome"&gt;Outcome:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboLogOutcome" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- Service Log --&gt;
    &lt;div id="pageServiceLog"&gt;
      &lt;div id="wbServiceLog" class="is-dock-fill"&gt;&lt;/div&gt;    
    &lt;/div&gt;



    &lt;!-- Extended Data --&gt;
    &lt;div id="pageExtendedData"&gt;
      &lt;div class="is-dock-fill" style="display:flex; flex-direction:column"&gt;
        &lt;div id="wbExtendedData" style="flex-grow:0; flex-shrink:0"&gt;&lt;/div&gt;
        &lt;div id="wbExtendedData2" style="flex-grow:1; flex-shrink:1"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;



    &lt;!-- Web Mail --&gt;
    &lt;div id="pageWebMail"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
  
        &lt;tbody&gt;
          &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblWebMail"&gt;Web Mail details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtWebMailStatus"&gt;Status:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtWebMailStatus" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="dateWebMailRead"&gt;Read On:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;div id="dateWebMailRead"&gt;&lt;/div&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblWebMailRelated"&gt;Related details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboWebMailRelatedAccount"&gt;Account:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboWebMailRelatedAccount" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboWebMailRelatedAccountApp"&gt;Application:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboWebMailRelatedAccountApp" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;
  
  

    &lt;!-- Document --&gt;
    &lt;div id="pageDocument"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
  
  
        &lt;tbody id="tbDocument"&gt;
          &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblDocument"&gt;The Document that this Log is linked to&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboDocumentFileName"&gt;File Name:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboDocumentFileName" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="txtDocumentBookmark"&gt;Bookmark:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="txtDocumentBookmark" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
  
        &lt;tbody id="tbDocumentPublication"&gt;
          &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblDocumentPublication"&gt;Document publication details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboDocument"&gt;Document:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboDocument" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboPublishStatus"&gt;Status:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboPublishStatus" /&gt;&lt;button id="cmdUnpublish"&gt;&lt;/button&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="datePublishOnDate"&gt;Publish On:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;div id="datePublishOnDate"&gt;&lt;/div&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboDocumentSendEmail"&gt;Send Email:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboDocumentSendEmail" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="datePublishedDate"&gt;Published:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;div id="datePublishedDate"&gt;&lt;/div&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="datePublishFailDate"&gt;Failed:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;div id="datePublishFailDate"&gt;&lt;/div&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboPublishResult"&gt;Result:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboPublishResult" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
  
        &lt;tbody id="tbDocumentPrintStatus"&gt;
          &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblDocumentPrintStatus"&gt;Document Print Status&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="cboPrintStatus"&gt;Status:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;input id="cboPrintStatus" /&gt;&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
            &lt;th&gt;&lt;label for="datePrintedDate"&gt;Printed:&lt;/label&gt;&lt;/th&gt;
            &lt;td&gt;&lt;div id="datePrintedDate"&gt;&lt;/div&gt;&lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
  
        &lt;tbody id="tbHtmlDocument"&gt;
          &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblHtmlDocument"&gt;HTML Document&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;/tbody&gt;
  
        &lt;tbody id="tbEmbeddedDocument"&gt;
          &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblEmbeddedDocument"&gt;Embedded Document&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- Fee &amp; Account Details --&gt;
    &lt;div id="pageFee"&gt;
      &lt;table id="tblFee" class="is-form" style="height:100%"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
  
        &lt;!-- WARNING: Do not use tbody elements otherwise there are sizing issues --&gt;
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblFeeCharged"&gt;Fee charged&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numFee"&gt;Fee:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numFee" /&gt; &lt;button id="cmdFee" class="is-button normal form"&gt;Details&lt;/button&gt; &lt;span id="spnChargeFeeWarning" class="is-info-text warning small"&gt;Failed to charge Fee&lt;/span&gt;&lt;/td&gt;
        &lt;/tr&gt;
  
        &lt;tr id="trAccountDetails"&gt;&lt;th colspan="2"&gt;&lt;label id="lblAccountDetails"&gt;Balance details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr id="trAccountDetailsPreview" style="height:100%"&gt;
          &lt;th colspan="2" style="height:100%"&gt;&lt;div id="wbAccountDetails"&gt;&lt;/div&gt;&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;
  
  
  
    &lt;!-- Charge Fee --&gt;
    &lt;div id="pageFeeNew"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
  
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblChargeFee"&gt;Charge a Fee&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkChargeLogFee" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;      
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboLogFeeElement"&gt;Element:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboLogFeeElement" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="numLogFee"&gt;Value:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="numLogFee" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtLogFeeReference"&gt;Reference:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtLogFeeReference" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtLogFeeNotes"&gt;Notes:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtLogFeeNotes" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- Other --&gt;
    &lt;div id="pageOther"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;

        &lt;tr id="trOwnerUser1"&gt;&lt;th colspan="2"&gt;&lt;label id="lblOwnerUser"&gt;Owner and User Delegated to&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr id="trOwnerUser2"&gt;
          &lt;th&gt;&lt;label for="cboOwnerUser"&gt;Owner:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboOwnerUser" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr id="trOwnerUser3"&gt;
          &lt;th&gt;&lt;label for="cboDelegatedToUser"&gt;Delegated&amp;nbsp;User:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboDelegatedToUser" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr id="trOwnerUser4"&gt;
          &lt;th&gt;&lt;label for="cboDelegatedToRole"&gt;Delegated Role:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboDelegatedToRole" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblRepeat"&gt;Log Repeat details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th colspan="2"&gt;&lt;input id="chkRepeatUse" type="checkbox" /&gt;&lt;/th&gt;
        &lt;/tr&gt;      
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="cboRepeatBasis"&gt;Basis:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRepeatBasis" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th class="indent1"&gt;&lt;label for="cboRepeatCycle"&gt;Cycle:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboRepeatCycle" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- External Party --&gt;
    &lt;div id="pageExternalParty"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:9em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
  
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblExternalParty"&gt;Link to an External Party&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboExternalParty"&gt;External&amp;nbsp;Party:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboExternalParty" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/div&gt;



    &lt;!-- Summary --&gt;
    &lt;div id="pageSummary"&gt;
      &lt;div id="wbSummary" class="is-dock-fill"&gt;&lt;/div&gt;        
    &lt;/div&gt;



    &lt;!-- Audit --&gt;
    &lt;div id="pageAudit"&gt;
      &lt;table class="is-form"&gt;
        &lt;colgroup&gt;
          &lt;col style="width:7em" /&gt;
          &lt;col /&gt;
        &lt;/colgroup&gt;
  
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label&gt;Log Code and Source&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtLogPk"&gt;Code:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtLogPk" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtParentLogPk"&gt;Parent:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtParentLogPk" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="txtSource"&gt;Source:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="txtSource" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblServiceLog"&gt;Service Log details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboServiceLogPk"&gt;Service Log:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboServiceLogPk" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblFeeTransaction"&gt;Fee Transaction details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboFeeAccountTransactionPk"&gt;Transaction:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboFeeAccountTransactionPk" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboAccountHistoryPk"&gt;History:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboAccountHistoryPk" /&gt;&lt;/td&gt;
        &lt;/tr&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblWorkflow"&gt;Linked Workflow details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr&gt;
          &lt;th&gt;&lt;label for="cboWorkflow"&gt;Workflow:&lt;/label&gt;&lt;/th&gt;
          &lt;td&gt;&lt;input id="cboWorkflow" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblExtendedData"&gt;Extended Data&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;tr id="trExtendedData"&gt;
          &lt;th colspan="2"&gt;
            &lt;button id="cmdExtendedData" class="is-button small"&gt;Extended&lt;/button&gt;
            &lt;button id="cmdParameters" class="is-button small"&gt;Parameters&lt;/button&gt;
            &lt;button id="cmdDocumentHtml" class="is-button small"&gt;HTML&lt;/button&gt;
            &lt;button id="cmdAccountData" class="is-button small"&gt;Account&lt;/button&gt;
            &lt;button id="cmdUserData" class="is-button small"&gt;User Data&lt;/button&gt;
          &lt;/th&gt;
        &lt;/tr&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblCreatedDetails"&gt;Creation and Last Updated details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;th colspan="2"&gt;&lt;div id="divCreatedDetails"&gt;&lt;/div&gt;&lt;/th&gt;
        
        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblPublishDetails"&gt;Document Publication details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;th colspan="2"&gt;&lt;div id="divPublishDetails"&gt;&lt;/div&gt;&lt;/th&gt;

        &lt;tr&gt;&lt;th colspan="2"&gt;&lt;label id="lblPrintedDetails"&gt;Document Printed details&lt;/label&gt;&lt;/th&gt;&lt;/tr&gt;
        &lt;th colspan="2"&gt;&lt;div id="divPrintedDetails"&gt;&lt;/div&gt;&lt;/th&gt;
      &lt;/table&gt;    
    &lt;/div&gt;

  &lt;/div&gt;


  &lt;!-- Form Footer --&gt;
  &lt;footer&gt;
    &lt;button id="cmdActions"/&gt;
    &lt;button id="cmdReply" class="is-button" style="float:left" icon="Log_Reply"&gt;Reply&lt;/button&gt;
    &lt;button id="cmdReplySms" class="is-button" style="float:left" icon="Sms|Reply"&gt;Reply via SMS&lt;/button&gt;
    &lt;button id="cmdReplyWebMail" class="is-button" style="float:left" icon="Webmail_Reply"&gt;Reply to Web Mail&lt;/button&gt;
    &lt;button id="cmdPrint_ServiceLog" class="is-button" style="float:left" icon="Print"&gt;Print Report&lt;/button&gt;
  
    &lt;button id="cmdCancel" class="is-button"&gt;Cancel&lt;/button&gt;
    &lt;button id="cmdCompleteLog" class="is-button positive"&gt;Complete &amp;amp; Save&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;

// Global Collections
var mElements;


// Controls
var C = {
  //   General
  lblLogDetails: null,
  cboRecord: null,
  cboRecordSub1: null,
  cboRecordSub2: null,
  dateLogDate: null,
  cboLogSeverity: null,  
  cboSubject: null,
  txtNotes: null,
  trReplyToLogNotes: null,
  txtReplyToLogNotes: null,
  lblAction: null,
  dateAction: null,
  dateActionComplete: null,
  lblLogOutcome: null,
  cboLogOutcome: null,

  //   Service Log
  wbServiceLog: null,

  //   Extended Data
  wbExtendedData: null,
  wbExtendedData2: null,

  //   Web Mail
  lblWebMail: null,
  txtWebMailStatus: null,
  dateWebMailRead: null,

  lblWebMailRelated: null,
  cboWebMailRelatedAccount: null,
  cboWebMailRelatedAccountApp: null,

  //   Document
  lblDocument: null,
  cboDocumentFileName: null,
  txtDocumentBookmark: null,
  cmdDocumentPrint: null,

  tbDocumentPublication: null,
  lblDocumentPublication: null,
  cboDocument: null,
  cboPublishStatus: null,
  cmdUnpublish: null,
  datePublishOnDate: null,
  cboDocumentSendEmail: null,
  datePublishedDate: null,
  datePublishFailDate: null,
  cboPublishResult: null,

  tbDocumentPrintStatus: null,
  lblDocumentPrintStatus: null,
  cboPrintStatus: null,
  datePrintedDate: null,

  tbHtmlDocument: null,
  lblHtmlDocument: null,

  tbEmbeddedDocument: null,
  lblEmbeddedDocument: null,

  //   Fee &amp; Account Details
  tblFee: null,
  lblFeeCharged: null,
  trFee: null,
  numFee: null,
  spnChargeFeeWarning: null,
  cmdFee: null,
  trAccountDetails: null,
  lblAccountDetails: null,
  trAccountDetailsPreview: null,
  wbAccountDetails: null,

  //   Charge Fee
  lblChargeFee: null,
  chkChargeLogFee: null,
  cboLogFeeElement: null,
  numLogFee: null,
  txtLogFeeReference: null,
  txtLogFeeNotes: null,

  //   Other
  lblOwnerUser: null,
  cboOwnerUser: null,
  cboDelegatedToUser: null,
  cboDelegatedToRole: null,
  
  lblRepeat: null,
  chkRepeatUse: null,
  cboRepeatBasis: null,
  cboRepeatCycle: null,

  //   External Party
  lblExternalParty: null,
  cboExternalParty: null,
  
  //   Audit
  txtLogPk: null,
  txtParentLogPk: null,
  txtSource: null,
  
  lblServiceLog: null,
  cboServiceLogPk: null,
  
  lblFeeTransaction: null,
  cboFeeAccountTransactionPk: null,
  cboAccountHistoryPk: null,
  
  lblWorkflow: null,
  cboWorkflow: null,
  
  lblExtendedData: null,
  trExtendedData: null,
  cmdExtendedData: null,
  cmdParameters: null,
  cmdDocumentHtml: null,
  cmdAccountData: null,
  cmdUserData: null,
  
  lblCreatedDetails: null,
  divCreatedDetails: null,
  lblPublishDetails: null,
  divPublishDetails: null,
  lblPrintedDetails: null,
  divPrintedDetails: null,
  
  //   Summary
  wbSummary: null,
}

// Form
var frmMain;
var tabDetails;

// Buttons
var cmdCancel;
var cmdFinish;

var cmdReply;
var cmdReplySms;
var cmdReplyWebMail;
var cmdCompleteLog;
var cmdPrint_ServiceLog;

// Other
var mAutoPrint = false;
var mPageId;

// ==========
// Initialise
// ==========
$(function () {
  // --------
  // Controls
  // --------
  //   General
  C.lblLogDetails = widget.UI.Label("lblLogDetails", {});
  C.cboRecord = widget.UI.DBCombo("cboRecord", {
    autoReadOnly: false,
    hyperlinkContent: true,
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onContentHyperlink: function () { Form_ExecuteAction("ShowMainRecord"); },
  });

  C.cboRecordSub1 = widget.UI.DBCombo("cboRecordSub1", {
    autoReadOnly: false,
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });
  C.cboRecordSub2 = widget.UI.DBCombo("cboRecordSub2", {
    autoReadOnly: false,
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });

  C.dateLogDate = widget.UI.DateTimeZone("dateLogDate", {
    allowBlank: true,
  });
  C.cboLogSeverity = widget.UI.DBCombo("cboLogSeverity", {
    width: widget.UI.FIELD_WIDTH_CODE_5,
  });
  C.cboSubject = widget.UI.InformationListComboBox("cboSubject", {
    allowBlank: false,
    limitToList: false,
    maxLength: 50,
    
    onChange: cboSubject_Change,
  });
  C.txtNotes = widget.UI.TextBox("txtNotes", {
    allowBlank: true,
    multiLine: true,
    spellCheck: true,
  });
  C.trReplyToLogNotes = $("#trReplyToLogNotes");
  C.txtReplyToLogNotes = widget.UI.TextBox("txtReplyToLogNotes", {
    autoReadOnly: false,
    multiLine: true,
    readOnly: true,
    rows: 8,
  });

  C.lblAction = widget.UI.Label("lblAction", {});
  C.dateAction = widget.UI.DateTimeZone("dateAction", {
    allowBlank: true,
    
    onChange: dateAction_Change,
  });
  C.dateActionComplete = widget.UI.DateTimeZone("dateActionComplete", {
    allowBlank: true,
    timeZoneVisible: false,
    
    onChange: dateActionComplete_Change,
  });

  C.lblLogOutcome = widget.UI.Label("lblLogOutcome", {});
  C.cboLogOutcome = widget.UI.InformationListComboBox("cboLogOutcome", {
    limitToList: false,
    maxLength: 50,
  });

  //   Service Log
  C.wbServiceLog = widget.UI.PreviewPane("wbServiceLog", {});

  //   Extended Data
  C.wbExtendedData = widget.UI.PreviewPane("wbExtendedData", {
    border: false,
    resizeToFit: true, // Once content has loaded
    resizeToFitAdditionalHeight: 12,
  });
  C.wbExtendedData2 = widget.UI.PreviewPane("wbExtendedData2", {
    border: false,  
  });
  
  //   Web Mail
  C.lblDocument = widget.UI.Label("lblWebMail", {});
  C.txtWebMailStatus = widget.UI.TextBox("txtWebMailStatus", {
    autoReadOnly: false,
    readOnly: true,
    width: "12em"
  });
  C.dateWebMailRead = widget.UI.DateTimeZone("dateWebMailRead", {
    autoReadOnly: false,
    readOnly: true,
    timeZoneVisible: true,
  });

  C.lblWebMailRelated = widget.UI.Label("lblWebMailRelated", {});
  C.cboWebMailRelatedAccount = widget.UI.DBCombo("cboWebMailRelatedAccount", {
    autoReadOnly: false,
    hyperlinkContent: true,
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onContentHyperlink: function () { Form_ExecuteAction("ShowWebMailRelatedAccount"); },
  });
  C.cboWebMailRelatedAccountApp = widget.UI.DBCombo("cboWebMailRelatedAccountApp", {
    autoReadOnly: false,
    hyperlinkContent: true,
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,

    onContentHyperlink: function () { Form_ExecuteAction("ShowWebMailRelatedAccountApp"); },
  });

  //   Document
  C.lblDocument = widget.UI.Label("lblDocument", {});
  C.cboDocumentFileName = widget.UI.DocumentManagerComboBox("cboDocumentFileName", {
    allowNew: true,
    maxLength: 255,
    
    onButtonClick: function (sender, e) { Form_ExecuteAction(e.id); },
    showPreview: false,
    fileTypes: "*",
  });
  C.txtDocumentBookmark = widget.UI.TextBox("txtDocumentBookmark", {
    allowBlank: true,
    maxLength: 50
  });

  C.tbDocumentPublication = $("#tbDocumentPublication");
  C.lblDocumentPublication = widget.UI.Label("lblDocumentPublication", {});
  C.cboDocument = widget.UI.DBCombo("cboDocument", {
    autoReadOnly: false,
    readOnly: true,
    showDropdown: false,
    width: widget.UI.FIELD_WIDTH_CODE_20
  });
  C.cboPublishStatus = widget.UI.ComboBox("cboPublishStatus", {
    allowBlank: false,
    limitToList: true,
    maxLength: 20,
    width: widget.UI.FIELD_WIDTH_CODE_10,
    
    onChange: pageDocument_Refresh,
  });
  C.cmdUnpublish = widget.UI.Button("cmdUnpublish", {
    caption: "Reset",
    cssClass: "is-button normal form",
    onClick: function () { Form_ExecuteAction("Unpublish"); },
  });
  C.datePublishOnDate = widget.UI.DateTimeZone("datePublishOnDate", {
    allowBlank: false
  });
  C.cboDocumentSendEmail = widget.UI.ComboBox("cboDocumentSendEmail", {
    allowBlank: false,
    limitToList: true,
    listCsv: "Default,Yes,No",
    width: "6em",
  });
  C.datePublishedDate = widget.UI.DateTimeZone("datePublishedDate", {
    allowBlank: true,
    autoReadOnly: false,
    readOnly: true,
    timeZoneVisible: false,
  });
  C.datePublishFailDate = widget.UI.DateTimeZone("datePublishFailDate", {
    allowBlank: false,
    timeVisible: false,
    timeZoneVisible: false,
  });
  C.cboPublishResult = widget.UI.InformationListComboBox("cboPublishResult", {
    limitToList: false,
    maxLength: 50
  });

  C.tbDocumentPrintStatus = $("#tbDocumentPrintStatus");
  C.lblDocumentPrintStatus = widget.UI.Label("lblDocumentPrintStatus", {
    //tooltipText: "Logs that have a Print Status of 'To Print' will appear in the Document Print wizard.\n\nWhen printing, a Log's Embedded Document will take precedence over the Document File Name and any HTML Document content.",
  });
  C.cboPrintStatus = widget.UI.ComboBox("cboPrintStatus", {
    allowBlank: false,
    limitToList: true,
    maxLength: 20,
    
    onChange: pageDocument_Refresh,
  });
  C.datePrintedDate = widget.UI.DateTimeZone("datePrintedDate", {
    allowBlank: true,
    autoReadOnly: false,
    readOnly: true,
  });

  C.tbHtmlDocument = $("#tbHtmlDocument");
  C.lblHtmlDocument = widget.UI.Label("lblHtmlDocument", {});

  C.tbEmbeddedDocument = $("#tbEmbeddedDocument");
  C.lblDocument = widget.UI.Label("lblEmbeddedDocument", {});

  //   Fee &amp; Account Details
  C.tblFee = $("#tblFee");
  C.lblFeeCharged = widget.UI.Label("lblFeeCharged", {});
  C.numFee = widget.UI.NumberBox("numFee", {
    decimals: -1, // Currency
    width: "5em",
  });
  C.spnChargeFeeWarning = $("#spnChargeFeeWarning");
  C.cmdFee = $("#cmdFee");
  C.cmdFee.on("click", cmdFee_Click);
  C.trAccountDetails = $("#trAccountDetails");
  C.lblAccountDetails = widget.UI.Label("lblAccountDetails", {});
  C.trAccountDetailsPreview = $("#trAccountDetailsPreview");
  C.wbAccountDetails = widget.UI.PreviewPane("wbAccountDetails", {});

  //   Charge Fee
  C.lblChargeFee = widget.UI.Label("lblChargeFee", {});
  C.chkChargeLogFee = widget.UI.CheckBox("chkChargeLogFee", {
    caption: "Charge a fee to cover expenses?",

    onChange: chkChargeLogFee_Change,
  });
  C.cboLogFeeElement = widget.UI.DBCombo("cboLogFeeElement", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_10,
    
    onChange: cboLogFeeElement_Change,
  });
  C.numLogFee = widget.UI.NumberBox("numLogFee", {
    allowBlank: false,
    blankIfZero: true,
    decimals: -1, // Currency
    width: "5em",
  });
  C.txtLogFeeReference = widget.UI.TextBox("txtLogFeeReference", {
    maxLength: 20,
  })
  C.txtLogFeeNotes = widget.UI.TextBox("txtLogFeeNotes", {
    maxLength: 255,
  })


  //   Other
  C.lblOwnerUser = widget.UI.Label("lblOwnerUser", {});
  C.cboOwnerUser = widget.UI.DBCombo("cboOwnerUser", {
    allowBlank: false,
    width: widget.UI.FIELD_WIDTH_CODE_20,    
  });
  C.cboDelegatedToUser = widget.UI.DBCombo("cboDelegatedToUser", {
    width: widget.UI.FIELD_WIDTH_CODE_20,
  });
  C.cboDelegatedToRole = widget.UI.DBCombo("cboDelegatedToRole", {
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  
  C.lblRepeat = widget.UI.Label("lblRepeat", {
    tooltipText: "",
  });
  C.chkRepeatUse = widget.UI.CheckBox("chkRepeatUse", {
    caption: "Will this Log repeat upon completion?",

    onChange: chkRepeatUse_Change,
  });
  C.cboRepeatBasis = widget.UI.ComboBox("cboRepeatBasis", {
    allowBlank: false,
    limitToList: true,
    width: "10em",
  });
  C.cboRepeatCycle = widget.UI.DateCycleComboBox("cboRepeatCycle", {
    allowBlank: false,
  });

  //   External Party
  C.lblExternalParty = widget.UI.Label("lblExternalParty", {});
  C.cboExternalParty = widget.UI.DBCombo("cboExternalParty", {
    width: widget.UI.FIELD_WIDTH_CODE_10,
  });
  
  //   Audit
  C.txtLogPk = widget.UI.TextBox("txtLogPk", {
    autoReadOnly: false,
    readOnly: true,
    width: "7em",
  });
  C.txtParentLogPk = widget.UI.TextBox("txtParentLogPk", {
    width: "7em",
  });
  C.txtSource = widget.UI.TextBox("txtSource", {
    autoReadOnly: false,
    readOnly: true,
    width: "20em",
  });
  
  C.lblServiceLog = widget.UI.Label("lblServiceLog", {});
  C.cboServiceLogPk = widget.UI.DBCombo("cboServiceLogPk", {
    autoReadOnly: false,
    readOnly: true,
    showDropdown: false,
    width: "7em",
  });
  
  C.lblFeeTransaction = widget.UI.Label("lblFeeTransaction", {});
  C.cboFeeAccountTransactionPk = widget.UI.DBCombo("cboFeeAccountTransactionPk", {
    autoReadOnly: false,
    hyperlinkContent: true,    
    readOnly: true,
    showDropdown: false,
    width: "7em",
    
    onContentHyperlink: function () { cmdFee_Click(); },    
  });
  C.cboAccountHistoryPk = widget.UI.DBCombo("cboAccountHistoryPk", {
    autoReadOnly: false,
    //hyperlinkContent: true,    
    readOnly: true,
    showDropdown: false,
    width: "7em",
  });

  C.lblWorkflow = widget.UI.Label("lblWorkflow", {});
  C.cboWorkflow = widget.UI.DBCombo("cboWorkflow", {
    width: widget.UI.FIELD_WIDTH_CODE_15,
    
    //onContentHyperlink: function () { cmdFee_Click(); },    
  });
  
  C.lblExtendedData = widget.UI.Label("lblExtendedData", {});
  C.trExtendedData = $("#trExtendedData");
  C.cmdExtendedData = $("#cmdExtendedData").click(function () { Form_ExecuteAction("ShowExtended_Extended"); });  
  C.cmdParameters = $("#cmdParameters").click(function () { Form_ExecuteAction("ShowExtended_Parameters"); });  
  C.cmdDocumentHtml = $("#cmdDocumentHtml").click(function () { Form_ExecuteAction("ShowExtended_Html"); });  
  C.cmdAccountData = $("#cmdAccountData").click(function () { Form_ExecuteAction("ShowExtended_AccountData"); });  
  C.cmdUserData = $("#cmdUserData").click(function () { Form_ExecuteAction("ShowExtended_UserData"); });  
  
  C.lblCreatedDetails = widget.UI.Label("lblCreatedDetails", {});
  C.divCreatedDetails = $("#divCreatedDetails");
  C.lblPublishDetails = widget.UI.Label("lblPublishDetails", {});
  C.divPublishDetails = $("#divPublishDetails");
  C.lblPrintedDetails = widget.UI.Label("lblPrintedDetails", {});
  C.divPrintedDetails = $("#divPrintedDetails");

  //   Summary
  C.wbSummary = widget.UI.PreviewPane("wbSummary", {});

  // Grids

  // 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",
    showBookmark: true,
    bookmarkEnabled: true,
    
    onBookmarkClick: function () { widget.UI.BookmarkToggleTabs(tabDetails, mRecord.RecordType, mRecord.Pk, mRecord.Pk, C.cboRecord.Text() + ": " + C.cboSubject.Text()); },
    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");
  cmdCompleteLog = $("#cmdCompleteLog");
  cmdReply = $("#cmdReply");
  cmdReplySms = $("#cmdReplySms");
  cmdReplyWebMail = $("#cmdReplyWebMail");
  cmdPrint_ServiceLog = $("#cmdPrint_ServiceLog");
  
  cmdCancel.click(tabDetails_Cancel);
  cmdFinish.click(Form_ExecuteAction_Finish);
  cmdCompleteLog.click(function () { Form_ExecuteAction("CompleteLog"); });
  cmdReply.click(function () { Form_ExecuteAction("Reply"); });
  cmdReplySms.click(function () { Form_ExecuteAction("ReplySms"); });
  cmdReplyWebMail.click(function () { Form_ExecuteAction("WebMailReply"); });
  cmdPrint_ServiceLog.click(function () { Form_ExecuteAction("Print_ServiceLog"); });

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

  // Global Collections
  mElements = mRecord.Elements;

  // Give Collections ability to lookup by code
  widget.ArrayAllowLookupById(mElements, "ElementId");
  
  // Never send Global Collections back
  mRecord.Elements = null;

  // Set Tab
  if (mPageId) {
    // After Publish has occurred
    tabDetails.SelectedTabId(mPageId);
  }
  else 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
  // NOTE: Many of these will be overridden in Fields_Update but are listed here for consistency with other forms
  if (!mRecord.AllowPageGeneral) tabDetails.TabVisible("General", false);
  if (!mRecord.AllowPageServiceLog) tabDetails.TabVisible("ServiceLog", false);
  if (!mRecord.AllowPageExtendedData) tabDetails.TabVisible("ExtendedData", false);
  if (!mRecord.AllowPageWebMail) tabDetails.TabVisible("WebMail", false);
  if (!mRecord.AllowPageDocument) tabDetails.TabVisible("Document", false);
  if (!mRecord.AllowPageFee) tabDetails.TabVisible("Fee", false);
  if (!mRecord.AllowPageFeeNew) tabDetails.TabVisible("FeeNew", false);
  if (!mRecord.AllowPageOther) tabDetails.TabVisible("Other", false);
  if (!mRecord.AllowPageExternalParty) tabDetails.TabVisible("ExternalParty", false);
  if (!mRecord.AllowPageAudit) tabDetails.TabVisible("Audit", false);
  if (!mRecord.AllowPageSummary) tabDetails.TabVisible("Summary", 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);
  
  // Define Actions
  Form_UpdateActions();
}

// ===========
// Load Fields
// ===========
function Fields_Load() {
  if (mRecord) {
    // General
    C.cboRecord.RefreshUnbound(mRecord.RecordId, mRecord.RecordDescription);
    switch (mRecord.LogObjectType) {
      case "AccountApp":
        C.cboRecordSub1.RefreshUnbound(mRecord.AccountAppApplicantPk, mRecord.AccountAppApplicantDescription);
        C.cboRecordSub2.RefreshUnbound(mRecord.AccountAppCollateralItemPk, mRecord.AccountAppCollateralItemDescription);
        break;

      case "SecurityStmtItem":
        C.cboRecordSub1.RefreshUnbound(mRecord.SecurityStmtItemPk, mRecord.SecurityStmtItemDescription);
        break;
    }
    
    C.dateLogDate.TimeZoneId(mRecord.LogTimeZoneId);
    C.dateLogDate.Value(mRecord.LogTzDate);
    C.cboLogSeverity.Text(mRecord.LogSeverityId);    
    C.cboSubject.Text(mRecord.Subject);
    C.txtNotes.Text(mRecord.Notes);
    C.txtReplyToLogNotes.Text(mRecord.ReplyToLogNotes);
    
    C.dateAction.TimeZoneId(mRecord.ActionTimeZoneId);
    C.dateAction.Value(mRecord.ActionTzDate);
    C.dateActionComplete.Value(mRecord.ActionCompleteTzDate);
    
    C.cboLogOutcome.Text(mRecord.LogOutcome);
    
    // Service Log
    if (mRecord.ServiceLogSummaryHtml) C.wbServiceLog.SetContent(mRecord.ServiceLogSummaryHtml, false);

    // Extended Data
    // NOTE: Deferred until pageExtendedData_Refresh() so 2-panel resize can occur correctly

    // Web Mail
    C.txtWebMailStatus.Text(mRecord.WebMailStatus);
    C.dateWebMailRead.TimeZoneId(mRecord.LogTimeZoneId); // Date Read is shown in Log Time Zone
    C.dateWebMailRead.Value(mRecord.WebMailReadTzDate);

    C.cboWebMailRelatedAccount.RefreshUnbound(mRecord.WebMailRelatedAccountId, mRecord.WebMailRelatedAccountName);
    C.cboWebMailRelatedAccountApp.RefreshUnbound(mRecord.WebMailRelatedAccountAppId, mRecord.WebMailRelatedAccountAppName);

    // Document
    C.cboDocumentFileName.Text(mRecord.DocumentFileName);
    C.txtDocumentBookmark.Text(mRecord.DocumentBookmark);
  
    C.cboDocument.RefreshUnbound(mRecord.DocumentId, mRecord.DocumentDescription);
    C.cboPublishStatus.Text(mRecord.PublishStatusText);
    C.cboDocumentSendEmail.Text(mRecord.DocumentSendEmailText);
    C.datePublishOnDate.TimeZoneId(mRecord.PublishOnTimeZoneId);
    C.datePublishOnDate.Value(mRecord.PublishOnTzDate);
    C.datePublishedDate.Value(mRecord.PublishedTzDate);
    C.datePublishFailDate.Value(mRecord.PublishFailDate);
    C.cboPublishResult.Text(mRecord.PublishResult);
  
    C.cboPrintStatus.Text(mRecord.PrintStatusText);
    C.datePrintedDate.TimeZoneId(mRecord.LogTimeZoneId);
    C.datePrintedDate.Value(mRecord.PrintedTzDate);
    
    // Fee &amp; Account Details
    C.numFee.Value(mRecord.Fee);
    if (mRecord.AccountDetailsSummaryHtml) C.wbAccountDetails.SetContent(mRecord.AccountDetailsSummaryHtml, false);
    
    // Charge Fee
    // NOTE: This uses the same mRecord.Fee property as the block above
    
    // Other    
    C.cboOwnerUser.Text(mRecord.OwnerUserId);
    C.cboDelegatedToUser.Text(mRecord.DelegatedToUserId);
    C.cboDelegatedToRole.Text(mRecord.DelegatedToRoleId);
    
    C.chkRepeatUse.Value(mRecord.RepeatUse);
    C.cboRepeatBasis.Text(mRecord.RepeatBasis);
    C.cboRepeatCycle.Text(mRecord.RepeatCycle);
    
    // External Party
    C.cboExternalParty.Text(mRecord.ExternalPartyId);
    
    // Audit
    C.txtLogPk.Text(mRecord.Pk);
    if (mRecord.ParentLogPk != 0) C.txtParentLogPk.Text(mRecord.ParentLogPk);
    C.txtSource.Text(mRecord.SourceText);
    
    C.cboServiceLogPk.RefreshUnbound(mRecord.ServiceLogPk, mRecord.ServiceLogDescription);
    
    C.cboFeeAccountTransactionPk.RefreshUnbound(mRecord.FeeAccountTransactionPk, "");
    C.cboAccountHistoryPk.RefreshUnbound(mRecord.AccountHistoryPk, "");
    
    C.cboWorkflow.Text(mRecord.WorkflowId);
    
    C.divCreatedDetails.html(mRecord.CreatedDetails);
    C.divPublishDetails.html(mRecord.PublishDetails);
    C.divPrintedDetails.html(mRecord.PrintedDetails);
    
    // Summary
    if (mRecord.SummaryHtml) C.wbSummary.SetContent(mRecord.SummaryHtml, false);
  }

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

  // Update Controls

  // Update fields
  Fields_Update();

  // Refresh Tab
  tabDetails_Refresh();
  tabDetails_Resize();
  
  // Auto-Print?
  if (mAutoPrint) {
    mAutoPrint = false;
    if (mRecord.PrintStatus == "ToPrint" || mRecord.PrintStatus == "Printed") {
      Form_ExecuteAction_DocumentPrint(true);
    }
  }
}

// ===========
// Save Fields
// ===========
function Fields_Save() {
  // General
  mRecord.LogTimeZoneId = C.dateLogDate.TimeZoneId();
  mRecord.LogTzDate = C.dateLogDate.Value();
  mRecord.LogSeverityId = C.cboLogSeverity.Text();  
  mRecord.Subject = C.cboSubject.Text();
  mRecord.Notes = C.txtNotes.Text();
  
  mRecord.ActionTimeZoneId = C.dateAction.TimeZoneId();
  mRecord.ActionTzDate = C.dateAction.Value();
  //mRecord.ActionUtcDateIsBlank = !mRecord.ActionTzDate; // Allow date to be cleared
  mRecord.ActionCompleteTzDate = C.dateActionComplete.Value();
  //mRecord.ActionCompleteUtcDateIsBlank = !mRecord.ActionCompleteTzDate; // Allow date to be cleared
  
  mRecord.LogOutcome = C.cboLogOutcome.Text();
  
  // Document
  if (C.cboDocumentFileName.IsNewFile()) {
    mRecord.DocumentFileName = "";
  }
  else {
    mRecord.DocumentFileName = C.cboDocumentFileName.Text();
  }
  mRecord.DocumentBookmark = C.txtDocumentBookmark.Text();

  mRecord.PublishStatusText = C.cboPublishStatus.Text();
  mRecord.PublishOnTimeZoneId = C.datePublishOnDate.TimeZoneId();
  mRecord.PublishOnTzDate = C.datePublishOnDate.Value();
  mRecord.DocumentSendEmailText = C.cboDocumentSendEmail.Text();
  mRecord.PublishFailDate = C.datePublishFailDate.Value();
  mRecord.PublishResult = C.cboPublishResult.Text();
  mRecord.PrintStatusText = C.cboPrintStatus.Text();
  
  // Fee &amp; Account Details
  mRecord.Fee = C.numFee.Value();
  
  // Charge Fee
  // NOTE: This uses the same mRecord.Fee property as the block above
  if (C.chkChargeLogFee.Value()) {
    mRecord.ChargeFee = true;
    mRecord.FeeElementId = C.cboLogFeeElement.Text();
    mRecord.Fee = C.numLogFee.Value();
    mRecord.FeeReference = C.txtLogFeeReference.Text();
    mRecord.FeeNotes = C.txtLogFeeNotes.Text();
  }
  
  // Other
  mRecord.OwnerUserId = C.cboOwnerUser.Text();
  mRecord.DelegatedToUserId = C.cboDelegatedToUser.Text();
  mRecord.DelegatedToRoleId = C.cboDelegatedToRole.Text();
  
  mRecord.RepeatUse = C.chkRepeatUse.Value();
  mRecord.RepeatBasis = C.cboRepeatBasis.Text();
  mRecord.RepeatCycle = C.cboRepeatCycle.Text();
  
  // External Party
  mRecord.ExternalPartyId = C.cboExternalParty.Text();
  
  // Audit
  if (C.txtParentLogPk.Text() == "") {
    mRecord.ParentLogPk = 0;
  }
  else {
    mRecord.ParentLogPk = parseInt(C.txtParentLogPk.Text());
  }
  mRecord.WorkflowId = C.cboWorkflow.Text();
}

// =============
// Update Fields
// =============
function Fields_Update() {
  // Heading
  var heading;
  if (mRecord) {
    if (mRecord.Pk == 0) {
      // New record
      if (mRecord.LogType == "WebMailToClient") {
        heading = "New Web Mail to Client";
      }
      else {
        heading = "New " + mRecord.ObjectNameFriendly + " Log";
      }
    }
    else {
      switch (mRecord.LogType) {
        case "WebMailFromClient":
          heading = "Web Mail from Client";
          break;

        case "WebMailToClient":
          heading = "Web Mail to Client";
          break;
          
        default:
          heading = mRecord.ObjectNameFriendly + " Log";
          break;
      }
    }
  }
  if (mRecord.ReplyToLogPk) {
    switch (mRecord.LogType) {
      case "WebMailToClient":
        heading += " (Reply to Web Mail)";
        break;

      default:
        heading += " (Reply)";
        break;
    }
  }
  else {
    if (mRecord.Pk != 0) heading += " (#" + mRecord.Pk + ")";
  }
  widget.SetHeading(heading);
  
  // Icon
  if (mRecord &amp;&amp; mRecord.Icon) widget.SetHeadingIcon(mRecord.Icon);
  
  // Bookmarked?
  tabDetails.Bookmarked(mRecord &amp;&amp; mRecord.Bookmarked);
  tabDetails.BookmarkVisible(mRecord &amp;&amp; mRecord.Pk &gt; 0);
  tabDetails.BookmarkEnabled(mRecord &amp;&amp; !mRecord.DatabaseReadOnly);

  // Information Lists
  if (mRecord) {
    C.cboSubject.SetComboFromInformationList(mRecord.SubjectInformationListId, false, cboSubject_Change);
    //C.cboLogOutcome.SetComboFromInformationList(""); // Must rebuild Log Outcomes list once initialised since this is based on the Subject
  }

  // Lists
  if (mRecord) {
    // General
    C.cboLogSeverity.RefreshFromStandardRange("LogSeverities");    
    // Charge Fee
    if (mRecord.AllowPageFeeNew) {
      C.cboLogFeeElement.RefreshFromStandardRange("ElementsFee");
    }
    
    // Other
    if (mRecord.AllowPageOther) {
      C.cboOwnerUser.RefreshFromStandardRange("Users", "", false, mRecord.OwnerUserId, "UserId,Name,Active");
      C.cboDelegatedToUser.RefreshFromStandardRange("Users", "", false, mRecord.DelegatedToUserId, "UserId,Name,Active");
      C.cboDelegatedToRole.RefreshFromStandardRange("Roles");
      C.cboRepeatBasis.ListFromCsvString(mRecord.LogRepeatBasisList);
      C.cboRepeatCycle.ListFromCsvString(mRecord.LogRepeatCycleList);
    }
    
    // External Party
    if (mRecord.AllowPageExternalParty) {
      C.cboExternalParty.RefreshFromStandardRange("ExternalParties", mRecord.ExternalPartyFilter);
    }
    
    // Audit
    if (mRecord.AddOnsWorkflow) {
      C.cboWorkflow.RefreshFromStandardRange("Workflows");
    }
  }

  // Controls
  if (mRecord) {
    if (mRecord.ReplyToLogNotes) {
      C.trReplyToLogNotes.show();
    }
    else {
      C.trReplyToLogNotes.hide();
    }
  
    if (mRecord.PrioritiseOwnerAndDelegated) {
      // Owner and Delegated
      $("#trOwnerUser1").detach().insertBefore("#trAction");
      $("#trOwnerUser2").detach().insertBefore("#trAction");
      $("#trOwnerUser3").detach().insertBefore("#trAction");
      $("#trOwnerUser4").detach().insertBefore("#trAction");
    }
    if (mRecord.PrioritiseOwnerAndDelegated) {
      // Hide "Other" tab
      tabDetails.TabVisible("Other", false);
    }
    
    // Log Type-specific
    switch (mRecord.LogType) {
      case "Audit":
      case "AuditChange":
      case "AuditSecurity":
        // Audit
        C.dateLogDate.ReadOnly(true);
        C.cboSubject.ReadOnly(true);
        C.txtNotes.ReadOnly(true);
        break;
    
      case "Document":
      case "DocumentEmail":
      case "DocumentSms":
        // Document
        C.dateLogDate.ReadOnly(true);
        C.tbDocumentPublication.show();
        C.numFee.ReadOnly(!mRecord.CanUpdateFee);
        break;

      case "NormalUser":
        // Normal User
        break;

      case "Service":
        // Service
        C.dateLogDate.ReadOnly(true);
        break;

      case "WebMailFromClient":
      case "WebMailFromClientArchived":
      case "WebMailToClient":
      case "WebMailToClientArchived":
        // Web Mail
        C.dateLogDate.ReadOnly(true);
        break;

      default:
        console.warn("Unhandled LogType in Fields_Update");
    }
    
    // General
    switch (mRecord.LogObjectType) {
      case "Account":
        C.cboRecord.Caption("Account:");
        break;

      case "AccountApp":
        C.cboRecord.Caption("Application:");
        C.cboRecordSub1.Caption("Applicant:");
        C.cboRecordSub2.Caption("Collateral:");
        break;

      case "Client":
        C.cboRecord.Caption("Client:");
        break;

      case "SecurityStmt":
        C.cboRecord.Caption("Statement:");
        C.cboRecordSub1.Caption("Item:");
        break;

      case "SecurityStmtItem":
        C.cboRecord.Caption("Statement:");
        break;

      case "User":
        C.cboRecord.Caption("User:");
        break;

      default:
        window.alert("Object Type '" + mObjectType + "' not handled!");
        break;
    }
    if (!mRecord.CanUpdateNotes) C.txtNotes.ReadOnly(true);
    
    // Extended Data
    if (!mRecord.ExtendedDataSummaryHtml2) {
      $("#wbExtendedData").css("flex-grow", "1");
      C.wbExtendedData2.Visible(false);
    }
    
    // Document
    var itemId;
    switch (mRecord.LogObjectType) {
      case "SecurityStmtItem":
        itemId = mRecord.SecurityStmtItemPk;
        break;
        
      default:
        itemId = mRecord.RecordId;
        break;
    }
    C.cboDocumentFileName.Refresh(mRecord.LogObjectType, itemId, { fileTypes: "*" });
    C.cmdUnpublish.Visible(mRecord.CanUnpublish);
    
    // Other
    if (!mRecord.CanUpdateOwnerUser) C.cboOwnerUser.ReadOnly(true);
    if (!mRecord.CanUpdateDelegatedToUser) C.cboDelegatedToUser.ReadOnly(true);
    if (!mRecord.CanUpdateDelegatedToRole) C.cboDelegatedToRole.ReadOnly(true);
    if (!mRecord.CanRepeat) {
      C.lblRepeat.VisibleRow(false);
      C.chkRepeatUse.VisibleRow(false);
      C.cboRepeatBasis.VisibleRow(false);
      C.cboRepeatCycle.VisibleRow(false);
    }
    else {
      chkRepeatUse_Change();
    }
    
    // Service Log page
    if (mRecord.ServiceLogPageTitle) {
      tabDetails.TabCaption("ServiceLog", mRecord.ServiceLogPageTitle);
      tabDetails.TabVisible("ServiceLog", true);
    }
    else {
      tabDetails.TabVisible("ServiceLog", false);
    }
    
    // Extended Data page
    if (mRecord.ExtendedDataPageTitle) {
      tabDetails.TabCaption("ExtendedData", mRecord.ExtendedDataPageTitle);
      tabDetails.TabVisible("ExtendedData", true);
    }
    else {
      tabDetails.TabVisible("ExtendedData", false);
    }
 
    // Fee &amp; Account Details page
    tabDetails.TabVisible("FeeNew", false);
    switch (mRecord.LogObjectType) {
      case "Account":
        if (mRecord.Pk &lt;= 0) {
          // New Logs can charge a Fee via a special page
          tabDetails.TabVisible("Fee", false);
          tabDetails.TabVisible("FeeNew", mRecord.CanChargeFee);
        }
        else if (mRecord.HasAccountData &amp;&amp; (mRecord.HasFee || mRecord.DocumentFeeElementPk)) {
          tabDetails.TabCaption("Fee", "Fee &amp; Details");
          tabDetails.TabVisible("Fee", true);
        }
        else if (mRecord.HasAccountData) {
          C.lblFeeCharged.VisibleRow(false);
          C.numFee.VisibleRow(false);
          C.trAccountDetails.addClass("first"); // Remove top padding from label (cannot achieve in CSS alone)
          tabDetails.TabCaption("Fee", "Account Details");
          tabDetails.TabVisible("Fee", true);
        }
        else if (mRecord.HasFee || mRecord.DocumentFeeElementPk) {
          C.trAccountDetails.hide();
          C.trAccountDetailsPreview.hide();
          C.tblFee.css("height", "auto"); // Remove 100% height
          tabDetails.TabCaption("Fee", "Fee");
          tabDetails.TabVisible("Fee", true);
        }
        else {
          tabDetails.TabVisible("Fee", false);
        }

        if (mRecord.FeeAccountTransactionPk &amp;&amp; mRecord.CanViewFeeTransaction) {
          C.cmdFee.show();
        }
        else {
          C.cmdFee.hide();
        }
        break;

      default:
        tabDetails.TabVisible("Fee", false);
        break;
    }
     
    // Charge Fee
    chkChargeLogFee_Change();

    // External Party
    C.cboExternalParty.AllowBlank(!mRecord.ExternalPartyMandatory);
    
    // Audit
    if (!mRecord.ServiceLogPk) {
      C.lblServiceLog.VisibleRow(false);
      C.cboServiceLogPk.VisibleRow(false);
    }
    if (!mRecord.AddOnsWorkflow) {
      C.lblWorkflow.VisibleRow(false);
      C.cboWorkflow.VisibleRow(false);
    }
    if (!mRecord.FeeAccountTransactionPk &amp;&amp; !mRecord.FeeAccountTransactionPk) {
      C.lblFeeTransaction.VisibleRow(false);
    }
    if (!mRecord.FeeAccountTransactionPk) C.cboFeeAccountTransactionPk.VisibleRow(false);
    if (!mRecord.AccountHistoryPk) C.cboAccountHistoryPk.VisibleRow(false);
    
    if (!mRecord.CreatedDetails) {
      C.lblCreatedDetails.VisibleRow(false);
      C.divCreatedDetails.hide();
    }

    if (mRecord.AllowViewExtended ||
        mRecord.AllowViewParameters ||
        mRecord.AllowViewHtml ||
        mRecord.AllowViewAccountData ||
        mRecord.AllowViewUserData) {
      if (!mRecord.AllowViewExtended) C.cmdExtendedData.hide();
      if (!mRecord.AllowViewParameters) C.cmdParameters.hide();
      if (!mRecord.AllowViewHtml) C.cmdDocumentHtml.hide();
      if (!mRecord.AllowViewAccountData) C.cmdAccountData.hide();
      if (!mRecord.AllowViewUserData) C.cmdUserData.hide();
    }
    else {
      C.lblExtendedData.VisibleRow(false);
      C.trExtendedData.hide();
    }
        
    if (!mRecord.PublishDetails) {
      C.lblPublishDetails.VisibleRow(false);
      C.divPublishDetails.hide();
    }

    if (!mRecord.PrintedDetails) {
      C.lblPrintedDetails.VisibleRow(false);
      C.divPrintedDetails.hide();
    }
    
    // Object Type Specific
    switch (mRecord.LogObjectType) {
      case "Account":
        C.cboRecordSub1.VisibleRow(false);
        C.cboRecordSub2.VisibleRow(false);
        break;

      case "AccountApp":
        C.cboRecordSub1.VisibleRow(mRecord.AccountAppApplicantPk != 0);
        C.cboRecordSub2.VisibleRow(mRecord.AccountAppCollateralItemPk != 0);
        break;

      case "Client":
        C.cboRecordSub1.VisibleRow(false);
        C.cboRecordSub2.VisibleRow(false);
        break;

      case "SecurityStmt":
        C.cboRecordSub1.VisibleRow(false);
        C.cboRecordSub2.VisibleRow(false);
        break;

      case "SecurityStmtItem":
        C.cboRecordSub1.Caption("Item:");
        C.cboRecordSub1.VisibleRow(true);
        C.cboRecordSub2.VisibleRow(false);
        break;

      case "User":
        C.cboRecordSub1.VisibleRow(false);
        C.cboRecordSub2.VisibleRow(false);
        break;

      default:
        window.alert("Fields_Update: Log Object Type '" + mObjectType + "' not handled!");
        break;
    }
  }

  // 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();
    pageExtendedData_Refresh();
    pageWebMail_Refresh();
    pageDocument_Refresh();
    pageFee_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.cboRecord.WidthResizeFromParent();
      C.cboRecordSub1.WidthResizeFromParent();
      C.cboRecordSub2.WidthResizeFromParent();
      C.cboLogSeverity.WidthResizeFromParent();      
      C.cboSubject.WidthResizeFromParent(true);
      C.txtNotes.ResizeFromParent();
      C.cboLogOutcome.WidthResizeFromParent(true);
      break;
      
    case "WebMail":
      C.cboWebMailRelatedAccount.WidthResizeFromParent();
      C.cboWebMailRelatedAccountApp.WidthResizeFromParent();
      break;

    case "Document":
      C.cboDocumentFileName.WidthResizeFromParent(true);
      C.txtDocumentBookmark.WidthResizeFromParent(true);
      C.cboDocument.WidthResizeFromParent();
      C.cboPublishResult.WidthResizeFromParent(true);
      break;
      
    case "Fee":
      if (mRecord.HasAccountData) C.wbAccountDetails.ResizeFromParent();
      break;
      
    case "FeeNew":
      C.txtLogFeeReference.WidthResizeFromParent();
      C.txtLogFeeNotes.WidthResizeFromParent();
      break;
      
    case "Other":
      C.cboOwnerUser.WidthResizeFromParent();
      C.cboDelegatedToUser.WidthResizeFromParent();
      C.cboDelegatedToRole.WidthResizeFromParent();
      break;
  }
}

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

    case "Document":
      pageDocument_Refresh();

    case "Fee":
      pageFee_Refresh();

    default:
      break;
  }

  // Page-specific
  switch(tabDetails.SelectedTabId()) {
    case "ServiceLog":
    cmdPrint_ServiceLog.text("Print " + mRecord.ServiceLogPageTitle);
      cmdPrint_ServiceLog.show();
      break;
      
    default:
      cmdPrint_ServiceLog.hide();
  }

  // Resize
  tabDetails_Resize();

  // Focus
  switch (tabDetails.SelectedTabId()) {
    case "General":
      C.cboSubject.Focus();
      break;
      
    default:
      tabDetails.FocusFirst();
      break;
  }
}

// ===============
// Refresh Actions
// ===============
function Form_UpdateActions() {
  // Define Actions
  var actions = [];

  if (!mRecord.ReadOnly &amp;&amp; mRecord.CanDelete) actions.push({ groupId: "Record", actionId: "Delete", caption: "Delete", icon: "Delete" });
  if (mRecord.CanPrintLogDetails) actions.push({ groupId: "Record", actionId: "Print", caption: "Print", icon: "Print" });
  
  if (!mRecord.ReadOnly &amp;&amp; mRecord.Pk &gt; 0) actions.push({ groupId: "Reply", actionId: "Reply", caption: "Reply", icon: "Log_Reply" });
  if (!mRecord.ReadOnly &amp;&amp; mRecord.Pk &gt; 0 &amp;&amp; mRecord.SupportsReplyViaSms) actions.push({ groupId: "Reply", actionId: "ReplySms", caption: "Reply via SMS", icon: "Sms|Reply" });
  
  if (mRecord.CanPublish) actions.push({ groupId: "Document", actionId: "Publish", caption: "Publish", icon: "Logs_Publish" });
  if (mRecord.CanUnpublish) actions.push({ groupId: "Document", actionId: "Unpublish", caption: "Unpublish", icon: "Logs_Publish|Undo" });
  if (mRecord.CanPrint) actions.push({ groupId: "Document", actionId: "DocumentPrint", caption: "Print Document", icon: "Document|Print"});
  
  if (!mRecord.ReadOnly &amp;&amp; mRecord.Pk &gt; 0 &amp;&amp; mRecord.LogType.startsWith("WebMail")) {
    if (mRecord.LogType == "WebMailFromClient" || mRecord.LogType == "WebMailFromClientArchived") actions.push({ groupId: "Web Mail", actionId: "WebMailReply", caption: "Reply to Web Mail", icon: "Webmail_Reply" });
    if (mRecord.LogType == "WebMailToClient" &amp;&amp; !mRecord.PublishedTzDate) actions.push({ groupId: "Web Mail", actionId: "WebMailRead", caption: "Mark as Read", icon: "Mail_Read" });
    if (mRecord.LogType == "WebMailToClient" &amp;&amp; mRecord.PublishedTzDate) actions.push({ groupId: "Web Mail", actionId: "WebMailUnread", caption: "Mark as Unread", icon: "Mail_Unread" });
    if (mRecord.LogType != "WebMailToClientArchived" &amp;&amp; mRecord.LogType != "WebMailFromClientArchived") actions.push({ groupId: "Web Mail", actionId: "WebMailArchive", caption: "Archive", icon: "Archive" });
    if (mRecord.LogType == "WebMailToClientArchived" || mRecord.LogType == "WebMailFromClientArchived") actions.push({ groupId: "Web Mail", actionId: "WebMailUnarchive", caption: "Unarchive", icon: "Archive_Undo" });
  }

  frmMain.ActionsDefine(actions, "cmdActions", Form_ExecuteAction);
  
  // Button Actions
  if (!mRecord.ReadOnly &amp;&amp; mRecord.Pk &gt; 0 &amp;&amp; C.dateAction.Value() &amp;&amp; !C.dateActionComplete.Value()) {
    cmdCompleteLog.show();
  }
  else {
    cmdCompleteLog.hide();
  }
  if (!mRecord.ReadOnly &amp;&amp; mRecord.Pk &gt; 0) {
     cmdReply.show();
  }
  else {
    cmdReply.hide();
  }
  if (!mRecord.ReadOnly &amp;&amp; mRecord.Pk &gt; 0 &amp;&amp; mRecord.SupportsReplyViaSms) {
     cmdReplySms.show();
  }
  else {
    cmdReplySms.hide();
  }
  if (!mRecord.ReadOnly &amp;&amp; (mRecord.LogType == "WebMailFromClient" || mRecord.LogType == "WebMailFromClientArchived")) {
    cmdReplyWebMail.show();
  }
  else {
    cmdReplyWebMail.hide();
  }
}

// =================
// Execute an Action
// =================
function Form_ExecuteAction(actionId, data) {
  switch (actionId.toUpperCase()) {
    case "COMPLETELOG":
      // Save &amp; Complete
      Form_ExecuteAction_FinishPost(true);
      break;
      
    case "DELETE":
      // Delete
      var params = {};
      Form_ExecuteAction_Delete(0, params);
      break;

    case "DOCUMENTPRINT":
      // Print Document
      Form_ExecuteAction_DocumentPrint();
      break;

    case "PRINT":
      // Print (Log Details)
      widget.ExecuteApplicationShortcutUrl("app://Report?reportId=" + mRecord.LogObjectType + "LogDetails&amp;primaryRangeName=Logs&amp;primaryRange=" + mRecord.Pk);
      break;

    case "PRINT_SERVICELOG":
      // Print Service Log
      C.wbServiceLog.Print();
      break;

    case "PUBLISH":
      // Publish
      Form_ExecuteAction_Publish();
      break;

    case "REPLY":
      // Reply
      widget.ExecuteApplicationShortcutUrl(mRecord.ReplyApplicationShortcutUrl);
      break;

    case "REPLYSMS":
      // Reply via SMS
      widget.ExecuteApplicationShortcutUrl(mRecord.ReplySmsApplicationShortcutUrl);
      break;
      
    case "SHOWEXTENDED_EXTENDED":
    case "SHOWEXTENDED_PARAMETERS":
    case "SHOWEXTENDED_HTML":
    case "SHOWEXTENDED_ACCOUNTDATA":
    case "SHOWEXTENDED_USERDATA":
      // Show Extended
      Form_ExecuteAction_ShowExtended(actionId.substr(13));
      break;

    case "SHOWMAINRECORD":
      // Show Main Record
      widget.Minimise();      
      widget.ExecuteApplicationShortcutUrl("app://formshow?form=" + mRecord.LogObjectType + "&amp;id=" + encodeURIComponent(mRecord.RecordId));
      break;

    case "UNPUBLISH":
      // Unpublish
      Form_ExecuteAction_Unpublish();
      break;

    case "WEBMAILREPLY":
      // Web Mail Reply
      widget.ExecuteApplicationShortcutUrl(mRecord.WebMailReplyApplicationShortcutUrl);
      break;
    
    case "WEBMAILARCHIVE":
      // Archive
      Form_ExecuteAction_WebMailAction("Archive", "archive this Web Mail Log so the Client can no longer view it", "Archive Web Mail Log");
      break;

    case "WEBMAILUNARCHIVE":
      // Unarchive
      Form_ExecuteAction_WebMailAction("Unarchive", "unarchive this Web Mail Log", "Unarchive Web Mail Log");
      break;

    case "WEBMAILREAD":
      // Mark as Read
      Form_ExecuteAction_WebMailAction("Read", "flag this Web Mail Log as having been read", "Flag Web Mail as Read");
      break;

    case "WEBMAILUNREAD":
      // Mark as Unread
      Form_ExecuteAction_WebMailAction("Unread", "flag this Web Mail Log as unread", "Flag Web Mail as Unread");
      break;
  
    default:
      window.alert("Unhandled action '" + actionId + "'");
  }
}

// =============
// Delete Action
// =============
function Form_ExecuteAction_Delete(checkIndex, params) {
  // Chained confirmations
  switch (checkIndex) {
    case 0:
      // Child Logs Confirmation
      if (mRecord.ChildLogCount != 0) {
        widget.UI.MsgBoxConfirm("This Log has child Logs linked to it as part of the same thread.\n\nDo you want to delete related child Logs?", { heading: "Delete Child Logs", captionOk: "Yes", captionCancel: "No" },
          function () {
            // Yes
            params.deleteChildLogs = true;
            Form_ExecuteAction_Delete(checkIndex + 1, params);
          },

          function () {
            // No
            Form_ExecuteAction_Delete(checkIndex + 1, params);
          });

        return;
      }
      break;

    case 1:
      // Service Log Warning
      if (mRecord.HasServiceLogs) {
        var msg;
        if (params.deleteChildLogs) {
          msg = "WARNING: One or more of the Logs you are about to delete has a related Service Log.\n\nService Log information will not be deleted.\n\nContinue?";
        }
        else {
          msg = "WARNING: The Log you are about to delete has a related Service Log.\n\nService Log information will not be deleted.\n\nContinue?";
        }

        widget.UI.MsgBoxConfirm(msg, { heading: "Service Logs Exist", icon: "Warning" }, function () { Form_ExecuteAction_Delete(checkIndex + 1, params); });

        return;
      }
      break;

    case 2:
      // File Confirmation
      if (mRecord.HasDeletableDocuments) {
        var msg;
        if (params.deleteChildLogs) {
          msg = "One or more of the Logs you are about to delete has a Document.\n\nDo you want to delete the related Files?";
        }
        else {
          msg = "The Log you are about to delete has a Document.\n\nDo you want to delete the related File?"
        }

        widget.UI.MsgBoxConfirm(msg, { heading: "Delete Files", captionOk: "Yes", captionCancel: "No" },
          function () {
            // Yes
            params.deleteFiles = true;
            Form_ExecuteAction_Delete(checkIndex + 1, params);
          },

          function () {
            // No
            Form_ExecuteAction_Delete(checkIndex + 1, params);
          });

        return;
      }
      break;

    case 3:
      // Final Confirmation
      var msg;
      if (params.deleteChildLogs) {
        msg = "Are you sure you want to PERMANENTLY delete this Log record and all of its child Logs?";
      }
      else {
        msg = "Are you sure you want to PERMANENTLY delete this Log record?";
      }
      if (params.deleteFiles) msg += "\n\nNOTE: Linked files will also be deleted.";

      widget.UI.MsgBoxConfirmDelete(msg, {}, function () { Form_ExecuteAction_DeletePost(params); }, null);
      return;
  }

  // No prompt so just move on to the next confirmation
  Form_ExecuteAction_Delete(checkIndex + 1, params);
}

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

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

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

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

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

// =====================
// Document Print Action
// =====================
function Form_ExecuteAction_DocumentPrint(afterPublish) {
  // Validate
  if (C.cboDocumentFileName.IsNewFile()) {
    if (!afterPublish) widget.UI.MsgBoxAlert("You cannot print a Document File that has not yet been uploaded.\n\nSave this Log and try again.");
    return;
  }
  else if (!C.cboDocumentFileName.Text()) {
    if (!afterPublish) widget.UI.MsgBoxAlert("There is no Document File Name specified.");
    return;
  }
  
  // Confirm?
  if (C.cboPrintStatus.Text() != "To Print") {
    Form_ExecuteAction_DocumentPrint_Execute(false);
  }
  else {
    var msg;
    if (afterPublish) {
      msg = "Download a copy of this document and update the Print Status to 'Printed'?";
    }
    else {
      msg = "Update the Print Status to 'Printed' and immediately save this Log prior to downloading the document?";
    }
    
    widget.UI.MsgBoxConfirm(msg, { heading: "Download Document", captionCancel: "No", captionOk: "Yes" },
      function () {
        // Yes
        Form_ExecuteAction_FinishPost(false, true);
      },

      function () {
        // No
        if (afterPublish) {
          // No means not to procede
        }
        else {
          Form_ExecuteAction_DocumentPrint_Execute();
        }
      }
    );
  }
}

function Form_ExecuteAction_DocumentPrint_Execute() {
  // Print Document
  var url;
  
  switch (mRecord.LogObjectType) {
    case "SecurityStmtItem":
      url = "app://DocumentManagerFile?itemType=" + mRecord.LogObjectType + "&amp;itemPk=" + encodeURIComponent(mRecord.SecurityStmtItemPk) + "&amp;fileName=" + encodeURIComponent(C.cboDocumentFileName.Text());
      break;
      
    default:
      url = "app://DocumentManagerFile?itemType=" + mRecord.LogObjectType + "&amp;itemId=" + encodeURIComponent(mRecord.RecordId) + "&amp;fileName=" + encodeURIComponent(C.cboDocumentFileName.Text());
      break;
  }
  
  widget.ExecuteApplicationShortcutUrl(url);
}


// =============
// 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(complete, printed) {
  // 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));
  
  // Add special 'Complete' parameter
  if (complete === true) params.Complete = true; else params.Complete = false;

  // Add special 'Printed' parameter
  if (printed === true) params.Printed = true; else params.Printed = false;
  
  // Finish
  // NOTE: We must use UploadFiles rather than GetString to ensure that any new Image File is uploaded
  widget.UploadFiles("Finish", params, C.cboDocumentFileName.GetFileData(),
    function (data) {
      // Close Form/ Callback
      if (printed) {
        // Reset Form
        mAutoPrint = true
        Form_Reset();
      }
      else {
        // Close Form
        widget.Close();      
        
        // Other Notifications
        switch (mRecord.LogObjectType) {
          case "Account":
            widget.ActionNotificationSend("AccountLogsRefresh", { accountId: mRecord.RecordId }, null, true);
            break;
  
          case "AccountApp":
            widget.ActionNotificationSend("AccountAppLogsRefresh", { accountAppId: mRecord.RecordId }, null, true);
            break;
  
          case "Client":
            widget.ActionNotificationSend("ClientLogsRefresh", { clientId: mRecord.RecordId }, null, true);        
            break;
  
          case "SecurityStmt":
          case "SecurityStmtItem":
            widget.ActionNotificationSend("SecurityStmtLogsRefresh", { securityStmtId: mRecord.RecordId }, null, true);
            break;
            
          case "User":
            widget.ActionNotificationSend("UserLogsRefresh", { userId: mRecord.RecordId }, null, true);        
            break;
        }
      }

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

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

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

// ==============
// Publish Action
// ==============
function Form_ExecuteAction_Publish() {
  var msg = "&lt;p&gt;Are you sure you want to publish this Log?&lt;/p&gt;";
  if (Form_IsDirty()) msg += "&lt;div class='is-info-text warning'&gt;&lt;b&gt;WARNING:&lt;/b&gt; Any changes you have made to this Log since opening this form will be lost.&lt;/div&gt;";
  widget.UI.MsgBoxConfirm(msg, { heading: "Publish Log", messageIsHtml: true }, Form_ExecuteAction_PublishPost);
}

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

  // Publish
  widget.GetString("Publish", {},
    function (data) {
      // Notify
      //TODO:
      //NotifyLogUpdated(true);

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

      // Auto-Print
      mAutoPrint = true;
      
      // Reload
      mPageId = "Document";
      Form_Reset();
      
      // Refresh Parent (to show updated details)
      //widget.RefreshParent();
    },

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

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

// ================
// Unpublish Action
// ================
function Form_ExecuteAction_Unpublish() {
  var msg = "&lt;p&gt;Are you sure you want to unpublish this Log?&lt;/p&gt;&lt;p&gt;Republishing a Log will regenerate the Document.&lt;/p&gt;";
  if (Form_IsDirty()) msg += "&lt;div class='is-info-text warning'&gt;&lt;b&gt;WARNING:&lt;/b&gt; Any changes you have made to this Log since opening this form will be lost.&lt;/div&gt;";
  widget.UI.MsgBoxConfirm(msg, { heading: "Unpublish Log", messageIsHtml: true }, Form_ExecuteAction_UnpublishPost);
}

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

  // Delete
  widget.GetString("Unpublish", {},
    function (data) {
      // Notify
      //TODO:
      //NotifyLogUpdated(true);

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

      // Reload
      mPageId = "Document";
      Form_Reset();
      
      // Refresh Parent (to show updated details)
      //widget.RefreshParent();
    },

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

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

// ===============
// Web Mail Action
// ===============
function Form_ExecuteAction_WebMailAction(action, description, title) {

  var msg = "&lt;p&gt;Are you sure you want to " + description + "?&lt;/p&gt;";
  if (Form_IsDirty()) msg += "&lt;div class='is-info-text warning'&gt;&lt;b&gt;WARNING:&lt;/b&gt; Any changes you have made to this Log since opening this form will be lost.&lt;/div&gt;";
  widget.UI.MsgBoxConfirm(msg, { heading: title, messageIsHtml: true }, function () { Form_ExecuteAction_WebMailActionPost(action); });
}

function Form_ExecuteAction_WebMailActionPost(action) {
  // Disable Form
  widget.UI.Block("Actioning Web Mail, please wait...");

  // Delete
  widget.GetString("WebMailAction", { action: action },
    function (data) {
      // Notify
      //TODO:
      //NotifyLogUpdated(true);

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

      // Reload
      mPageId = "WebMail";
      Form_Reset();
      
      // Refresh Parent (to show updated details)
      //widget.RefreshParent();
    },

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

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

// =====================
// Show Extended Actions
// =====================
function Form_ExecuteAction_ShowExtended(extendedType) {
  // Disable Form
  widget.UI.Block("Fetching extended data, please wait...");

  // Get Extended Data
  widget.GetString("GetExtendedData", { extendedType: extendedType },
    function (data) {
      // Enable Form
      widget.UI.Unblock();
      
      // Show Extended Data
      var title = "???";
      switch(extendedType) {
        case "AccountData":
          title = "Account Data";
          break;

        case "Extended":
          title = "Extended Data";
          break;

        case "Html":
          title = "Document HTML";
          break;
      
        case "Parameters":
          title = "Parameters";
          break;
          
        case "UserData":
          title = "User Data";
          break;
      }
      widget.UI.Forms.ShowHtml(title, data);
    },

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

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

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

  // Controls
}

// ================
// pageExtendedData
// ================
function pageExtendedData_Refresh() {
  if (!mRecord) return;

  if (mRecord.ExtendedDataSummaryHtml) C.wbExtendedData.SetContent(mRecord.ExtendedDataSummaryHtml, false);
  if (mRecord.ExtendedDataSummaryHtml2) C.wbExtendedData2.SetContent(mRecord.ExtendedDataSummaryHtml2, false);
}

// ===========
// pageWebMail
// ===========
function pageWebMail_Refresh() {

  C.dateWebMailRead.VisibleRow(mRecord.WebMailReadTzDate != null);

  if (mRecord.WebMailRelatedAccountId || mRecord.WebMailRelatedAccountAppId) {
    C.lblWebMailRelated.VisibleRow(true);
    if (mRecord.WebMailRelatedAccountId) {
      C.cboWebMailRelatedAccount.VisibleRow(true);
    }
    else {
      C.cboWebMailRelatedAccount.VisibleRow(false);
    }
    if (mRecord.WebMailRelatedAccountAppId) {
      C.cboWebMailRelatedAccountApp.VisibleRow(true);
    }
    else {
      C.cboWebMailRelatedAccountApp.VisibleRow(false);
    }
  }
  else {
    C.lblWebMailRelated.VisibleRow(false);
    C.cboWebMailRelatedAccount.VisibleRow(false);
    C.cboWebMailRelatedAccountApp.VisibleRow(false);
  }
}

// ============
// pageDocument
// ============
function pageDocument_Refresh(sender, e) {
  // Handled (if called directly from a control's handler)
  if (e) e.ChangeHandled = true;
  
  // Print Button
  var buttons = [];
  if (mRecord.CanPrint) buttons.push({id: "DocumentPrint", icon: "Print"});
  C.cboDocumentFileName.ButtonsDefine(buttons);

  // Initialise
  var IsDocumentLog = (mRecord &amp;&amp; (mRecord.LogType == "Document" || mRecord.LogType == "DocumentEmail" || mRecord.LogType == "DocumentSms"));
  var PublishStatus = C.cboPublishStatus.Text();
  if (!PublishStatus &amp;&amp; mRecord) PublishStatus = mRecord.PublishStatus;

  // Document publication details
  if (mRecord.DocumentId) {
    C.tbDocumentPublication.show();
  }
  else {
    C.tbDocumentPublication.hide();
  }

  if (IsDocumentLog) {
    switch (PublishStatus) {
      case "Failed":
        C.datePublishOnDate.VisibleRow(true);
        C.cboDocumentSendEmail.VisibleRow(false);
        C.datePublishOnDate.ReadOnly(true);
        C.datePublishedDate.VisibleRow(true);
        C.datePublishFailDate.VisibleRow(true);
        C.cboPublishResult.VisibleRow(true);
        C.cboPublishResult.Caption("Reason:");

        // Refresh Information Lists
        if (!mRecord.ReadOnly) {
          C.cboPublishResult.SetComboFromInformationList(mRecord.PublishResultFailedInformationListId);
        }
        break;

      case "None":
        C.datePublishOnDate.VisibleRow(false);
        C.cboDocumentSendEmail.VisibleRow(false);        
        C.datePublishedDate.VisibleRow(false);
        C.datePublishFailDate.VisibleRow(false);
        C.cboPublishResult.VisibleRow(false);
        break;

      case "NotIssued":
      case "Not Issued":
        C.datePublishOnDate.VisibleRow(false);
        C.cboDocumentSendEmail.VisibleRow(false);
        C.datePublishedDate.VisibleRow(false);
        C.datePublishFailDate.VisibleRow(false);
        C.cboPublishResult.VisibleRow(true);      

        // Refresh Information Lists
        if (!mRecord.ReadOnly) {
          C.cboPublishResult.SetComboFromInformationList(mRecord.PublishResultNotIssuedInformationListId);
        }
        break;

      case "Open":
        C.datePublishOnDate.VisibleRow(false);
        C.cboDocumentSendEmail.VisibleRow(mRecord.SupportsDocumentSendEmail);
        C.datePublishedDate.VisibleRow(false);
        C.datePublishFailDate.VisibleRow(false);
        C.cboPublishResult.VisibleRow(false);
        break;

      case "Published":
        C.datePublishOnDate.VisibleRow(true);
        C.cboDocumentSendEmail.VisibleRow(false);
        C.datePublishOnDate.ReadOnly(true);
        C.datePublishedDate.VisibleRow(true);
        C.datePublishFailDate.VisibleRow(false);
        C.cboPublishResult.Caption("Result:");
        C.cboPublishResult.VisibleRow(true);

        // Refresh Information Lists
        if (!mRecord.ReadOnly) {
          C.cboPublishResult.SetComboFromInformationList(mRecord.PublishResultInformationListId);
        }
        break;

      case "ToSend":
      case "To Send":
        C.datePublishOnDate.VisibleRow(true);
        C.cboDocumentSendEmail.VisibleRow(mRecord.SupportsDocumentSendEmail);        
        C.datePublishOnDate.VisibleRow(true);
        if (!mRecord.ReadOnly &amp;&amp; !C.datePublishOnDate.Value()) {
          // Default to current time
          C.datePublishOnDate.ValueSetNow();
        }
        //TODO:
        //C.datePublishOnDate.ReadOnly(!(mRecord &amp;&amp; mRecord.Permissions.CanSave));
        C.datePublishedDate.VisibleRow(false);
        C.datePublishFailDate.VisibleRow(false);
        C.cboPublishResult.VisibleRow(false);
        break;
      
      default:
        window.alert("Publish Status '" + mRecord.PublishStatus + "' not handled.");
        break;
    }

    // Available Publish Statuses
    if (mRecord &amp;&amp; mRecord.PublishStatusList) {
      C.cboPublishStatus.ListFromCsvString(mRecord.PublishStatusList);
    }

    // Unpublish button
    //TODO:
  }
  else {
    C.tbDocumentPublication.hide();
  }

  // Document Print Status
  var showPrintStatus = mRecord.HasDocument &amp;&amp; mRecord.SupportsDocumentPrint;
  switch (mRecord.LogObjectType) {
    case "SecurityStmt":
    case "SecurityStmtItem":
      // Not applicable to Security Statements
      showPrintStatus = false;
      break;
  }
  if (showPrintStatus) {
    C.tbDocumentPrintStatus.show();
    if (mRecord.PrintedTzDate) {
      C.datePrintedDate.VisibleRow(true);
    }
    else {
      C.datePrintedDate.VisibleRow(false);
    }

    // Available Print Statuses
    if (mRecord &amp;&amp; mRecord.PrintStatusList) {
      C.cboPrintStatus.ListFromCsvString(mRecord.PrintStatusList);
    }
  }
  else {
    C.tbDocumentPrintStatus.hide();
  }

  // HTML Document
  C.tbHtmlDocument.hide();

  // Embedded File
  C.tbEmbeddedDocument.hide();
}

// ====================
// pageFee (both pages)
// ====================
function pageFee_Refresh() {
  var IsDocumentLog = (mRecord &amp;&amp; (mRecord.LogType == "Document" || mRecord.LogType == "DocumentEmail" || mRecord.LogType == "DocumentSms"));
  
  var PublishStatus = C.cboPublishStatus.Text();
  if (!PublishStatus &amp;&amp; mRecord) PublishStatus = mRecord.PublishStatus;
  
  // Reset
  C.spnChargeFeeWarning.hide();
  C.lblChargeFee.VisibleRow(false);
  C.chkChargeLogFee.VisibleRow(false);
  C.cboLogFeeElement.VisibleRow(false);
  C.numLogFee.VisibleRow(false);
  C.txtLogFeeReference.VisibleRow(false);
  C.txtLogFeeNotes.VisibleRow(false);
  C.lblFeeCharged.VisibleRow(false);
  C.numFee.VisibleRow(false);

  // Update Fee details
  if (mRecord.CanUpdateFee) {
    if (IsDocumentLog) {
      // Allow Fee to be edited since the Document is not yet Published                        
      C.lblFeeCharged.Text("Fee to charge when published");
      C.lblFeeCharged.VisibleRow(true);
      C.numFee.VisibleRow(true);
    }
    else {
      // Allow a Fee to be Charged
      C.lblChargeFee.VisibleRow(true);
      C.chkChargeLogFee.VisibleRow(true);
      chkChargeLogFee_Change();
    }
  }
  else {
    if (mRecord.HasFee) {
      if (mRecord.FeeAccountTransactionPk == 0) {
        if (IsDocumentLog) {
          switch (PublishStatus) {
            case "Open":
            case "ToSend":
            case "To Send":                    
              C.lblFeeCharged.Text("Fee to charge when published");
              break;

            default:
              C.spnChargeFeeWarning.show();
              break;
          }
        }
        else {
          C.spnChargeFeeWarning.show();
        }
      }
      else {
        C.lblFeeCharged.Text("Fee charged");
      }

      C.lblFeeCharged.VisibleRow(true);
      C.numFee.ReadOnly(true);
      C.numFee.VisibleRow(true);
    }
  }
}

// ====================
// Notification Handler
// ====================
function Widget_NotificationHandler(actionId, data) {
   switch(actionId.toUpperCase()) {
     case "BANKACCOUNTENQUIRY.REFRESH":
      // Refresh Bank Account Enquiry, e.g., after a "Get Report"
      wbServiceLog_Refresh();
      break;
     
     case "SERVICELOG.REFRESH":
      // Refresh the Service Log
      wbServiceLog_Refresh();
      break;
      
     case "FORMCLOSE":
      // Form Close button is disabled so act as if 'Cancel' has been clicked
      tabDetails_Cancel();
      break;
   }
      
}

// ==========
// cboSubject
// ==========
function cboSubject_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update Log Outcome Information List (since this can be defined as a sectioned list)
  C.cboLogOutcome.SetLogOutcomeComboFromSectionedInformationList(mRecord.LogOutcomesInformationListId, C.cboSubject.Text(), mRecord.LogOutcome, mRecord.Source);
}

// ==========
// dateAction
// ==========
function dateAction_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  Form_UpdateActions();
}

// ==================
// dateActionComplete
// ==================
function dateActionComplete_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  Form_UpdateActions();
}

// ======
// cmdFee
// ======
function cmdFee_Click() {
  // NOTE: id is used if running this Widget within finPOWER Connect desktop. finPOWER Connect Cloud uses accountId and accountTransactionPk
  widget.ExecuteApplicationShortcutUrl("app://formshow?form=AccountTransactionView&amp;accountId=" + encodeURIComponent(mRecord.RecordId) + "&amp;accountTransactionPk=" + mRecord.FeeAccountTransactionPk + "&amp;id=" + mRecord.FeeAccountTransactionPk);
}

// ===============
// chkChargeLogFee
// ===============
function chkChargeLogFee_Change(sender, e) {
  C.cboLogFeeElement.VisibleRow(C.chkChargeLogFee.Value());
  C.numLogFee.VisibleRow(C.chkChargeLogFee.Value());
  C.txtLogFeeReference.VisibleRow(C.chkChargeLogFee.Value());
  C.txtLogFeeNotes.VisibleRow(C.chkChargeLogFee.Value());
}

// ================
// cboLogFeeElement
// ================
function cboLogFeeElement_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;

  // Update default value, reference and notes
  if (e) {
    var element = mElements.GetItem(C.cboLogFeeElement.Text());
    if (element) {
      C.numLogFee.Value(element.TransactionValue);
      C.txtLogFeeReference.Text(element.TransactionReference);
      C.txtLogFeeNotes.Text(element.TransactionNotes);
    }
  }
}

// ============
// wbServiceLog
// ============
function wbServiceLog_Refresh() {
  // Service Log
  if (mRecord.ServiceLogSummaryHtml) {
    widget.GetString("GetServiceLogSummary", {}, 
      function (data) {
        C.wbServiceLog.SetContent(data, false);      
      },
      
      function (error) {
        widget.UI.MsgBoxAlert(error);
      }
    );
  }
  else {
    // No Service Log Summary so ignore
  }
}

// ============
// chkRepeatUse
// ============
function chkRepeatUse_Change(sender, e) {
  C.cboRepeatBasis.VisibleRow(C.chkRepeatUse.Value());
  C.cboRepeatCycle.VisibleRow(C.chkRepeatUse.Value());
}

// ===============
// cmdExtendedData
// ===============
function cmdExtendedData_Click() {
}

// =============
// cmdParameters
// =============
function cmdParameters_Click() {
}

// ===============
// cmdDocumentHtml
// ===============
function cmdDocumentHtml_Click() {
}

// ==============
// cmdAccountData
// ==============
function cmdAccountData_Click() {
}

// ===========
// cmdUserData
// ===========
function cmdUserData_Click() {
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>lkKrCPYyGECM3J6HNCobTA</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Log</Caption>
    <HtmlWidgetAllowInitialEventCaching>false</HtmlWidgetAllowInitialEventCaching>
    <HtmlWidgetMaxHeight>1200</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>800</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>false</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <HtmlWidgetSpecialEventShowAsSummaryPage>false</HtmlWidgetSpecialEventShowAsSummaryPage>
    <HtmlWidgetSummaryPageObjectType>None</HtmlWidgetSummaryPageObjectType>
    <Icon>Log</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="PrioritiseOwnerAndDelegated" type="Boolean">
            <BlankTip />
            <Caption>Move "Owner and User Delegated to" to "General" tab?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>False</Value>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>TESTING</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>true</Visible>
          </Parameter>
          <Parameter name="ObjectType" 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>Account,AccountApp,Client,SecurityStmt,SecurityStmtItem,User</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="Id" type="Number">
            <BlankTip />
            <Caption>Log 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 />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="LogType" 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>WebMailFromClient,WebMailToClient</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AccountId" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AccountAppId" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="AccountAppApplicantPk" 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 />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="AccountAppCollateralItemPk" 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 />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="ClientId" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="SecurityStmtId" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="SecurityStmtItemPk" 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 />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="UserId" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="WorkflowId" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="WorkflowItemPk" type="Number">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <DecimalPlaces>0</DecimalPlaces>
            <GroupDigits>true</GroupDigits>
            <MaxValue />
            <MinValue />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </Parameter>
          <Parameter name="ReplyToLogPk" 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 />
            <NumberSpecialType>None</NumberSpecialType>
            <SpinChange>1</SpinChange>
          </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,ServiceLog,ExtendedData,WebMail,Document,Fee,FeeNew,Other,ExternalParty,Audit,Summary</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>
          <Parameter name="DefaultLogSeverityId" 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.LogSeverities</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="DefaultSubject" type="Text">
            <BlankTip />
            <Caption />
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="DefaultOwnerUserId" 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.Users</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="DefaultDelegatedUserId" 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.Users</List>
            <LimitToList>false</LimitToList>
            <MaxLength>0</MaxLength>
            <Rows>1</Rows>
          </Parameter>
          <Parameter name="ActionImmediately" type="Boolean">
            <BlankTip />
            <Caption>Action Immediately?</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>