helpers = {
    formatSize: function(bytes){
         var i = -1;
         do {
             bytes = bytes / 1024;
             i++;
         } while (bytes > 99);
         return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];
     },
    formatFileName: function(name){
        if (name.length > 33){
            name = name.slice(0, 19) + '...' + name.slice(-13);    
        }
        return name;
    },
}

function bindNextEvents() {
    /* Здесь выполняется код привязки функций для блока next */
    $('[name=create_album]').change(function(){
        if ($(this).attr('checked')){
            $('tr.album-options div').slideDown('fast');
        }
        else {
            $('tr.album-options div').slideUp('fast');
        }
    });

    function check_public_uploads (cb) {
        var l = $(cb).parents('label');
        var c = $(cb).attr('checked');
        l.find('.comment').hide();
        if (c) l.find('.comment.yes').show();
        else l.find('.comment.no').show();
    }

    var pb = $('[name=public_uploads]');
    check_public_uploads(pb);
    pb.click(function(){
        check_public_uploads(this);
    });

}

function getQueue(){ return $('.qq-upload-list'); }

function getJSON(data){
    try { return JSON.parse(data); }
    catch (e) { return eval('(' + data + ')'); }
}

function onComplete(evt, ID, fileObj, response, data) {
    //console.log('completed', ID, fileObj, response, data);
    var q = getQueue(),
        resp = getJSON(response),
        elem = q.find('li#id-' + ID);
    elem.find('.qq-upload-cancel, .qq-upload-spinner').remove();
    if (resp.success){
        elem.append('<span class="qq-upload-success"></span>'); }
    else {
        elem.find('.qq-upload-failed-text').show();
    }
    onCompleteGeneral(ID, fileObj.name, resp);
}

function onSelect(evt, ID, fileObj) {
    // Файл добавлен в очередь загрузки
    addUploadList();
    var q = getQueue();
    var elem = $(fileTemplate);
    elem.attr('id', 'id-' + ID);
    elem.find('.qq-upload-file').html(helpers.formatFileName(fileObj.name));
    elem.find('.qq-upload-size').html(helpers.formatSize(fileObj.size));
    q.append(elem);
}

function onProgress () {
}

function allComplete(evt, data) {
}

function addUploadList(){
    if (!$('.qq-upload-list').length){
        $('#uploadify-uploader').append(uploadListTemplate).find('.qq-upload-cancel-text').remove();
    }
}

var fileTemplate = (
    '<li>' +
    '<span class="qq-upload-file"></span>' +
    '<span class="qq-upload-spinner"></span>' +
    '<span class="qq-upload-size"></span>' +
    '<a class="qq-upload-cancel" href="#">'+gettext("Cancel")+'</a>' +
    '<span class="qq-upload-failed-text">'+gettext("Failed")+'</span>' +
    '</li>')

var uploadListTemplate = (
    '<div class="list-abs"><div class="list-wrap">' +
    '<ul class="qq-upload-list"></ul>' + 
    '<div id="next"></div>' +
    '</div></div>' + 
    '</div>')


function showNextButton() {
    var next = $('.next-block');

    if (!next.is(':visible'))
        if (!$('.qq-upload-list .qq-upload-cancel').length)
            if ($('.qq-upload-list .qq-upload-success').length){
                next.remove();
                $('#next').append(next);
                next.show('fast');
                bindNextEvents();
            }
}

function onCompleteGeneral(id, fileName, responseJSON){
    /* numericID используется в qq-uploader */
    var url = responseJSON.url,
        code = responseJSON.code,
        error = responseJSON.error,
        id_regex = /(\d+)$/;
    var numericID = id_regex.exec(id);
    if (numericID) numericID = numericID[0];

    //console.log('general', id, fileName, responseJSON);

    if (code) {
        var f = $('form#uploaded_images');
        var a = f.attr('action').split('&');
        a.push(code);
        f.attr('action', a.join('&'));
    }
    if (url) {
        if (numericID) {
            var li = $($('.qq-upload-list .qq-upload-file')[numericID]); }
        else {
            var li = $('.qq-upload-list li#id-' + id + ' .qq-upload-file');
            //console.log(li);
        }
        li.html('<a href="'+url+'">'+li.html()+'</a>');

    }
    else if (error) {
        if (numericID) {
            var li = $($('.qq-upload-list .qq-upload-failed-text')[numericID]); }
        else {
            var li = $('.qq-upload-list li#id-' + id + ' .qq-upload-failed-text');
        }
        li.html(error);
    }
    showNextButton();
}

function getOperaVerion(){
    var re = /Opera.*Version\/(\d+.\d+)$/;
    try {
        return parseFloat(re.exec(window.navigator.userAgent)[1]); }
    catch (e) {
        return 0
    }
}

$(document).ready(function(){
    if (getOperaVerion() >= 11.5 ){
        $('#file-uploader').hide();
        $('#uploadify-uploader').show();
    }

    if ($('#uploadify').length){
        $('#uploadify').addClass('qq-upload-button').append(gettext("Upload a file"));
    }
    if (!$('#file-uploader').is(':visible')) return;

    var uploader = new qq.FileUploader({
        // pass the dom node (ex. $(selector)[0] for jQuery users)
        element: document.getElementById('file-uploader'),
        // path to server-side upload script
        action: '/ajax_upload',
        allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'tiff'],
        //sizeLimit: 5 * 1024 * 1024,
        debug: true,
        messages: {
            typeError: gettext("{file} has invalid extension. Only {extensions} are allowed."),
            sizeError: gettext("{file} is too large, maximum file size is {sizeLimit}."),
            minSizeError: gettext("{file} is too small, minimum file size is {minSizeLimit}."),
            emptyError: gettext("{file} is empty, please select files again without it."),
            onLeave: gettext("The files are being uploaded, if you leave now the upload will be cancelled.")
        },
        onComplete: onCompleteGeneral,
        template: '<div class="qq-uploader">' + 
            '<div class="qq-upload-drop-area"><span>'+gettext("Drop files here to upload")+'</span></div>' +
            '<div class="qq-upload-button" title="'+gettext("Try to drag'n'drop files to this box")+'">'+gettext("Upload a file")+'</div>' + uploadListTemplate,
        fileTemplate: fileTemplate,
    });
    $('.qq-upload-drop-area').click(function(){ $(this).hide('fast'); });
});

