@model Disco.Web.Models.User.ShowModel
@{
    Authorization.Require(Claims.User.ShowAttachments);

    var canAddAttachments = Authorization.Has(Claims.User.Actions.AddAttachments);
    var canRemoveAnyAttachments = Authorization.Has(Claims.User.Actions.RemoveAnyAttachments);
    var canRemoveOwnAttachments = Authorization.Has(Claims.User.Actions.RemoveOwnAttachments);

    Html.BundleDeferred("~/Style/Shadowbox");
    Html.BundleDeferred("~/ClientScripts/Modules/Shadowbox");
    Html.BundleDeferred("~/ClientScripts/Modules/jQuery-SignalR");

    if (canAddAttachments)
    {
        Html.BundleDeferred("~/ClientScripts/Modules/Silverlight");
    }
}
<div id="UserDetailTab-Resources" class="UserPart">
    <table id="userShowResources">
        <tr>
            <td id="Attachments" class="@(canAddAttachments ? "canAddAttachments" : "cannotAddAttachments")">
                <div class="attachmentOutput">
                    @if (Model.User.UserAttachments != null)
                    {
                        foreach (var ua in Model.User.UserAttachments)
                        {
                        <a href="@Url.Action(MVC.API.User.AttachmentDownload(ua.Id))" data-attachmentid="@ua.Id" data-mimetype="@ua.MimeType">
                            <span class="icon" title="@ua.Filename">
                                <img alt="Attachment Thumbnail" src="@(Url.Action(MVC.API.User.AttachmentThumbnail(ua.Id)))" /></span>
                            <span class="comments" title="@ua.Comments">
                                @{if (!string.IsNullOrEmpty(ua.DocumentTemplateId))
                                  { @ua.DocumentTemplate.Description}
                                  else
                                  { @ua.Comments }}
                            </span><span class="author">@ua.TechUser.ToStringFriendly()</span>@if (canRemoveAnyAttachments || (canRemoveOwnAttachments && ua.TechUserId == CurrentUser.UserId))
                                                                                              {<text><span class="remove fa fa-times-circle"></span></text>}<span class="timestamp" data-livestamp="@(ua.Timestamp.ToUnixEpoc())" title="@ua.Timestamp.ToFullDateTime()">@ua.Timestamp.ToFullDateTime()</span>
                        </a>   
                        }
                    }
                </div>
                @if (canAddAttachments)
                {
                    <div class="attachmentInput clearfix">
                        <span class="action upload fa fa-upload" title="Attach File"></span><span class="action photo fa fa-camera" title="Capture Image"></span>
                    </div>
                }
                <script type="text/javascript">
                    Shadowbox.init({
                        skipSetup: true,
                        modal: true
                    });
                    $(function () {
                        var $Attachments = $('#Attachments');
                        var $attachmentOutput = $Attachments.find('.attachmentOutput');
                        var $dialogUpload = null;
                        var $dialogRemoveAttachment = null;

                        // Connect to Hub
                        var hub = $.connection.userUpdates;

                        // Map Functions
                        hub.client.addAttachment = onAddAttachment;
                        hub.client.removeAttachment = onRemoveAttachment;

                        $.connection.hub.qs = { UserId: '@(Model.User.UserId.Replace(@"\", @"\\"))' };
                        $.connection.hub.error(onHubError);

                        // Start Connection
                        $.connection.hub.start().fail(onHubError);

                        function onHubError(error) {
                            alert('Live-update Error: ' + error);
                        }

                        function onAddAttachment(id, quick) {
                            var data = { id: id };
                            $.ajax({
                                url: '@Url.Action(MVC.API.User.Attachment())',
                                dataType: 'json',
                                data: data,
                                success: function (d) {
                                    if (d.Result == 'OK') {
                                        var a = d.Attachment;
                                        @if (canRemoveAnyAttachments)
                                        {
                                        <text>buildAttachment(a, true, quick);</text>
                                        }
                                        else if (canRemoveOwnAttachments)
                                        {
                                        <text>buildAttachment(a, (a.AuthorId === '@(CurrentUser.UserId)'), quick);</text>
                                        }
                                        else
                                        {
                                        <text>buildAttachment(a, false, quick);</text>
                                        }
                                    } else {
                                        alert('Unable to add attachment: ' + d.Result);
                                    }
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    alert('Unable to add attachment: ' + textStatus);
                                }
                            });
                        }
                        function buildAttachment(a, canRemove, quick) {
                            var t = '<a><span class="icon"><img alt="Attachment Thumbnail" /></span><span class="comments"></span><span class="author"></span>';
                            if (canRemove)
                                t += '<span class="remove fa fa-times-circle"></span>';
                            t += '<span class="timestamp"></span></a>';

                            var e = $(t);

                            e.attr('data-attachmentid', a.Id).attr('data-mimetype', a.MimeType).attr('href', '@(Url.Action(MVC.API.User.AttachmentDownload()))/' + a.Id);
                            e.find('.icon img').attr('src', '@(Url.Action(MVC.API.User.AttachmentThumbnail()))/' + a.Id);
                            e.find('.comments').text(a.Description);
                            e.find('.author').text(a.Author);
                            e.find('.timestamp').text(a.TimestampFull).attr('title', a.TimestampFull).livestamp(a.TimestampUnixEpoc);
                            if (canRemove)
                                e.find('.remove').click(removeAttachment);
                            if (!quick)
                                e.hide();
                            $attachmentOutput.append(e);
                            onUpdate();
                            if (!quick)
                                e.show('slow');
                            if (a.MimeType.toLowerCase().indexOf('image/') == 0)
                                e.shadowbox({ gallery: 'attachments', player: 'img', title: a.Description });
                            else
                                e.click(onDownload);
                        }

                        function onDownload() {
                            var $this = $(this);
                            var url = $this.attr('href');

                            if ($.connection && $.connection.hub && $.connection.hub.transport &&
                                                $.connection.hub.transport.name == 'foreverFrame') {
                                // SignalR active with foreverFrame transport - use popup window
                                window.open(url, '_blank', 'height=150,width=250,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no');
                            } else {
                                // use iFrame
                                if (!$attachmentDownloadHost) {
                                    $attachmentDownloadHost = $('<iframe>')
                                        .attr({ 'src': url, 'title': 'Attachment Download Host' })
                                        .addClass('hidden')
                                        .appendTo('body')
                                        .contents();
                                } else {
                                    $attachmentDownloadHost[0].location.href = url;
                                }
                            }

                            return false;
                        }

                        function onRemoveAttachment(id) {
                            var a = $attachmentOutput.find('a[data-attachmentid=' + id + ']');

                            a.hide(300).delay(300).queue(function () {
                                var $this = $(this);
                                if ($this.attr('data-mimetype').toLowerCase().indexOf('image/') == 0)
                                    Shadowbox.removeCache(this);
                                $this.find('.timestamp').livestamp('destroy');
                                $this.remove();
                                onUpdate();
                            });
                        }

                        function onUpdate() {
                            var attachmentCount = $attachmentOutput.children('a').length;
                            var tabHeading = 'Attachments [' + attachmentCount + ']';
                            $('#UserDetailTab-ResourcesLink').text(tabHeading);
                        }

                        @if (canAddAttachments)
                        {<text>
                        //#region Add Attachments
                        if (!document.DiscoFunctions) {
                            document.DiscoFunctions = {};
                        }
                        document.DiscoFunctions.addAttachment = function (Id) { return; /* Silverlight notification, do nothing use SignalR */ };

                        var $attachmentInput = $Attachments.find('.attachmentInput');
                        $attachmentInput.find('.photo').click(function () {
                            showDialog('/WebCam');
                        });
                        $attachmentInput.find('.upload').click(function () {
                            showDialog('/File');
                        });

                        var silverlightOnLoadNavigation = null;
                        var silverlightIsLoaded = null;

                        function showDialog(navigationPath) {
                            if (!$dialogUpload) {
                                $dialogUpload = $('#dialogUpload').dialog({
                                    autoOpen: false,
                                    draggable: false,
                                    modal: true,
                                    resizable: false,
                                    width: 860,
                                    height: 550,
                                    close: function () {
                                        var sl = $('#silverlightUploadAttachment').get(0);
                                        if (sl.content)
                                            sl.content.Navigator.Navigate('/Hidden');
                                    }
                                });

                                Silverlight.createObject('@(Links.ClientBin.Disco_Silverlight_AttachmentUpload_xap)',
                                    $('#silverlightHostUploadAttachment').get(0),
                                    'silverlightUploadAttachment',
                                    { width: '840px', height: '500px', background: 'white', version: '4.0.60310.0' },
                                    {
                                        onLoad: function () {
                                            if (silverlightOnLoadNavigation) {
                                                $('#silverlightUploadAttachment').get(0).content.Navigator.Navigate(silverlightOnLoadNavigation);
                                                silverlightIsLoaded = true;
                                            }
                                        }
                                    },
                                    'UploadUrl=@(Url.Action(MVC.API.User.AttachmentUpload(Model.User.UserId, null)))');
                            }

                            $dialogUpload.dialog('open');
                            if (silverlightIsLoaded) {
                                $('#silverlightUploadAttachment').get(0).content.Navigator.Navigate(navigationPath);
                            } else {
                                silverlightOnLoadNavigation = navigationPath;
                            }
                        };

                        //#endregion
                        </text>}
                        @if (canRemoveAnyAttachments || canRemoveOwnAttachments)
                        {<text>
                        //#region Remove Attachments

                        $attachmentOutput.find('span.remove').click(removeAttachment);

                        function removeAttachment() {
                            $this = $(this).closest('a');

                            var data = { id: $this.attr('data-attachmentid') };

                            if (!$dialogRemoveAttachment) {
                                $dialogRemoveAttachment = $('#dialogRemoveAttachment').dialog({
                                    resizable: false,
                                    height: 140,
                                    modal: true,
                                    autoOpen: false
                                });
                            }

                            $dialogRemoveAttachment.dialog("enable");
                            $dialogRemoveAttachment.dialog('option', 'buttons', {
                                "Remove": function () {
                                    $dialogRemoveAttachment.dialog("disable");
                                    $dialogRemoveAttachment.dialog("option", "buttons", null);
                                    $.ajax({
                                        url: '@Url.Action(MVC.API.User.AttachmentRemove())',
                                        dataType: 'json',
                                        data: data,
                                        success: function (d) {
                                            if (d == 'OK') {
                                                // Do nothing, await SignalR notification
                                            } else {
                                                alert('Unable to remove attachment: ' + d);
                                            }
                                            $dialogRemoveAttachment.dialog("close");
                                        },
                                        error: function (jqXHR, textStatus, errorThrown) {
                                            alert('Unable to remove attachment: ' + textStatus);
                                            $dialogRemoveAttachment.dialog("close");
                                        }
                                    });
                                },
                                Cancel: function () {
                                    $dialogRemoveAttachment.dialog("close");
                                }
                            });

                            $dialogRemoveAttachment.dialog('open');

                            return false;
                        }

                        //#endregion
                        </text>}

                        $attachmentOutput.children('a').each(function () {
                            $this = $(this);
                            if ($this.attr('data-mimetype').toLowerCase().indexOf('image/') == 0)
                                $this.shadowbox({ gallery: 'attachments', player: 'img', title: $this.find('.comments').text() });
                            else
                                $this.click(onDownload);
                        });
                    });
                </script>
            </td>
        </tr>
    </table>
    <script>
        $('#UserDetailTabItems').append('<li><a href="#UserDetailTab-Resources" id="UserDetailTab-ResourcesLink">Attachments [@(Model.User.UserAttachments == null ? 0 : Model.User.UserAttachments.Count)]</a></li>');
    </script>
</div>
@if (canAddAttachments)
{
    <div id="dialogUpload" class="dialog" title="Upload Attachment">
        <div id="silverlightHostUploadAttachment">
        </div>
    </div>
}
@if (canRemoveAnyAttachments || canRemoveOwnAttachments)
{
    <div id="dialogRemoveAttachment" class="dialog" title="Remove this Attachment?">
        <p>
            <i class="fa fa-exclamation-triangle fa-lg"></i>&nbsp;Are you sure?
        </p>
    </div>
}