(function() {
    function fallbackCopyTextToClipboard(text) {
        var textArea = document.createElement("textarea");
        textArea.value = text;

        // Avoid scrolling to bottom
        textArea.style.top = "0";
        textArea.style.left = "0";
        textArea.style.position = "fixed";

        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Fallback: Copying text command was ' + msg);
            toastr.success('Copied!');
        } catch (err) {
            console.error('Fallback: Oops, unable to copy', err);
        }

        document.body.removeChild(textArea);
    }
    function copyTextToClipboard(text) {
        if (!navigator.clipboard) {
            fallbackCopyTextToClipboard(text);
            return;
        }
        navigator.clipboard.writeText(text).then(function() {
            console.log('Async: Copying to clipboard was successful!');
            toastr.success('Copied!');
        }, function(err) {
            console.error('Async: Could not copy text: ', err);
        });
    }

    function init() {
        $(document)
            .off('click.click-to-copy', '.click-to-copy')
            .on('click.click-to-copy', '.click-to-copy', function(event) {
            copyTextToClipboard($(this).text());
        });
        window.copyTextToClipboard = copyTextToClipboard;
    }

    addMCInitializer('click-to-copy', init);

}).call(window);
