// #lightbox doesn't exist yet, so wait a bit (could be improved)
window.setTimeout(function() {
    // Callback when the image in the modal changes
    var observer = new MutationObserver(function(mutations) {

        // Get the icon element or create it if it doesn't exist yet
        var downloadLink = $('#lightbox #lb-download-link');
        if (downloadLink.length === 0)
        {
            // Insert the markup
            $('#lightbox .lb-closeContainer').before('<a id="lb-download-link" ' +
                'target="_blank" download="" class="btn btn-sm ml-auto btn-img-lightbox-download"' +
                'aria-label="'+ lmsg("common.cla_comments.image.download_full_image") +'" title="'+ lmsg("common.cla_comments.image.download_full_image") +'">' +
                '<ion-icon name="download-outline"></ion-icon>' +
                '</a>');
            downloadLink = $('#lightbox #lb-download-link');

            // Add a click handler to override lightbox
            downloadLink.on('click', function(evt) {
                // Stop the event going further and lightbox absorbing it
                evt.stopPropagation();

                // But don't return anything. We haven't handled it and want DOM to do its default a href thing
            });
        }
        // Take the preview image URL and strip the '/lg' from the end to get the full size image URL
        var url = $('#lightbox .lb-image').prop('src').slice(0, -3);

        // Change the href of the download icon to match the preview
        downloadLink.prop('href', url);

        $('#lightbox .lb-closeContainer .lb-close').attr({
            role: 'button',
            'aria-label': lmsg("common.cla_comments.close"),
        }).addClass('btn btn-sm').html('<ion-icon name="close-outline"></ion-icon>');
    });

    // Lightbox doesn't emit events so manually watch for the image src attribute changing
    observer.observe($('#lightbox .lb-image')[0], {
        attributes: true,
        attributeFilter: ['src'] });
}, 500);
