% # vim:set sts=4 sw=4 ts=4 ft=javascript expandtab:
function findItem(name) {
    var files = localStorage.getItem('files');
    if (files === null) {
        files = new Array();
    } else {
        files = JSON.parse(files);
    }
    var i;
    for (i = 0; i < files.length; i++) {
        if (files[i].short === name) {
            return files[i];
        }
    }
}
function updateMailtoLink() {
    var btn     = document.getElementById('mailto');
    var emails  = document.getElementById('emails');
    var subject = document.getElementById('subject');
    var text    = document.getElementById('body');

    btn.href = 'mailto:'+encodeURIComponent(emails.value)+'?subject='+encodeURIComponent(subject.value)+'&body='+encodeURIComponent(text.value);
}
function populateBody() {
    var links = [
    % my $ref = ref(stash('links'));
    % if ($ref eq 'ARRAY') {
    %   for my $link (@{stash('links')}) {
        '<%= $link %>',
    %   }
    % } else {
        '<%= stash('links') %>',
    % }
    ];
    var text = "<%== l('Hello,\n\nHere\'s some files I want to share with you:\n') %>";
    links.forEach(function(name, index, array) {
        var item = findItem(name);
        if (item !== null && item !== undefined) {
            var limit = (item.delay === 0) ? null : moment.unix(item.delay * 86400 + item.created_at).locale(window.navigator.language).format('LLLL');
            text = text+'- '+item.name+'<%= l(':') %> '+item.url;
            if (limit !== null) {
                text = text+"\n  (<%= l('deadline: ') %>"+limit+')';
            }
            text = text+"\n";
        }
    });

    text  = text+"\n--\n<%= l('Share your files in total privacy on %1', url_for('/')->to_abs) %>";
    tArea = document.getElementById('body').value = text;
    updateMailtoLink();
}
document.addEventListener('DOMContentLoaded', function() {
% if (stash('populate')) {
    populateBody();
% }

    var emails  = document.getElementById('emails');
    var subject = document.getElementById('subject');
    var text    = document.getElementById('body');
    emails.addEventListener('change', updateMailtoLink);
    subject.addEventListener('change', updateMailtoLink);
    text.addEventListener('change', updateMailtoLink);
});
