@model Disco.Web.Areas.Config.Models.DeviceProfile.ShowModel
@using Disco.Services.Devices.ManagedGroups;
@using Disco.Web.Areas.Config.Models.Shared;
@{
    Authorization.Require(Claims.Config.DeviceProfile.Show);

    ViewBag.Title = Html.ToBreadcrumb("Configuration", MVC.Config.Config.Index(), "Device Profiles", MVC.Config.DeviceProfile.Index(null), Model.DeviceProfile.ToString());

    var canConfig = Authorization.Has(Claims.Config.DeviceProfile.Configure);
    var canConfigExpression = Authorization.Has(Claims.Config.DeviceProfile.ConfigureComputerNameTemplate);
    var canDelete = (Authorization.Has(Claims.Config.DeviceProfile.Delete) && Model.CanDelete);

    var hideAdvanced =
        Model.DeviceProfile.AssignedUsersLinkedGroup == null &&
        Model.DeviceProfile.DevicesLinkedGroup == null;

    if (canConfig)
    {
        Html.BundleDeferred("~/Style/Fancytree");
        Html.BundleDeferred("~/ClientScripts/Modules/jQuery-Fancytree");
    }
}
<div id="configurationDeviceProfileShow" class="form@(hideAdvanced ? " Config_HideAdvanced" : null)" style="width: 640px">
    <table>
        <tr>
            <th style="width: 170px;">Id:
            </th>
            <td>
                @Html.DisplayFor(model => model.DeviceProfile.Id)
            </td>
        </tr>
        <tr>
            <th>Name:
            </th>
            <td>@if (canConfig)
                {
                @Html.TextBoxFor(model => model.DeviceProfile.Name)
                @AjaxHelpers.AjaxSave()
                @AjaxHelpers.AjaxLoader()
                <script type="text/javascript">
                    $(function () {
                        var $Name = $('#DeviceProfile_Name');
                        var $NameAjaxSave = $Name.next('.ajaxSave');
                        $Name
                            .watermark('Profile Short Name')
                            .focus(function () { $Name.select() })
                            .keydown(function (e) {
                                $NameAjaxSave.show();
                                if (e.which == 13) {
                                    $(this).blur();
                                }
                            }).blur(function () {
                                $NameAjaxSave.hide();
                            })
                            .change(function () {
                                $NameAjaxSave.hide();
                                var $ajaxLoading = $NameAjaxSave.next('.ajaxLoading').show();
                                var data = { ProfileName: $Name.val() };
                                $.ajax({
                                    url: '@Url.Action(MVC.API.DeviceProfile.UpdateName(Model.DeviceProfile.Id))',
                                    dataType: 'json',
                                    data: data,
                                    success: function (d) {
                                        if (d == 'OK') {
                                            $ajaxLoading.hide().next('.ajaxOk').show().delay('fast').fadeOut('slow');
                                        } else {
                                            $ajaxLoading.hide();
                                            alert('Unable to update name: ' + d);
                                        }
                                    },
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        alert('Unable to update name: ' + textStatus);
                                        $ajaxLoading.hide();
                                    }
                                });
                            });
                    });
                </script>
                }
                else
                {
                @Model.DeviceProfile.Name
                }
            </td>
        </tr>
        <tr>
            <th>Short Name:
            </th>
            <td>@if (canConfig)
                {
                @Html.TextBoxFor(model => model.DeviceProfile.ShortName)
                @AjaxHelpers.AjaxSave()
                @AjaxHelpers.AjaxLoader()
                <script type="text/javascript">
                    $(function () {
                        var $ShortName = $('#DeviceProfile_ShortName');
                        var $ShortNameAjaxSave = $ShortName.next('.ajaxSave');
                        $ShortName
                            .watermark('Profile Short Name')
                            .focus(function () { $ShortName.select() })
                            .keydown(function (e) {
                                $ShortNameAjaxSave.show();
                                if (e.which == 13) {
                                    $(this).blur();
                                }
                            }).blur(function () {
                                $ShortNameAjaxSave.hide();
                            })
                            .change(function () {
                                $ShortNameAjaxSave.hide();
                                var $ajaxLoading = $ShortNameAjaxSave.next('.ajaxLoading').show();
                                var data = { ShortName: $ShortName.val() };
                                $.ajax({
                                    url: '@Url.Action(MVC.API.DeviceProfile.UpdateShortName(Model.DeviceProfile.Id))',
                                    dataType: 'json',
                                    data: data,
                                    success: function (d) {
                                        if (d == 'OK') {
                                            $ajaxLoading.hide().next('.ajaxOk').show().delay('fast').fadeOut('slow');
                                        } else {
                                            $ajaxLoading.hide();
                                            alert('Unable to update short name: ' + d);
                                        }
                                    },
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        alert('Unable to update short name: ' + textStatus);
                                        $ajaxLoading.hide();
                                    }
                                });
                            });
                    });
                </script>
                }
                else
                {
                @Model.DeviceProfile.ShortName
                }
            </td>
        </tr>
        <tr>
            <th>Description:
            </th>
            <td>@if (canConfig)
                {
                @Html.TextBoxFor(model => model.DeviceProfile.Description)
                @AjaxHelpers.AjaxSave()
                @AjaxHelpers.AjaxLoader()
                <script type="text/javascript">
                    $(function () {
                        var $Description = $('#DeviceProfile_Description');
                        var $DescriptionAjaxSave = $Description.next('.ajaxSave');
                        $Description
                            .watermark('Profile Description')
                            .focus(function () { $Description.select() })
                            .keydown(function (e) {
                                $DescriptionAjaxSave.show();
                                if (e.which == 13) {
                                    $(this).blur();
                                }
                            }).blur(function () {
                                $DescriptionAjaxSave.hide();
                            })
                            .change(function () {
                                $DescriptionAjaxSave.hide();
                                var $ajaxLoading = $DescriptionAjaxSave.next('.ajaxLoading').show();
                                var data = { Description: $Description.val() };
                                $.ajax({
                                    url: '@Url.Action(MVC.API.DeviceProfile.UpdateDescription(Model.DeviceProfile.Id))',
                                    dataType: 'json',
                                    data: data,
                                    success: function (d) {
                                        if (d == 'OK') {
                                            $ajaxLoading.hide().next('.ajaxOk').show().delay('fast').fadeOut('slow');
                                        } else {
                                            $ajaxLoading.hide();
                                            alert('Unable to update description: ' + d);
                                        }
                                    },
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        alert('Unable to update description: ' + textStatus);
                                        $ajaxLoading.hide();
                                    }
                                });
                            });
                    });
                </script>
                }
                else
                {
                @Model.DeviceProfile.Description
                }
            </td>
        </tr>
        <tr>
            <th>Members</th>
            <td>
                <div><strong>@Model.DeviceCount.ToString("n0")</strong> @(Model.DeviceCount == 1 ? "devices is a member" : "devices are members") of this profile.</div>
                @if (Model.DeviceDecommissionedCount > 0)
                {
                    <div class="smallMessage">@Model.DeviceDecommissionedCount.ToString("n0") @(Model.DeviceDecommissionedCount == 1 ? "device is" : "devices are") decommissioned.</div>
                }
            </td>
        </tr>
        <tr>
            <th>Distribution Type:
            </th>
            <td>@if (canConfig)
                {
                @Html.DropDownList("DeviceProfile_DistributionType", Model.DeviceProfileDistributionTypes)
                @AjaxHelpers.AjaxLoader()
                <script type="text/javascript">
                    $(function () {
                        $('#DeviceProfile_DistributionType').change(function () {
                            var $this = $(this);
                            var $ajaxLoading = $this.next('.ajaxLoading').show();
                            var data = { DistributionType: $this.val() };
                            $.getJSON('@Url.Action(MVC.API.DeviceProfile.UpdateDistributionType(Model.DeviceProfile.Id))', data, function (response, result) {
                                if (result != 'success' || response != 'OK') {
                                    alert('Unable to change Distribution Type:\n' + response);
                                    $ajaxLoading.hide();
                                } else {
                                    $ajaxLoading.hide().next('.ajaxOk').show().delay('fast').fadeOut('slow');
                                }
                            });
                        });
                    });
                </script>
                }
                else
                {
                @Model.DeviceProfile.DistributionType.ToString()
                }
            </td>
        </tr>
        <tr>
            <th>Address:
            </th>
            <td>@if (canConfig)
                {
                @Html.DropDownListFor(m => m.DeviceProfile.DefaultOrganisationAddress, Model.OrganisationAddresses.ToSelectListItems(Model.DeviceProfile.DefaultOrganisationAddress, true, "None"))
                @AjaxHelpers.AjaxLoader()
                <script type="text/javascript">
                    $(function () {
                        $('#DeviceProfile_DefaultOrganisationAddress').change(function () {
                            var $this = $(this);
                            var $ajaxLoading = $this.next('.ajaxLoading').show();
                            var data = { DefaultOrganisationAddress: $this.val() };
                            $.getJSON('@Url.Action(MVC.API.DeviceProfile.UpdateDefaultOrganisationAddress(Model.DeviceProfile.Id))', data, function (response, result) {
                                if (result != 'success' || response != 'OK') {
                                    alert('Unable to change Address:\n' + response);
                                    $ajaxLoading.hide();
                                } else {
                                    $ajaxLoading.hide().next('.ajaxOk').show().delay('fast').fadeOut('slow');
                                }
                            });
                        });
                    });
                </script>
                }
                else
                {
                    if (Model.DefaultOrganisationAddress == null)
                    {
                <span class="smallMessage">&lt;None Specified&gt;</span>
                    }
                    else
                    {
                @Model.DefaultOrganisationAddress.ToString()
                    }
                }
            </td>
        </tr>
        <tr>
            <th>Allocate Certificates:
            </th>
            <td>@if (canConfig)
                {
                @Html.DropDownListFor(model => model.DeviceProfile.CertificateProviderId, Model.CertificateProviders.ToSelectListItems(null, true, "Not Allocated"))
                @AjaxHelpers.AjaxLoader()
                <script type="text/javascript">
                    $(function () {
                        var $field = $('#DeviceProfile_CertificateProviderId');
                        var $ajaxLoading = $field.next('.ajaxLoading');
                        $field
                        .change(function () {
                            $ajaxLoading.show();
                            var data = { CertificateProviderId: $field.val() };
                            $.ajax({
                                url: '@Url.Action(MVC.API.DeviceProfile.UpdateCertificateProviderId(Model.DeviceProfile.Id))',
                                dataType: 'json',
                                data: data,
                                success: function (d) {
                                    if (d == 'OK') {
                                        $ajaxLoading.hide().next('.ajaxOk').show().delay('fast').fadeOut('slow');
                                    } else {
                                        $ajaxLoading.hide();
                                        alert('Unable to update Certificate Provider Id: ' + d);
                                    }
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    alert('Unable to update Certificate Provider Id: ' + textStatus);
                                    $ajaxLoading.hide();
                                }
                            });
                        });
                    });
                </script>
                }
                else
                {
                    if (string.IsNullOrEmpty(Model.DeviceProfile.CertificateProviderId))
                    {
                <span class="smallMessage">&lt;None Allocated&gt;</span>
                    }
                    else
                    {
                        var cp = Model.CertificateProviders.FirstOrDefault(p => p.Id == Model.DeviceProfile.CertificateProviderId);
                        if (cp == null)
                        {
                <span class="smallMessage">&lt;None Allocated&gt;</span>
                        }
                        else
                        {
                @cp.Name
                        }
                    }
                }
            </td>
        </tr>
        <tr>
            <th>Computer Name<br />
                Template Expression:
            </th>
            <td>@if (canConfig && canConfigExpression)
                {
                @Html.TextBoxFor(model => model.DeviceProfile.ComputerNameTemplate)
                @AjaxHelpers.AjaxSave()
                @AjaxHelpers.AjaxLoader()
                <a id="expressionBrowserAnchor" href="@(Url.Action(MVC.Config.DocumentTemplate.ExpressionBrowser()))">&nbsp;</a>
                <script type="text/javascript">
                    $(function () {
                        var $ComputerNameTemplate = $('#DeviceProfile_ComputerNameTemplate');
                        var $ajaxSave = $ComputerNameTemplate.next('.ajaxSave');
                        $ComputerNameTemplate
                            .focus(function () { $ComputerNameTemplate.select() })
                            .keydown(function (e) {
                                $ajaxSave.show();
                                if (e.which == 13) {
                                    $(this).blur();
                                }
                            }).blur(function () {
                                $ajaxSave.hide();
                            })
                            .change(function () {
                                $ajaxSave.hide();
                                var $ajaxLoading = $ajaxSave.next('.ajaxLoading').show();
                                var data = { ComputerNameTemplate: $ComputerNameTemplate.val() };
                                $.ajax({
                                    url: '@(Url.Action(MVC.API.DeviceProfile.UpdateComputerNameTemplate(Model.DeviceProfile.Id)))',
                                    dataType: 'json',
                                    data: data,
                                    success: function (d) {
                                        if (d == 'OK') {
                                            $ajaxLoading.hide().next('.ajaxOk').show().delay('fast').fadeOut('slow');
                                        } else {
                                            $ajaxLoading.hide();
                                            alert('Unable to update computer name template: ' + d);
                                        }
                                    },
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        alert('Unable to update computer name template: ' + textStatus);
                                        $ajaxLoading.hide();
                                    }
                                });
                            });
                    });
                </script>
                }
                else
                {
                <div id="displayComputerNameTemplate" class="code">
                    @if (string.IsNullOrWhiteSpace(Model.DeviceProfile.ComputerNameTemplate))
                    {
                        <span class="smallMessage">&lt;None Specified&gt;</span>
                    }
                    else
                    {
                        @Model.DeviceProfile.ComputerNameTemplate
                    }
                </div>
                }
                <div style="margin-top: 8px;">
                    @if (canConfig)
                    {
                        <input id="DeviceProfile_EnforceComputerNameConvention" type="checkbox" @(Model.DeviceProfile.EnforceComputerNameConvention ? new MvcHtmlString("checked=\"checked\" ") : new MvcHtmlString(string.Empty))/>
                        <script type="text/javascript">
                            $(function () {
                                $('#DeviceProfile_EnforceComputerNameConvention').click(function () {
                                    var $this = $(this);
                                    var $ajaxLoading = $this.nextAll('.ajaxLoading').show();
                                    var data = { EnforceComputerNameConvention: $this.is(':checked') };
                                    $.getJSON('@Url.Action(MVC.API.DeviceProfile.UpdateEnforceComputerNameConvention(Model.DeviceProfile.Id))', data, function (response, result) {
                                        if (result != 'success' || response != 'OK') {
                                            alert('Unable to change Enforce Computer Name Convention:\n' + response);
                                            $ajaxLoading.hide();
                                        } else {
                                            $ajaxLoading.hide().next('.ajaxOk').show().delay('fast').fadeOut('slow');
                                        }
                                    });
                                });
                            });
                        </script>
                    }
                    else
                    {
                        <input id="DeviceProfile_EnforceComputerNameConvention" type="checkbox" @(Model.DeviceProfile.EnforceComputerNameConvention ? new MvcHtmlString("checked=\"checked\" ") : new MvcHtmlString(string.Empty)) disabled="disabled" />
                    }
                    <label for="DeviceProfile_EnforceComputerNameConvention">
                        Enforce Naming Convention
                    </label>
                    @AjaxHelpers.AjaxLoader()
                </div>
                <div class="smallMessage" style="margin-top: 8px;">
                    Note: Computer names are only changed when Active Directory accounts are provisioned.
                </div>
            </td>
        </tr>
        <tr>
            <th>Policies</th>
            <td>
                <div>
                    @if (canConfig)
                    {
                        <input id="DeviceProfile_ProvisionADAccount" type="checkbox" @(Model.DeviceProfile.ProvisionADAccount ? new MvcHtmlString("checked=\"checked\" ") : new MvcHtmlString(string.Empty))/>
                        <script type="text/javascript">
                            $(function () {
                                $('#DeviceProfile_ProvisionADAccount').click(function () {
                                    var $this = $(this);
                                    var $ajaxLoading = $this.nextAll('.ajaxLoading').show();
                                    var data = { ProvisionADAccount: $this.is(':checked') };
                                    $.getJSON('@Url.Action(MVC.API.DeviceProfile.UpdateProvisionADAccount(Model.DeviceProfile.Id))', data, function (response, result) {
                                        if (result != 'success' || response != 'OK') {
                                            alert('Unable to change Provision AD Account:\n' + response);
                                            $ajaxLoading.hide();
                                        } else {
                                            $ajaxLoading.hide().next('.ajaxOk').show().delay('fast').fadeOut('slow');
                                        }
                                    });
                                });
                            });
                        </script>
                    }
                    else
                    {
                        <input id="DeviceProfile_ProvisionADAccount" type="checkbox" @(Model.DeviceProfile.ProvisionADAccount ? new MvcHtmlString("checked=\"checked\" ") : new MvcHtmlString(string.Empty)) disabled="disabled" />
                    }
                    <label for="DeviceProfile_ProvisionADAccount">
                        Provision Active Directory Account
                    </label>
                    @AjaxHelpers.AjaxLoader()
                </div>
                <div style="margin-top: 8px;">
                    @if (canConfig)
                    {
                        <input id="DeviceProfile_AssignedUserLocalAdmin" type="checkbox" @(Model.DeviceProfile.AssignedUserLocalAdmin ? new MvcHtmlString("checked=\"checked\" ") : new MvcHtmlString(string.Empty))/>
                        <script type="text/javascript">
                            $(function () {
                                $('#DeviceProfile_AssignedUserLocalAdmin').click(function () {
                                    var $this = $(this);
                                    var $ajaxLoading = $this.nextAll('.ajaxLoading').show();
                                    var data = { AssignedUserLocalAdmin: $this.is(':checked') };
                                    $.getJSON('@Url.Action(MVC.API.DeviceProfile.UpdateAssignedUserLocalAdmin(Model.DeviceProfile.Id))', data, function (response, result) {
                                        if (result != 'success' || response != 'OK') {
                                            alert('Unable to change Assigned User Is Local Administrator:\n' + response);
                                            $ajaxLoading.hide();
                                        } else {
                                            $ajaxLoading.hide().next('.ajaxOk').show().delay('fast').fadeOut('slow');
                                        }
                                    });
                                });
                            });
                        </script>
                    }
                    else
                    {
                        <input id="DeviceProfile_AssignedUserLocalAdmin" type="checkbox" @(Model.DeviceProfile.AssignedUserLocalAdmin ? new MvcHtmlString("checked=\"checked\" ") : new MvcHtmlString(string.Empty)) disabled="disabled" />
                    }
                    <label for="DeviceProfile_AssignedUserLocalAdmin">
                        Assigned User is Local Administrator
                    </label>
                    @AjaxHelpers.AjaxLoader()
                </div>
                <div style="margin-top: 8px;">
                    @if (canConfig)
                    {
                        <input id="DeviceProfile_AllowUntrustedReimageJobEnrolment" type="checkbox" @(Model.DeviceProfile.AllowUntrustedReimageJobEnrolment ? new MvcHtmlString("checked=\"checked\" ") : null)/>
                        <script type="text/javascript">
                            $(function () {
                                $('#DeviceProfile_AllowUntrustedReimageJobEnrolment').click(function () {
                                    var $this = $(this);
                                    var $ajaxLoading = $this.nextAll('.ajaxLoading').show();
                                    var data = { AllowUntrustedReimageJobEnrolment: $this.is(':checked') };
                                    $.getJSON('@Url.Action(MVC.API.DeviceProfile.UpdateAllowUntrustedReimageJobEnrolment(Model.DeviceProfile.Id))', data, function (response, result) {
                                        if (result != 'success' || response != 'OK') {
                                            alert('Unable to change Allow Untrusted Reimage Job Enrolment:\n' + response);
                                            $ajaxLoading.hide();
                                        } else {
                                            $ajaxLoading.hide().next('.ajaxOk').show().delay('fast').fadeOut('slow');
                                        }
                                    });
                                });
                            });
                        </script>
                    }
                    else
                    {
                        <input id="DeviceProfile_AllowUntrustedReimageJobEnrolment" type="checkbox" @(Model.DeviceProfile.AllowUntrustedReimageJobEnrolment ? new MvcHtmlString("checked=\"checked\" ") : new MvcHtmlString(string.Empty)) disabled="disabled" />
                    }
                    <label for="DeviceProfile_AllowUntrustedReimageJobEnrolment">
                        Allow Untrusted Enrolment Where a <span class="code">'Software - Reimage'</span> Job is Open
                    </label>
                    @AjaxHelpers.AjaxLoader()
                </div>
            </td>
        </tr>
        <tr>
            <th>Organisational Unit:
            </th>
            <td>@if (canConfig)
                {
                <div id="DeviceProfile_OrganisationalUnit" class="code" data-value="@Model.DeviceProfile.OrganisationalUnit">
                    <span>
                        @Model.FriendlyOrganisationalUnitName
                    </span>
                </div>
                <a id="changeOrganisationalUnit" href="#" class="button small">Change</a>@AjaxHelpers.AjaxLoader()
                <div id="dialogOrganisationalUnit" title="Organisational Unit" class="dialog">
                    <div id="dialogOrganisationalUnit_Loading">
                        @AjaxHelpers.AjaxLoader() Loading Organisational Units
                    </div>
                    <div id="treeOrganisationalUnit" class="organisationalUnitTree">
                    </div>
                </div>
                <script type="text/javascript">
                    $(function () {
                        var ouSetUrl = '@Url.Action(MVC.API.DeviceProfile.UpdateOrganisationalUnit(Model.DeviceProfile.Id, null, true))';
                        var ouValue = $('#DeviceProfile_OrganisationalUnit').attr('data-value');
                        var $ouTree = null;
                        var ouTree = null;
                        var $dialog = null;
                        var ouSet = function (ou) {
                            var url = ouSetUrl + '&' + $.param({ OrganisationalUnit: ou })
                            window.location.href = url;
                        }
                        var expandNodeTree = function (node) {
                            var parent = node.parent;
                            if (parent) {
                                expandNodeTree(parent);
                                parent.setExpanded(true, { noAnimation: true, noEvents: false });
                            }
                        }
                        var expandAndFocusNode = function (nodeKey) {
                            if (ouTree) {
                                var ouNode = ouTree.getNodeByKey(ouValue);
                                if (ouNode) {
                                    expandNodeTree(ouNode);
                                    ouNode.setFocus(true);
                                    ouNode.setActive(true);

                                    var li = ouNode.li;
                                    var liOffset = li.offsetParent;
                                    if (li.offsetTop + li.offsetHeight > liOffset.offsetHeight)
                                        $(liOffset).animate({ 'scrollTop': li.offsetTop - liOffset.offsetHeight + li.offsetHeight + 4 }, 'fast');
                                }
                            }
                        }
                        var ouChange = function () {
                            if (!$dialog) {

                                $dialog = $('#dialogOrganisationalUnit').dialog({
                                    autoOpen: false,
                                    buttons: null,
                                    draggable: false,
                                    modal: true,
                                    resizable: false,
                                    width: 500,
                                    height: 500
                                });
                                $loading = $('#dialogOrganisationalUnit_Loading');
                                $loading.find('i.ajaxLoading').show();

                                $ouTree = $('#treeOrganisationalUnit');
                                $dialog.css('overflow', 'visible');
                                $ouTree.css('height', '100%');

                                $.getJSON('@(Url.Action(MVC.API.System.DomainOrganisationalUnits()))', null, function (data) {
                                    $loading.hide();

                                    // Make 'Domains' unselectable
                                    $.each(data, function (i, node) {
                                        node.unselectable = true;
                                    });

                                    ouTree = $ouTree.fancytree({
                                        source: data,
                                        checkbox: false,
                                        selectMode: 1,
                                        keyboard: false,
                                        fx: null
                                    }).fancytree('getTree');

                                    ouTree.$container.css('position', 'relative');

                                    // Set Buttons
                                    $dialog.dialog('option', 'buttons', {
                                        'Use Default Container': function () {
                                            var $this = $(this);
                                            $this.css('overflow', 'hidden');
                                            $this.dialog("disable");
                                            $this.dialog("option", "buttons", null);
                                            ouSet('');
                                        },
                                        'Save': function () {
                                            var node = ouTree.getActiveNode();
                                            if (node && node.key.substr(0, 3).toLowerCase() == 'ou=') {
                                                var $this = $(this);
                                                $this.css('overflow', 'hidden');
                                                $this.dialog("disable");
                                                $this.dialog("option", "buttons", null);
                                                ouSet(node.key);
                                            } else {
                                                alert('Select an Organisational Unit to Save')
                                            }
                                        }
                                    });

                                    // Expand
                                    expandAndFocusNode(ouValue);

                                    ouTree.options.fx = { height: "toggle", duration: 200 };
                                });
                            }
                            $dialog.dialog('open');

                            if (ouTree) {
                                // Expand
                                expandAndFocusNode(ouValue);
                            }

                            return false;
                        };

                        $('#changeOrganisationalUnit').click(ouChange);
                    });
                </script>
                }
                else
                {
                <div id="displayOrganisationalUnit" class="code">
                    <span>
                        @Model.FriendlyOrganisationalUnitName
                    </span>
                </div>
                }
                <div style="margin-top: 8px;">
                    @if (canConfig)
                    {
                        <input id="DeviceProfile_EnforceOrganisationalUnit" type="checkbox" @(Model.DeviceProfile.EnforceOrganisationalUnit ? new MvcHtmlString("checked=\"checked\" ") : new MvcHtmlString(string.Empty))/>
                        <script type="text/javascript">
                            $(function () {
                                $('#DeviceProfile_EnforceOrganisationalUnit').click(function () {
                                    var $this = $(this);
                                    var $ajaxLoading = $this.nextAll('.ajaxLoading').show();
                                    var data = { EnforceOrganisationalUnit: $this.is(':checked') };
                                    $.getJSON('@Url.Action(MVC.API.DeviceProfile.UpdateEnforceOrganisationalUnit(Model.DeviceProfile.Id))', data, function (response, result) {
                                        if (result != 'success' || response != 'OK') {
                                            alert('Unable to change Enforce Organisation Unit:\n' + response);
                                            $ajaxLoading.hide();
                                        } else {
                                            $ajaxLoading.hide().next('.ajaxOk').show().delay('fast').fadeOut('slow');
                                        }
                                    });
                                });
                            });
                        </script>
                    }
                    else
                    {
                        <input id="DeviceProfile_EnforceOrganisationalUnit" type="checkbox" @(Model.DeviceProfile.EnforceOrganisationalUnit ? new MvcHtmlString("checked=\"checked\" ") : new MvcHtmlString(string.Empty)) disabled="disabled" />
                    }
                    <label for="DeviceProfile_EnforceOrganisationalUnit">
                        Enforce Organisational Unit
                    </label>
                    @AjaxHelpers.AjaxLoader()
                </div>
            </td>
        </tr>
        @if (hideAdvanced)
        {
            <tr>
                <td colspan="2" style="text-align: right;">
                    <button id="Config_HideAdvanced_Show" class="button small">Show Advanced Options</button>
                    <script>
                        $(function () {
                            $('#Config_HideAdvanced_Show').click(function () {
                                var $this = $(this);
                                $this.closest('.Config_HideAdvanced').removeClass('Config_HideAdvanced');
                                $this.closest('tr').remove();
                            });
                        });
                    </script>
                </td>
            </tr>
        }
        <tr class="Config_HideAdvanced_Item">
            <th>Linked Groups:
            </th>
            <td>
                <div>
                    @Html.Partial(MVC.Config.Shared.Views.LinkedGroupInstance, new LinkedGroupModel()
               {
                   CanConfigure = canConfig,
                   CategoryDescription = DeviceProfileDevicesManagedGroup.GetCategoryDescription(Model.DeviceProfile),
                   Description = DeviceProfileDevicesManagedGroup.GetDescription(Model.DeviceProfile),
                   ManagedGroup = Model.DevicesLinkedGroup,
                   UpdateUrl = Url.Action(MVC.API.DeviceProfile.UpdateDevicesLinkedGroup(Model.DeviceProfile.Id, redirect: true))
               })
                    @Html.Partial(MVC.Config.Shared.Views.LinkedGroupInstance, new LinkedGroupModel()
               {
                   CanConfigure = canConfig,
                   CategoryDescription = DeviceProfileAssignedUsersManagedGroup.GetCategoryDescription(Model.DeviceProfile),
                   Description = DeviceProfileAssignedUsersManagedGroup.GetDescription(Model.DeviceProfile),
                   ManagedGroup = Model.AssignedUsersLinkedGroup,
                   UpdateUrl = Url.Action(MVC.API.DeviceProfile.UpdateAssignedUsersLinkedGroup(Model.DeviceProfile.Id, redirect: true))
               })
                    @if (canConfig)
                    {
                        @Html.Partial(MVC.Config.Shared.Views.LinkedGroupShared)
                    }
                </div>
            </td>
        </tr>
    </table>
