% # vim:set sw=4 ts=4 sts=4 ft=javascript expandtab:
window.gallery_url = '<%= prefix().'gallery' %>#';
window.zip_url = '<%= prefix().'zip' %>?i=';
window.random_url = '<%= prefix().'random' %>?i=';
window.short_hash = {};
window.zip_hash = {};
window.random_hash = {};
function addToShortHash(short) {
    window.short_hash[short] = 1;
    if (Object.keys(window.short_hash).length > 0) {
        $('#gallery-url').removeClass('hidden');
        $('#gallery-url-input').val(window.gallery_url+Object.keys(window.short_hash).join(','));
        $('#gallery-url-link').attr('href', window.gallery_url+Object.keys(window.short_hash).join(','));
    }
}
function rmFromShortHash(short) {
    delete window.short_hash[short];
    $('#gallery-url-input').val(window.gallery_url+Object.keys(window.short_hash).join(','));
    $('#gallery-url-link').attr('href', window.gallery_url+Object.keys(window.short_hash).join(','));
    if (Object.keys(window.short_hash).length === 0) {
        $('#gallery-url').addClass('hidden');
    }
}
function addToZipHash(short) {
    window.zip_hash[short] = 1;
    if (Object.keys(window.zip_hash).length > 0) {
        $('#zip-url').removeClass('hidden');
        $('#zip-url-input').val(window.zip_url+Object.keys(window.zip_hash).join('&i='));
        $('#zip-url-link').attr('href', window.zip_url+Object.keys(window.zip_hash).join('&i='));
    }
}
function rmFromZipHash(short) {
    delete window.zip_hash[short];
    $('#zip-url-input').val(window.zip_url+Object.keys(window.zip_hash).join('&i='));
    $('#zip-url-link').attr('href', window.zip_url+Object.keys(window.zip_hash).join('&i='));
    if (Object.keys(window.zip_hash).length === 0) {
        $('#zip-url').addClass('hidden');
    }
}
function addToRandomHash(short) {
    window.random_hash[short] = 1;
    if (Object.keys(window.random_hash).length > 0) {
        $('#random-url').removeClass('hidden');
        $('#random-url-input').val(window.random_url+Object.keys(window.random_hash).join('&i='));
        $('#random-url-link').attr('href', window.random_url+Object.keys(window.random_hash).join('&i='));
    }
}
function rmFromRandomHash(short) {
    delete window.random_hash[short];
    $('#random-url-input').val(window.random_url+Object.keys(window.random_hash).join('&i='));
    $('#random-url-link').attr('href', window.random_url+Object.keys(window.random_hash).join('&i='));
    if (Object.keys(window.random_hash).length === 0) {
        $('#random-url').addClass('hidden');
    }
}
/* Stolen from https://github.com/mozilla-services/push-dev-dashboard/blob/3ad4de737380d0842f40c82301d1f748c1b20f2b/push/static/js/validation.js */
function createNode(text) {
    var node = document.createElement('pre');
    node.classList.add('copy-node');
    node.textContent = text;
    return node;
}

function copyNode(node) {
    var selection = getSelection();
    selection.removeAllRanges();

    var range = document.createRange();
    range.selectNodeContents(node);
    selection.addRange(range);

    var success = document.execCommand('copy');
    selection.removeAllRanges();
    return success;
}

function copyText(text) {
    var node = createNode(text);
    document.body.appendChild(node);
    var success = copyNode(node);
    document.body.removeChild(node);
    return success;
}
function copyLink(e) {
    e.preventDefault();
    var successful = copyText($(this).prop('href'));
    var msg = successful ? 'successful' : 'unsuccessful';
    console.debug('Copying text command was ' + msg);
    if (!successful) {
        badToast('<%= l('Unable to copy to clipboard') %>');
        throw new Error('Copying text command was ' + msg);
    } else {
        goodToast('<%= l('Copied to clipboard') %>');
    }
}

function copyInput(node) {
    node.select();
    var success = document.execCommand('copy');
    getSelection().removeAllRanges();
    return success;
}
function copyToClipboard(el) {
    el = el.siblings('input');
    try {
        var successful = copyInput(el);
        var msg = successful ? 'successful' : 'unsuccessful';
        console.debug('Copying text command was ' + msg);
        if (!successful) {
            badToast('<%= l('Unable to copy to clipboard') %>');
            throw new Error('Copying text command was ' + msg);
        } else {
            goodToast('<%= l('Copied to clipboard') %>');
        }
    } catch (err) {
        prompt('<%= l('Hit Ctrl+C, then Enter to copy the short link') %>', el.val());
    }
}
function copyAllToClipboard(e) {
    e.preventDefault;
    var text = new Array();
    $('.view-link-input').each(function(index) {
        text.push($(this).val());
    });

    try {
        var successful = copyText(text.join("\n"));
        var msg = successful ? 'successful' : 'unsuccessful';
        console.debug('Copying text command was ' + msg);
        if (!successful) {
            throw new Error('Copying text command was ' + msg);
        }
    } catch (err) {
        prompt('<%= l('Hit Ctrl+C, then Enter to copy the short link') %>', text.join(" "));
    }

}
function clickOnCopyLink(e) {
    e.preventDefault();
    copyToClipboard($(this));
}
function delImage(e) {
    e.preventDefault();
    var short = $(this).attr('data-short');
    var token = $(this).attr('data-token');
    $.ajax({
        url: '<%= url_for('/') %>d/'+short+'/'+token,
        method: 'GET',
        data: {
            _format: 'json'
        },
        success: function(data) {
            if (data.success) {
                $('#alert-'+short).remove();
                evaluateCopyAll();
                delItem(short);
                goodToast('<%= l('Image deleted') %>');
            } else {
                badToast(data.msg);
            }
        },
        error: function() {
        },
        complete: function() {
        }
    });
}
function link(url, dl, token, modify, only_url) {
    if (token !== undefined) {
        if (modify !== undefined && modify === true) {
            return  '<%== url_for('/m/')->to_abs() %>'+url+'/'+token;
        }
        var link = '<%== url_for('/')->to_abs() %>d/'+url+'/'+token;
        if (only_url !== undefined && only_url === true) {
            return link;
        }
        return [
            '<label class="sr-only" for="link-del-', url, '"><%= l('Deletion link') %></label>',
            '<div class="input-group input-group-sm">',
                '<div class="input-group-btn adjust-addon">',
                    '<a class="btn btn-default text-danger" href="#" title="<%= l('Deletion link') %>" id="del-', url, '" data-short="', url, '" data-token="', token, '">',
                        '<span class="icon icon-trash"></span> ',
                    '</a>',
                '</div>',
                '<input type="text" class="form-control" id="link-del-', url, '" value="', link, '" readonly>',
                '<a href="#" class="input-group-addon copy-to-clipboard-link" title="<%= l('Copy to clipboard') %>">',
                    '<span class="icon icon-clipboard"></span>',
                '</a>',
            '</div>'
        ].join('');
    } else if (dl !== '') {
        url = url+'?'+dl;
    }
    return '<%== prefix() %>'+url;
}

function badToast(msg) {
    Toastify({
        text: msg,
        duration: 6000,
        newWindow: true,
        close: true,
        gravity: 'bottom',
        positionLeft: false,
        backgroundColor: '#f26163'
    }).showToast();
}

function goodToast(msg) {
    Toastify({
        text: msg,
        duration: 3000,
        newWindow: true,
        close: true,
        gravity: 'bottom',
        positionLeft: false
    }).showToast();
}
