{% load i18n %}
$('.add-file').click(function(){
    $('#add-file-popup').modal({focus:false});    
    var file_tree_cont = $('#file-tree');
    $.ajax({
        url: repos_get_url,
        cache: false,
        dataType: 'json',
        success: function(data) {
            var file_tree = new FileTree();
            var repos = file_tree.format_repo_data(data);
            if (repos.length > 0) {
                file_tree.renderFileTree(file_tree_cont.data('site_root', '{{SITE_ROOT}}'), repos/*, {'two_state': true}*/);
            } else {
                file_tree_cont.html('<p class="error">' + "{% trans "You don't have any library at present" %}" + '</p>');
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            var error;
            if (jqXHR.responseText) {
                error = $.parseJSON(jqXHR.responseText).error;
            } else {
                error = "{% trans "Failed. Please check the network." %}";
            }
            file_tree_cont.html('<p class="error">' + error + '</p>');
        }
    });
});
$('#add-file-popup .submit').click(function() {
    var files_ct = $('#selected-files');
    var selected = files_ct.data('files') || [];
    $('[name="selected"][checked="checked"]', $('#file-tree')).each(function() {
        var val =  $(this).val();
        if (val.charAt(val.length - 1) != '/') { // only submit file
            selected.push($(this).val());
        }
    });
    $.modal.close();
    var files = '';
    for (var i = 0, len = selected.length; i < len; i++) {
        files += '<li class="item">' + '<img src="{{MEDIA_URL}}img/del.png" class="rm vam" data-index="' + i + '" /><span class="vam">' + selected[i].substr(selected[i].lastIndexOf('/') + 1) + '</span></li>';
    }
    files_ct.data('files', selected).html(files).removeClass('hide');
    $('.rm', files_ct).click(function() {
        var selected_f = files_ct.data('files');
        selected_f.splice($(this).data('index'), 1);
        $(this).parent().remove();
        files_ct.data('files', selected_f);
    });
});