</div>
@if (canDelete)
{
    <div id="dialogConfirmDelete" title="Delete this Device Profile?">
        <p>
            <i class="fa fa-exclamation-triangle fa-lg warning"></i>
            This item will be permanently deleted and cannot be recovered. Are you sure?
        </p>
    </div>
    <script type="text/javascript">
        $(function () {

            var button = $('#buttonDelete');
            var buttonLink = button.attr('href');
            button.attr('href', '#');
            button.click(function () {
                $("#dialogConfirmDelete").dialog('open');
            });

            $("#dialogConfirmDelete").dialog({
                resizable: false,
                height: 140,
                modal: true,
                autoOpen: false,
                buttons: {
                    "Delete": function () {
                        $(this).dialog('disable');
                        window.location.href = buttonLink;
                    },
                    Cancel: function () {
                        $(this).dialog("close");
                    }
                }
            });

        });
    </script>
}
<div class="actionBar">
    @if (canDelete)
    { 
        @Html.ActionLinkButton("Delete", MVC.API.DeviceProfile.Delete(Model.DeviceProfile.Id, true), "buttonDelete")
    }
    @if (Authorization.Has(Claims.Device.Actions.Export))
    {
        @Html.ActionLinkButton("Export Devices", MVC.Device.Export(null, Disco.Models.Services.Devices.Exporting.DeviceExportTypes.Profile, Model.DeviceProfile.Id))
    }
    @if (Authorization.Has(Claims.Device.Search) && Model.DeviceCount > 0)
    {
        @Html.ActionLinkButton(string.Format("View {0} Device{1}", Model.DeviceCount, (Model.DeviceCount != 1 ? "s" : null)), MVC.Search.Query(Model.DeviceProfile.Id.ToString(), "DeviceProfile"))
    }
</div>
