var Wick = Wick || {};
Wick.ShareProjectList = (function () {
    
    function init() {
        var shoppingListLinkInput = $('#share-list-modal #shopping-list-link'),
            shoppingListLinkEl = shoppingListLinkInput[0],
            linkContainer = $('#copy-link'),
            actualLink = linkContainer.find('a'),
            copyClass = 'copy-link_hovered';
        
        actualLink.click(function (e) {
            e.preventDefault();
        });
        
        linkContainer.click(function () {
            if (navigator.userAgent.match(/TradeProMobile_iOS|DIYMobile_iOS/i)) {
                iosCopyToClipboard(shoppingListLinkInput);
            } else if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
                shoppingListLinkEl.select();
                shoppingListLinkEl.setSelectionRange(0, 999999);
            } else {
                shoppingListLinkEl.select();
            }

            document.execCommand("copy");
            actualLink.addClass(copyClass);
        });

        shoppingListLinkInput.click(function () {
            linkContainer.click();
            actualLink.removeClass(copyClass);
        });
    }

    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();
})();
