@model Disco.Web.Areas.Config.Models.DocumentTemplate.ShowModel
@using Disco.Services.Documents.ManagedGroups;
@using Disco.Services.Interop.ActiveDirectory;
@using Disco.Web.Areas.Config.Models.Shared;
@{
    Authorization.Require(Claims.Config.DocumentTemplate.Show);

    var canConfig = Authorization.Has(Claims.Config.DocumentTemplate.Configure);

    var hideAdvanced =
        Model.DocumentTemplate.UsersLinkedGroup == null &&
        Model.DocumentTemplate.DevicesLinkedGroup == null &&
        Model.DocumentTemplate.FilterExpression == null &&
        Model.DocumentTemplate.OnGenerateExpression == null &&
        Model.DocumentTemplate.OnImportAttachmentExpression == null &&
        Model.TemplateExpressions.All(e => e.All(p => !p.ParseError) &&
        !Model.OnImportUserFlagRules.Any());

    #region Can Bulk Generate
    var canBulkGenerate = Authorization.Has(Claims.Config.DocumentTemplate.BulkGenerate);
    if (canBulkGenerate)
    {
        switch (Model.DocumentTemplate.Scope)
        {
            case DocumentTemplate.DocumentTemplateScopes.Device:
                canBulkGenerate = Authorization.Has(Claims.Device.Actions.GenerateDocuments);
                break;
            case DocumentTemplate.DocumentTemplateScopes.Job:
                canBulkGenerate = Authorization.Has(Claims.Job.Actions.GenerateDocuments);
                break;
            case DocumentTemplate.DocumentTemplateScopes.User:
                canBulkGenerate = Authorization.Has(Claims.User.Actions.GenerateDocuments);
                break;
            default:
                throw new InvalidOperationException("Invalid DocumentType Scope");
        }
    }
    #endregion

    ViewBag.Title = Html.ToBreadcrumb("Configuration", MVC.Config.Config.Index(), "Document Templates", MVC.Config.DocumentTemplate.Index(null), Model.DocumentTemplate.Description);

    if (canConfig)
    {
        Html.BundleDeferred("~/ClientScripts/Modules/Disco-PropertyChangeHelpers");
    }
}
<div id="Config_DocumentTemplates_Show" class="@(hideAdvanced ? " Config_HideAdvanced" : null)">
    <div class="form" style="width: 650px; margin: 10px auto 20px;">
        <table>
            <tbody>
                <tr>
                    <th>
                        Id:
                    </th>
                    <td>
                        <code>@Html.DisplayFor(model => model.DocumentTemplate.Id)</code>
                    </td>
                </tr>
                <tr>
                    <th>
                        Statistics:
                    </th>
                    <td>
                        <strong>@Model.StoredInstanceCount.ToString("n0")</strong> Stored Instance@(Model.StoredInstanceCount == 1 ? null : "s")
                    </td>
                </tr>
                <tr>
                    <th>
                        Description:
                    </th>
                    <td>
                        @if (canConfig)
                        {
                            @Html.TextBoxFor(model => model.DocumentTemplate.Description)
                            @AjaxHelpers.AjaxSave()
                            @AjaxHelpers.AjaxLoader()
                            <script type="text/javascript">
                                $(function () {
                                    document.DiscoFunctions.PropertyChangeHelper(
                                        $('#DocumentTemplate_Description'),
                                        'Description',
                                        '@Url.Action(MVC.API.DocumentTemplate.UpdateDescription(Model.DocumentTemplate.Id))',
                                        'Description'
                                    );
                                });
                            </script>
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(Model.DocumentTemplate.Description))
                            {
                                <span class="smallMessage">&lt;None Specified&gt;</span>
                            }
                            else
                            {
                                @Model.DocumentTemplate.Description
                            }
                        }
                    </td>
                </tr>
                <tr>
                    <th>
                        &nbsp;
                    </th>
                    <td>
                        <div>
                            @if (canConfig)
                            {
                                <input id="DocumentTemplate_IsHidden" type="checkbox" @(Model.DocumentTemplate.IsHidden ? new MvcHtmlString("checked=\"checked\" ") : null) />
                                <label for="DocumentTemplate_IsHidden">Hidden</label>
                                @AjaxHelpers.AjaxLoader()
                                <script type="text/javascript">
                                    $(function () {
                                        document.DiscoFunctions.PropertyChangeHelper(
                                            $('#DocumentTemplate_IsHidden'),
                                            null,
                                            '@Url.Action(MVC.API.DocumentTemplate.UpdateIsHidden(Model.DocumentTemplate.Id))',
                                            'IsHidden'
                                        );
                                    });
                                </script>
                            }
                            else
                            {
                                <input id="DocumentTemplate_IsHidden" type="checkbox" @(Model.DocumentTemplate.IsHidden ? new MvcHtmlString("checked=\"checked\" ") : null) disabled="disabled" />
                                <label for="DocumentTemplate_IsHidden">Hidden</label>
                            }
                        </div>
                        <div class="info-box">
                            <p class="fa-p">
                                <i class="fa fa-info-circle"></i>If selected the template will not appear in the list of documents to generate.
                            </p>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th>
                        Scope:
                    </th>
                    <td>
                        <h4>@Model.DocumentTemplate.Scope Scope</h4>
                        <div class="info-box">
                            <p class="fa-p">
                                <i class="fa fa-info-circle"></i>This template is generated from @(Model.DocumentTemplate.Scope)s. Any expressions within the Template&nbsp;PDF will be evaluated within the <a href="@(Url.Action(MVC.Config.Expressions.Browser()))#@(Model.DocumentTemplate.Scope)Scope">@(Model.DocumentTemplate.Scope) Scope</a>.
                            </p>
                        </div>
                        <div>
                            <button id="Config_DocumentTemplates_Scope_Button" class="button small">Change Scope</button>
                        </div>
                        @if (canConfig)
                        {
                            <div id="Config_DocumentTemplates_Scope_Dialog" title="Change Document Template Scope" class="dialog">
                                @using (Html.BeginForm(MVC.API.DocumentTemplate.UpdateScope(Model.DocumentTemplate.Id, redirect: true)))
                                {
                                    <div class="input">
                                        <label for="Config_DocumentTemplates_Scope_Scope">Scope: </label>
                                        <select id="Config_DocumentTemplates_Scope_Scope" name="Scope">
                                            @foreach (var scope in Model.Scopes)
                                            {
                                                <option value="@scope" selected="@(scope == Model.DocumentTemplate.Scope ? " selected" : null)">@scope</option>
                                            }
                                        </select>
                                    </div>
                                }
                                <div class="info-box">
                                    <p class="fa-p">
                                        <i class="fa fa-info-circle"></i>Expressions within the Template PDF may need to be updated to reflect any changes to the Document Template Scope.
                                    </p>
                                </div>
                                @if (Model.DocumentTemplate.UsersLinkedGroup != null || Model.DocumentTemplate.DevicesLinkedGroup != null)
                                {
                                    <div class="info-box error">
                                        <p class="fa-p">
                                            <i class="fa fa-exclamation-circle"></i><strong>Warning:</strong> This Document Template contains Linked Groups, these will be automatically updated to reflect the new Document Template Scope which <strong>may result in undesired behaviour</strong>.
                                        </p>
                                    </div>
                                }
                            </div>
                            <script type="text/javascript">
                                $(function () {
                                    var dialog;

                                    function showDialog() {
                                        if (dialog == null) {
                                            dialog = $('#Config_DocumentTemplates_Scope_Dialog').dialog({
                                                width: 400,
                                                resizable: false,
                                                modal: true,
                                                autoOpen: false,
                                                buttons: {
                                                    'Save Changes': function () {
                                                        dialog.dialog('option', 'buttons', null);
                                                        dialog.dialog('disable');
                                                        $('#Config_DocumentTemplates_Scope_Scope').closest('form').submit();
                                                    },
                                                    'Cancel': function () {
                                                        dialog.dialog('close');
                                                    }
                                                }
                                            });
                                        }

                                        dialog.dialog('open');

                                        return false;
                                    }

                                    $('#Config_DocumentTemplates_Scope_Button').click(showDialog);
                                });
                            </script>
                        }
                        @if (Model.DocumentTemplate.Scope == DocumentTemplate.DocumentTemplateScopes.Job)
                        {
                            <hr />
                            <h4>Job Type Filters:</h4>
                            <div id="Config_DocumentTemplates_JobSubTypes">
                                <div>
                                    @if (Model.DocumentTemplate.JobSubTypes.Count > 0)
                                    {
                                        <ul>
                                            @foreach (var jobType in Model.DocumentTemplate.JobSubTypes.GroupBy(jst => jst.JobType).OrderBy(jtg => jtg.Key.Description))
                                            {
                                                <li>
                                                    @jobType.Key.Description
                                                    <ul>
                                                        @if (jobType.Count() == Model.JobTypes.FirstOrDefault(jt => jt.Id == jobType.Key.Id).JobSubTypes.Count)
                                                        {
                                                            <li><span class="smallMessage">[All Sub Types]</span></li>
                                                        }
                                                        else
                                                        {
                                                            foreach (var jobSubType in jobType)
                                                            {
                                                                <li>@jobSubType.Description</li>
                                                            }
                                                        }
                                                    </ul>
                                                </li>
                                            }
                                        </ul>
                                    }
                                    else
                                    {
                                        <span class="smallMessage">&lt;No Filter&gt;</span>
                                    }
                                </div>
                                @if (canConfig)
                                {
                                    <a id="Config_DocumentTemplates_JobSubTypes_Update" href="#" class="button small">Update</a>
                                    <div id="Config_DocumentTemplates_JobSubTypes_Update_Dialog" class="dialog" title="Job Type Filter">
                                        @using (Html.BeginForm(MVC.API.DocumentTemplate.UpdateJobSubTypes(Model.DocumentTemplate.Id, null, true)))
                                        {
                                            var selectedTypes = Model.DocumentTemplate.JobSubTypes.Select(jst => jst.JobType).Distinct().ToList();
                                            foreach (var jt in Model.JobTypes)
                                            {
                                                <div class="jobTypes">
                                                    <h4>
                                                        <input id="Types_@(jt.Id)" class="jobType" type="checkbox" value="@(jt.Id)" @(selectedTypes.Contains(jt) ? "checked=\" checked\"" : null) /><label for="Types_@(jt.Id)">@jt.Description</label>
                                                    </h4>
                                                    <div id="SubTypes_@(jt.Id)" class="jobSubTypes">
                                                        @CommonHelpers.CheckboxBulkSelect(string.Format("CheckboxBulkSelect_{0}", jt.Id), "div")
                                                        @CommonHelpers.CheckBoxList("JobSubTypes", jt.JobSubTypes.OrderBy(jst => jst.Description).ToSelectListItems(Model.DocumentTemplate.JobSubTypes), 2)
                                                    </div>
                                                </div>
                                            }
                                        }
                                    </div>
                                    <script>
                                        (function () {
                                            var dialog;

                                            function showDialog() {
                                                if (!dialog) {
                                                    dialog = $('#Config_DocumentTemplates_JobSubTypes_Update_Dialog').dialog({
                                                        resizable: false,
                                                        modal: true,
                                                        autoOpen: false,
                                                        width: 750,
                                                        height: 580,
                                                        buttons: {
                                                            "Save Changes": saveChanges,
                                                            Cancel: cancel
                                                        }
                                                    });

                                                    dialog.find('.jobSubTypes').hide();
                                                    dialog.on('change', 'input.jobType', function () {
                                                        var $this = $(this);
                                                        if ($this.is(':checked'))
                                                            $('#SubTypes_' + $this.val()).slideDown('fast');
                                                        else
                                                            $('#SubTypes_' + $this.val()).slideUp('fast');
                                                    }).find('input.jobType:checked').each(function () {
                                                        $('#SubTypes_' + $(this).val()).show();
                                                    });
                                                }

                                                dialog.dialog('open');

                                                return false;
                                            }

                                            function cancel() {
                                                dialog.dialog("disable");
                                                dialog.dialog("option", "buttons", null);

                                                // Refresh Page
                                                window.location.reload(true);
                                            }

                                            function saveChanges() {
                                                var form = dialog.find('form');

                                                $('input.jobType:unchecked').each(function () {
                                                    $('#SubTypes_' + $(this).val()).find('input').prop('checked', false);
                                                });

                                                form.submit();

                                                dialog.dialog("disable");
                                                dialog.dialog("option", "buttons", null);
                                            }

                                            $(function () {
                                                $('#Config_DocumentTemplates_JobSubTypes_Update').click(showDialog);
                                            });

                                        })();
                                    </script>
                                }
                            </div>
                        }
                    </td>
                </tr>
                <tr>
                    <th>
                        &nbsp;
                    </th>
                    <td>
                        <div>
                            @if (canConfig)
                            {
                                <input id="DocumentTemplate_FlattenForm" type="checkbox" @(Model.DocumentTemplate.FlattenForm ? new MvcHtmlString("checked=\"checked\" ") : new MvcHtmlString(string.Empty)) />
                                <label for="DocumentTemplate_FlattenForm">Flatten Form</label>
                                @AjaxHelpers.AjaxLoader()
                                <script type="text/javascript">
                                    $(function () {
                                        document.DiscoFunctions.PropertyChangeHelper(
                                            $('#DocumentTemplate_FlattenForm'),
                                            null,
                                            '@Url.Action(MVC.API.DocumentTemplate.UpdateFlattenForm(Model.DocumentTemplate.Id))',
                                            'FlattenForm'
                                        );
                                    });
                                </script>
                            }
                            else
                            {
                                <input id="DocumentTemplate_FlattenForm" type="checkbox" @(Model.DocumentTemplate.FlattenForm ? new MvcHtmlString("checked=\"checked\" ") : new MvcHtmlString(string.Empty)) disabled="disabled" />
                                <label for="DocumentTemplate_FlattenForm">Flatten Form</label>
                            }
                        </div>
                        <div class="info-box">
                            <p class="fa-p">
                                <i class="fa fa-info-circle"></i>When a document is generated all form elements will be removed and their content written in place if this option is selected.
                            </p>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <div class="form Config_DocumentTemplates_Template" style="width: 650px; margin: 0 auto 20px;">
        <h2>PDF Template</h2>
        <table>
            <tbody>
                <tr>
                    <td>
                        <div style="margin: -8px -5px; height: 350px; overflow-y: scroll; text-align: center;">
                            <img style="margin: 8px 5px;" src="@Url.Action(MVC.API.DocumentTemplate.TemplatePreview(Model.DocumentTemplate.Id))" />
                        </div>
                    </td>
                </tr>
                @if (canConfig)
                {
                    <tr>
                        <td>
                            @if (Model.TemplatePagesHaveAttachmentId.Any(i => !i))
                            {
                                <div class="info-box">
                                    @for (int i = 0; i < Model.TemplatePagesHaveAttachmentId.Count; i++)
                                    {
                                        if (!Model.TemplatePagesHaveAttachmentId[i])
                                        {
                                            <p class="fa-p">
                                                <i class="fa fa-question-circle"></i>Note: Page @(i + 1) does not have a <code>DiscoAttachmentId</code> field.
                                            </p>
                                        }
                                    }
                                    <p style="margin-top: 6px;">
                                        The <code>DiscoAttachmentId</code> field is replaced with a unique QR Code which identifies the page when it is imported back into Disco ICT.
                                    </p>
                                </div>
                            }
                            <div style="text-align: right;">
                                @Html.ActionLinkSmallButton("Download Template", MVC.API.DocumentTemplate.Template(Model.DocumentTemplate.Id))
                                @if (canConfig && Authorization.Has(Claims.Config.DocumentTemplate.Upload))
                                {
                                    <button class="button small" id="Config_DocumentTemplates_TemplatePdf_Button">Replace Template</button>
                                    <div id="Config_DocumentTemplates_TemplatePdf_Dialog" title="Replace Document PDF Template" class="dialog">
                                        <h4>Select a PDF Template to upload:</h4>
                                        <div>
                                            @using (Html.BeginForm(MVC.API.DocumentTemplate.Template(Model.DocumentTemplate.Id, true, null), FormMethod.Post, new { enctype = "multipart/form-data" }))
                                            {
                                                <input type="file" name="Template" id="Config_DocumentTemplates_TemplatePdf_Template" accept=".pdf" style="width: 250px;" />
                                            }
                                        </div>
                                    </div>
                                    <script type="text/javascript">
                                        $(function () {
                                            var dialog, template;

                                            function showDialog() {
                                                if (dialog == null) {
                                                    template = $('#Config_DocumentTemplates_TemplatePdf_Template');

                                                    dialog = $('#Config_DocumentTemplates_TemplatePdf_Dialog').dialog({
                                                        width: 350,
                                                        resizable: false,
                                                        modal: true,
                                                        autoOpen: false,
                                                        buttons: {
                                                            'Upload': function () {
                                                                if (template.val() == '') {
                                                                    alert('A template file is required to upload.');
                                                                } else {
                                                                    dialog.dialog('option', 'buttons', null);
                                                                    dialog.dialog('disable');
                                                                    template.closest('form').submit();
                                                                }
                                                            },
                                                            'Cancel': function () {
                                                                dialog.dialog('close');
                                                            }
                                                        }
                                                    });
                                                }

                                                dialog.dialog('open');

                                                return false;
                                            }

                                            $('#Config_DocumentTemplates_TemplatePdf_Button').click(showDialog);
                                        });
                                    </script>
                                }
                            </div>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>

    <div class="form Config_HideAdvanced_Item" style="width: 650px;">
        <h2>Advanced Options</h2>
        <table>
            <tbody>
                <tr>
                    <th>
                        Filter Expression:
                    </th>
                    <td>
                        @if (canConfig && Authorization.Has(Claims.Config.DocumentTemplate.ConfigureFilterExpression))
                        {
                            @Html.EditorFor(model => model.DocumentTemplate.FilterExpression)
                            @AjaxHelpers.AjaxRemove()
                            @AjaxHelpers.AjaxSave()
                            @AjaxHelpers.AjaxLoader()
                            <script type="text/javascript">
                                $(function () {
                                    var field = $('#DocumentTemplate_FilterExpression');
                                    var fieldRemove = field.next('.ajaxRemove');
                                    var fieldOriginalWidth, fieldOriginalHeight;

                                    document.DiscoFunctions.PropertyChangeHelper(
                                        field,
                                        'None',
                                        '@Url.Action(MVC.API.DocumentTemplate.UpdateFilterExpression(Model.DocumentTemplate.Id))',
                                        'FilterExpression'
                                    );

                                    field.focus(function () {
                                        fieldOriginalWidth = field.width();
                                        fieldOriginalHeight = field.height();
                                        field.css('overflow', 'visible').animate({ width: field.parent().width() - 42, height: 75 }, 200);
                                    }).blur(function () {
                                        field.css('overflow', 'hidden').animate({ width: fieldOriginalWidth, height: fieldOriginalHeight }, 200);
                                    }).change(function () {
                                        if (!!field.val()) {
                                            fieldRemove.show();
                                        } else {
                                            fieldRemove.hide();
                                        }
                                    }).attr('placeholder', 'None').attr('spellcheck', 'false');

                                    fieldRemove.click(function () {
                                        field.val('').change();
                                    });

                                    if (!!field.val()) {
                                        fieldRemove.show();
                                    } else {
                                        fieldRemove.hide();
                                    }
                                });
                            </script>
                        }
                        else
                        {
                            if (string.IsNullOrWhiteSpace(Model.DocumentTemplate.FilterExpression))
                            {
                                <span class="smallMessage">&lt;None Specified&gt;</span>
                            }
                            else
                            {
                                <div class="code">
                                    @Model.DocumentTemplate.FilterExpression
                                </div>
                            }
                        }
                        <div class="info-box">
                            <p class="fa-p">
                                <i class="fa fa-fw fa-info-circle"></i>This expression will be evaluated to determine if this template is shown in the <em>Generate Document</em> drop-down list. If the template is hidden (see above) this expression is ignored.
                            </p>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th>
                        On Generated Expression:
                    </th>
                    <td>
                        @if (canConfig && Authorization.Has(Claims.Config.DocumentTemplate.ConfigureFilterExpression))
                        {
                            @Html.EditorFor(model => model.DocumentTemplate.OnGenerateExpression)
                            @AjaxHelpers.AjaxRemove()
                            @AjaxHelpers.AjaxSave()
                            @AjaxHelpers.AjaxLoader()
                            <script type="text/javascript">
                                $(function () {
                                    var field = $('#DocumentTemplate_OnGenerateExpression');
                                    var fieldRemove = field.next('.ajaxRemove');
                                    var fieldOriginalWidth, fieldOriginalHeight;

                                    document.DiscoFunctions.PropertyChangeHelper(
                                        field,
                                        'None',
                                        '@Url.Action(MVC.API.DocumentTemplate.UpdateOnGenerateExpression(Model.DocumentTemplate.Id))',
                                        'OnGenerateExpression'
                                    );

                                    field.focus(function () {
                                        fieldOriginalWidth = field.width();
                                        fieldOriginalHeight = field.height();
                                        field.css('overflow', 'visible').animate({ width: field.parent().width() - 42, height: 75 }, 200);
                                    }).blur(function () {
                                        field.css('overflow', 'hidden').animate({ width: fieldOriginalWidth, height: fieldOriginalHeight }, 200);
                                    }).change(function () {
                                        if (!!field.val()) {
                                            fieldRemove.show();
                                        } else {
                                            fieldRemove.hide();
                                        }
                                    }).attr('placeholder', 'None').attr('spellcheck', 'false');

                                    fieldRemove.click(function () {
                                        field.val('').change();
                                    });

                                    if (!!field.val()) {
                                        fieldRemove.show();
                                    } else {
                                        fieldRemove.hide();
                                    }
                                });
                            </script>
                        }
                        else
                        {
                            if (string.IsNullOrWhiteSpace(Model.DocumentTemplate.OnGenerateExpression))
                            {
                                <span class="smallMessage">&lt;None Specified&gt;</span>
                            }
                            else
                            {
                                <div class="code">
                                    @Model.DocumentTemplate.OnGenerateExpression
                                </div>
                            }
                        }
                        <div class="info-box">
                            <p class="fa-p">
                                <i class="fa fa-fw fa-info-circle"></i>This expression will be evaluated each time a document is generated from this template.
                            </p>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th>
                        On Import Expression:
                    </th>
                    <td>
                        @if (canConfig && Authorization.Has(Claims.Config.DocumentTemplate.ConfigureFilterExpression))
                        {
                            @Html.EditorFor(model => model.DocumentTemplate.OnImportAttachmentExpression)
                            @AjaxHelpers.AjaxRemove()
                            @AjaxHelpers.AjaxSave()
                            @AjaxHelpers.AjaxLoader()
                            <script type="text/javascript">
                                $(function () {
                                    var field = $('#DocumentTemplate_OnImportAttachmentExpression');
                                    var fieldRemove = field.next('.ajaxRemove');
                                    var fieldOriginalWidth, fieldOriginalHeight;

                                    document.DiscoFunctions.PropertyChangeHelper(
                                        field,
                                        'None',
                                        '@Url.Action(MVC.API.DocumentTemplate.UpdateOnImportAttachmentExpression(Model.DocumentTemplate.Id))',
                                        'OnImportAttachmentExpression'
                                    );

                                    field.focus(function () {
                                        fieldOriginalWidth = field.width();
                                        fieldOriginalHeight = field.height();
                                        field.css('overflow', 'visible').animate({ width: field.parent().width() - 42, height: 75 }, 200);
                                    }).blur(function () {
                                        field.css('overflow', 'hidden').animate({ width: fieldOriginalWidth, height: fieldOriginalHeight }, 200);
                                    }).change(function () {
                                        if (!!field.val()) {
                                            fieldRemove.show();
                                        } else {
                                            fieldRemove.hide();
                                        }
                                    }).attr('placeholder', 'None').attr('spellcheck', 'false');

                                    fieldRemove.click(function () {
                                        field.val('').change();
                                    });

                                    if (!!field.val()) {
                                        fieldRemove.show();
                                    } else {
                                        fieldRemove.hide();
                                    }
                                });
                            </script>
                        }
                        else
                        {
                            if (string.IsNullOrWhiteSpace(Model.DocumentTemplate.OnImportAttachmentExpression))
                            {
                                <span class="smallMessage">&lt;None Specified&gt;</span>
                            }
                            else
                            {
                                <div class="code">
                                    @Model.DocumentTemplate.OnImportAttachmentExpression
                                </div>
                            }
                        }
                        <div class="info-box">
                            <p class="fa-p">
                                <i class="fa fa-fw fa-info-circle"></i>This expression will be evaluated each time a document is imported (as an attachment) where it is determined the document was based on this template.
                            </p>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th>
                        On Import <br /> User Flag Rules:
                    </th>
                    <td>
                        @if (canConfig && Authorization.Has(Claims.Config.UserFlag.Configure))
                        {
                            <table id="DocumentTemplate_OnImportUserFlagRules" class="tableData">
                                <thead>
                                    <tr>
                                        <td>Action</td>
                                        <td>User Flag</td>
                                        <td>Comments</td>
                                        <td>&nbsp;</td>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="@(Model.OnImportUserFlagRules.Any() ? "hidden" : null)">
                                        <td colspan="4"><span class="smallMessage">&lt;None Specified&gt;</span></td>
                                    </tr>
                                    @foreach (var rule in Model.OnImportUserFlagRules)
                                    {
                                        <tr data-id="@rule.Id">
                                            <td>@(rule.AddFlag ? "Assign" : "Remove")</td>
                                            <td>
                                                <i class="fa fa-@(rule.UserFlag.Icon) fa-lg d-@(rule.UserFlag.IconColour)"></i>
                                                @if (Authorization.Has(Claims.Config.UserFlag.Configure))
                                                {
                                                    <span>@Html.ActionLink(rule.UserFlag.Name, MVC.Config.UserFlag.Index(rule.UserFlag.Id))</span>
                                                }
                                                else
                                                {
                                                    <span>@rule.UserFlag.Name</span>
                                                }
                                            </td>
                                            <td>
                                                @if (string.IsNullOrWhiteSpace(rule.Comments))
                                                {
                                                    <span>&nbsp;</span>
                                                }
                                                else
                                                {
                                                    <span class="whitespace-pre-wrap">@rule.Comments</span>
                                                }
                                            </td>
                                            <td>
                                                <i class="fa fa-times-circle fa-lg ajaxRemove" title="Remove"></i>
                                                <i class="ajaxLoading" title="Loading..."></i>
                                            </td>
                                        </tr>
                                    }
                                </tbody>
                            </table>
                            using (Html.BeginForm(MVC.API.DocumentTemplate.RemoveOnImportUserFlagRule(Model.DocumentTemplate.Id), FormMethod.Post, new { id = "DocumentTemplate_OnImportUserFlagRules_Remove" }))
                            {
                                @Html.AntiForgeryToken()
                                @Html.Hidden("ruleId", "")
                            }
                            <a id="DocumentTemplate_OnImportUserFlagRules_AddButton" href="#" class="button small">Add User Flag Rule</a>
                            <div id="DocumentTemplate_OnImportUserFlagRules_AddDialog" class="hiddenDialog" title="On Import User Flag Rule: @(Model.DocumentTemplate.Id)">
                                <div class="brief">
                                    @switch (Model.DocumentTemplate.Scope)
                                    {
                                        case "Device":
                                            <div>
                                                The user flag will be created/removed against the devices assigned user.
                                            </div>
                                            break;
                                        case "Job":
                                            <div>
                                                The user flag will be created/removed against the jobs associated user.
                                            </div>
                                            break;
                                        case "User":
                                            <div>
                                                The user flag will be created/removed against the user.
                                            </div>
                                            break;
                                    }
                                </div>
                                @using (Html.BeginForm(MVC.API.DocumentTemplate.AddOnImportUserFlagRule(Model.DocumentTemplate.Id), FormMethod.Post))
                                {
                                    @Html.AntiForgeryToken()
                                    <div class="distribute-evenly">
                                        <span>
                                            <input id="DocumentTemplate_OnImportUserFlagRules_Add_Create" type="radio" name="addFlag" value="true" checked /><label for="DocumentTemplate_OnImportUserFlagRules_Add_Create">Assign User Flag</label>
                                        </span>
                                        <span>
                                            <input id="DocumentTemplate_OnImportUserFlagRules_Add_Remove" type="radio" name="addFlag" value="false" /><label for="DocumentTemplate_OnImportUserFlagRules_Add_Remove">Remove User Flag</label>
                                        </span>
                                    </div>
                                    <div class="dialog-item-picker">
                                        @foreach (var flag in Model.UserFlags)
                                        {
                                            <div class="item">
                                                <input id="DocumentTemplate_OnImportUserFlagRules_Add_Flag_@flag.Id" type="radio" name="userFlagId" value="@flag.Id" required />
                                                <label for="DocumentTemplate_OnImportUserFlagRules_Add_Flag_@flag.Id"><i class="fa fa-@(flag.Icon) fa-fw fa-lg d-@(flag.IconColour)"></i>@flag.Name</label>
                                            </div>
                                        }
                                    </div>
                                    <div>
                                        <div class="mt-1">
                                            <label for="DocumentTemplate_OnImportUserFlagRules_Add_Comments">Comments</label> <small>(added to the assignment; optional)</small>
                                        </div>
                                        <textarea id="DocumentTemplate_OnImportUserFlagRules_Add_Comments" name="comments"></textarea>
                                    </div>
                                }
                            </div>

                            <script id="DocumentTemplate_OnImportUserFlagRules_AddTemplate" type="text/template">
                    <tr>
                        <td class="rule-action"></td>
                        <td>
                            <i class="rule-flag fa fa-lg"></i>
                            <span class="rule-flag"></span>
                        </td>
                        <td>
                            <span class="rule-comments whitespace-pre-wrap"></span>
                        </td>
                        <td>
                            <i class="fa fa-times-circle fa-lg ajaxRemove" title="Remove"></i>
                            <i class="ajaxLoading" title="Loading..." style="display: none;"></i>
                        </td>
                    </tr>
                    </script>
                    <script type="text/javascript">
                        $(function () {
                            const rulesTable = $('#DocumentTemplate_OnImportUserFlagRules');

                            rulesTable.on('click', '.ajaxRemove', e => {
                                const $remove = $(e.currentTarget);
                                const $target = $remove.closest('tr');
                                const id = $target.attr('data-id');

                                const $loader = $remove.next('.ajaxLoading');
                                $loader.show();
                                $remove.hide();

                                const $form = $('#DocumentTemplate_OnImportUserFlagRules_Remove');
                                $form.find('[name="ruleId"]').val(id);
                                const body = new FormData($form[0]);
                                fetch($form[0].action, {
                                    body: body,
                                    method: 'POST'
                                }).then(r => {
                                    if (r.status === 200) {
                                        $target.remove();

                                        const rows = rulesTable.find('tbody').find('tr');
                                        if (rows.length === 1) {
                                            rows.first().removeClass('hidden');
                                        } else {
                                            rows.first().addClass('hidden');
                                        }
                                    } else {
                                        alert(r.statusText);
                                        $loader.hide();
                                        $remove.show();
                                    }
                                })
                                    .catch(e => {
                                        alert(e);
                                        $loader.hide();
                                        $remove.show();
                                    });
                            });

                            let dialog = null;
                            $('#DocumentTemplate_OnImportUserFlagRules_AddButton').click(e => {
                                e.preventDefault();

                                if (!dialog) {
                                    dialog = $('#DocumentTemplate_OnImportUserFlagRules_AddDialog').dialog({
                                        resizable: false,
                                        modal: true,
                                        autoOpen: false,
                                        width: 460,
                                        buttons: {
                                            "Add Rule": function () {
                                                dialog.dialog("disable");

                                                const form = dialog.find('form')[0];
                                                if (form.reportValidity()) {
                                                    const body = new FormData(form);

                                                    fetch(form.action, {
                                                        method: 'POST',
                                                        body: body
                                                    })
                                                        .then(r => r.json())
                                                        .then(r => {
                                                            const row = $($('#DocumentTemplate_OnImportUserFlagRules_AddTemplate').html());
                                                            row.attr('data-id', r.Id);
                                                            row.find('.rule-action').text(r.AddFlag ? 'Assign' : 'Remove');
                                                            row.find('i.rule-flag').addClass('fa-' + r.UserFlagIcon + ' d-' + r.UserFlagColour);
                                                            row.find('span.rule-flag').text(r.UserFlagName);
                                                            row.find('.rule-comments').text(r.Comments);
                                                            rulesTable.find('tbody').append(row);

                                                            rulesTable.find('tbody').find('tr').first().addClass('hidden');
                                                            
                                                            dialog.dialog("close");
                                                        })
                                                        .catch(e => {
                                                            alert(e);
                                                        })
                                                }
                                            },
                                            Close: function () {
                                                $(this).dialog("close");
                                            }
                                        }
                                    });
                                }

                                dialog.dialog('open');
                                return false;
                            });
                        });
                    </script>
                }
                else
                {
                    if (!Model.OnImportUserFlagRules.Any())
                    {
                        <span class="smallMessage">&lt;None Specified&gt;</span>
                    }
                    else
                    {
                        <table class="tableData">
                            <thead>
                                <tr>
                                    <td>Action</td>
                                    <td>User Flag</td>
                                    <td>Comments</td>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var rule in Model.OnImportUserFlagRules)
                                {
                                    <tr>
                                        <td>@(rule.AddFlag ? "Assign" : "Remove")</td>
                                        <td>
                                            <i class="fa fa-@(rule.UserFlag.Icon) fa-lg d-@(rule.UserFlag.IconColour)"></i>
                                            @if (Authorization.Has(Claims.Config.UserFlag.Configure))
                                            {
                                                <span>@Html.ActionLink(rule.UserFlag.Name, MVC.Config.UserFlag.Index(rule.UserFlag.Id))</span>
                                            }
                                            else
                                            {
                                                <span>@rule.UserFlag.Name</span>
                                            }
                                        </td>
                                        <td>
                                            @if (string.IsNullOrWhiteSpace(rule.Comments))
                                            {
                                                <span>&nbsp;</span>
                                            }
                                            else
                                            {
                                                <span class="whitespace-pre-wrap">@rule.Comments</span>
                                            }
                                        </td>
                                    </tr>
                                }
                            </tbody>
                        </table>
                    }
                }
                        <div class="info-box">
                            <p class="fa-p">
                                <i class="fa fa-fw fa-info-circle"></i>
                                These rules will be applied each time a document is imported (as an attachment) where it is determined the document was based on this template.
                                When creating a user flag assignment, if an assignment already exists the rule will be skipped.
                                When removing user flag assignments, if no assignment is present the rule will be skipped.
                            </p>
                        </div>
                        </td>
                        </tr>
                        <tr>
                            <th>
                                Linked Groups:
                            </th>
                            <td>
                                <div>
                                    @Html.Partial(MVC.Config.Shared.Views.LinkedGroupInstance, new LinkedGroupModel()
                               {
                                   CanConfigure = canConfig,
                                   CategoryDescription = DocumentTemplateUsersManagedGroup.GetCategoryDescription(Model.DocumentTemplate),
                                   Description = DocumentTemplateUsersManagedGroup.GetDescription(Model.DocumentTemplate),
                                   ManagedGroup = Model.UsersLinkedGroup,
                                   IncludeFilterBeginDate = true,
                                   UpdateUrl = Url.Action(MVC.API.DocumentTemplate.UpdateUsersLinkedGroup(Model.DocumentTemplate.Id, redirect: true))
                               })
                                    @Html.Partial(MVC.Config.Shared.Views.LinkedGroupInstance, new LinkedGroupModel()
                               {
                                   CanConfigure = canConfig,
                                   CategoryDescription = DocumentTemplateDevicesManagedGroup.GetCategoryDescription(Model.DocumentTemplate),
                                   Description = DocumentTemplateDevicesManagedGroup.GetDescription(Model.DocumentTemplate),
                                   ManagedGroup = Model.DevicesLinkedGroup,
                                   IncludeFilterBeginDate = true,
                                   UpdateUrl = Url.Action(MVC.API.DocumentTemplate.UpdateDevicesLinkedGroup(Model.DocumentTemplate.Id, redirect: true))
                               })
                                    @if (canConfig)
                                    {
                                        @Html.Partial(MVC.Config.Shared.Views.LinkedGroupShared)
                                    }
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="Config_HideAdvanced_Item">
                <h2>Template Expressions</h2>
                @Html.Partial(MVC.Config.DocumentTemplate.Views._ExpressionsTable, Model.TemplateExpressions)
            </div>
        </div>
        <div id="dialogConfirmDelete" title="Delete this Document Template?" class="dialog">
            <p>
                <i class="fa fa-exclamation-triangle fa-lg warning"></i>This item will be permanently deleted and cannot be recovered.<br />
                <em>
                    This <strong>will not delete attachments</strong> which have already been imported,
                    but any generated documents will no longer be automatically imported.
                </em><br />
                Are you sure?
            </p>
        </div>
        <script type="text/javascript">
            $(function () {
                var button = $('#buttonDelete');
                var buttonDialog = $("#dialogConfirmDelete");
                var buttonLink = button.attr('href');
                button.attr('href', '#');
                button.click(function () {
                    buttonDialog.dialog('open');
                    return false;
                });
                buttonDialog.dialog({
                    resizable: false,
                    modal: true,
                    autoOpen: false,
                    buttons: {
                        "Delete": function () {
                            $this = $(this);
                            $this.dialog('disable');
                            $this.dialog("option", "buttons", null);
                            window.location.href = buttonLink;
                        },
                        Cancel: function () {
                            $(this).dialog("close");
                        }
                    }
                });

            });
        </script>
        <div class="actionBar">
            @if (hideAdvanced)
            {
                <button id="Config_HideAdvanced_Show" class="button">Show Advanced Options</button>
                <script>
                    $(function () {
                        $('#Config_HideAdvanced_Show').click(function () {
                            $('#Config_DocumentTemplates_Show').removeClass('Config_HideAdvanced');
                            $(this).remove();
                        });
                    });
                </script>
            }
            @if (Authorization.Has(Claims.Config.Show))
            {
                @Html.ActionLinkButton("Expression Browser", MVC.Config.Expressions.Browser())
            }
            @if (Authorization.Has(Claims.Config.DocumentTemplate.Export))
            {
                @Html.ActionLinkButton("Export Instances", MVC.Config.DocumentTemplate.Export(Model.DocumentTemplate.Id, null))
            }
            @if (canBulkGenerate)
            {
                if (Model.DocumentTemplate.Scope == DocumentTemplate.DocumentTemplateScopes.User)
                {
                    @Html.ActionLinkButton("Bulk Generate", MVC.Config.DocumentTemplate.BulkGenerate(Model.DocumentTemplate.Id))
                }
                else
                {
                    <a id="buttonBulkGenerate" href="#" class="button">Bulk Generate</a>
                    <div id="dialogBulkGenerate" class="hiddenDialog dialog-bulk-generate" title="Bulk Generate: @(Model.DocumentTemplate.Id)">
                        <div class="brief">
                            @switch (Model.DocumentTemplate.Scope)
                            {
                                case "Device":
                                    <div>
                                        Enter multiple <span class="scopeDescBulkGenerate">Device Serial Numbers</span> separated by <code>&lt;new line&gt;</code>, commas (<code>,</code>) or semicolons (<code>;</code>).
                                    </div>
                                    <div class="examples clearfix">
                                        <h4>Examples:</h4>
                                        <div class="example1 code">
                                            01234567<br />
                                            ABCD9876<br />
                                            8VQ6G2R
                                        </div>
                                        <div class="example2 code">01234567,ABCD9876,8VQ6G2R</div>
                                        <div class="example3 code">01234567;ABCD9876;8VQ6G2R</div>
                                    </div>
                                    break;
                                case "Job":
                                    <div>
                                        Enter multiple <span class="scopeDescBulkGenerate">Job Ids</span> separated by <code>&lt;new line&gt;</code>, commas (<code>,</code>) or semicolons (<code>;</code>).
                                    </div>
                                    <div class="examples clearfix">
                                        <h4>Examples:</h4>
                                        <div class="example1 code">
                                            86<br />
                                            99<br />
                                            44
                                        </div>
                                        <div class="example2 code">86,99,44</div>
                                        <div class="example3 code">86;99;44</div>
                                    </div>
                                    break;
                            }
                        </div>
                        @using (Html.BeginForm(MVC.API.DocumentTemplate.BulkGenerate(Model.DocumentTemplate.Id), FormMethod.Post))
                        {
                            <div class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="DataIds"></div>
                            <textarea id="inputBulkGenerateDataIds" name="DataIds" data-val="true" data-val-required="Identifiers are required"></textarea>
                            if (Model.TemplatePageCount > 1 && Model.TemplatePageCount % 2 != 0)
                            {
                                <div style="margin-top: 6px;">
                                    <input id="inputBulkGenerateInsertBlankPage" type="checkbox" name="InsertBlankPage" value="True" /><label for="inputBulkGenerateInsertBlankPage">Insert Blank Pages for Double-Sided Printing</label>
                                </div>
                            }
                        }
                    </div>

                    <script>
                        $(function () {
                            var dialog;

                            $('#buttonBulkGenerate').click(function () {
                                if (!dialog) {
                                    dialog = $('#dialogBulkGenerate').dialog({
                                        resizable: false,
                                        modal: true,
                                        autoOpen: false,
                                        width: 460,
                                        buttons: {
                                            "Bulk Generate": function () {
                                                dialog.find('form').submit();
                                                dialog.dialog("disable");
                                            },
                                            Close: function () {
                                                $(this).dialog("close");
                                            }
                                        }
                                    });

                                    $.validator.unobtrusive.reparse('#inputBulkGenerateDataIds');
                                }

                                dialog.dialog('open');
                                return false;
                            });
                        });
                    </script>
                }
            }
            @if (Authorization.Has(Claims.Config.DocumentTemplate.Delete))
            {
                @Html.ActionLinkButton("Delete", MVC.API.DocumentTemplate.Delete(Model.DocumentTemplate.Id, true), "buttonDelete")
            }
        </div>
        @if (!string.IsNullOrWhiteSpace(Model.BulkGenerateDownloadId))
        {
            <div id="Config_DocumentTemplates_Show_DownloadBulk_Dialog" class="dialog" title="Download Bulk Documents">
                <a href="@Url.Action(MVC.API.DocumentTemplate.BulkGenerateDownload(Model.BulkGenerateDownloadId, Model.BulkGenerateDownloadFilename))" class="button"><i class="fa fa-download fa-lg"></i>Download Bulk Documents</a>
            </div>
            <script>
                $(function () {
                    $('#Config_DocumentTemplates_Show_DownloadBulk_Dialog')
                        .dialog({
                            width: 400,
                            height: 100,
                            resizable: false,
                            modal: true,
                            autoOpen: true
                        });
                });
            </script>
        }