var Wick = Wick || {};
Wick.TradeProVoucher = (function () {
    
    function init() {
        $('.copy-barcode').on('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            var discountCode = $(this).parent().find('input');
            
            if (discountCode.length === 0) {
                discountCode = $('.tradepro-frame');
            }
    
            discountCode.removeAttr('disabled').attr('readonly', 'readonly');

            if (navigator.userAgent.match(/TradeProMobile_iOS|DIYMobile_iOS/i)) {
                iosCopyToClipboard(discountCode);
            } else if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
                discountCode[0].select();
                discountCode[0].setSelectionRange(0, 999999);
            } else {
                discountCode[0].select();
            }

            document.execCommand("copy");
            discountCode.attr('disabled', 'disabled').removeAttr('readonly');
            
            Wick.Notification.show({
                text: 'Code copied to clipboard',
                container: $(this).parents('.row').eq(0).find('.copy-barcode_notification'),
                type: 'success',
                noScrolling: true,
                temporary: true,
                delay: 5000,
                closeBtn: true
            });
            return false;
        });
    }

    function iosCopyToClipboard($input) {
        var el = $input.get(0);
        var editable = el.contentEditable;
        var readOnly = el.readOnly;

        el.contentEditable = true;
        el.readOnly = false;
        var range = document.createRange();
        range.selectNodeContents(el);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
        el.setSelectionRange(0, 999999);
        el.contentEditable = editable;
        el.readOnly = readOnly;
    }

    init();
})();
