/**
 * @extends SyqComponent
 */
function SyqComponent_uploadform()
{
    this.names = ['fileupload','swfupload'];

    this.showTab = function(name)
    {
        for (var i=0;i<this.names.length;i++)
        {
            var nameI = this.names[i];
            if (nameI!='error') this.components[nameI+'_tab'].setActive(name==nameI);
            if (name==nameI) this.q('#'+nameI+'_content').show();
            else             this.q('#'+nameI+'_content').hide();
        }
    };
    this.getTab = function()
    {
        for (var i=0;i<this.names.length;i++)
        {
            if (this.q('#'+this.names[i]+'_tab').isActive()) return this.names[i];
        }
        return '';
    };
    this.fileupload_tab_click = function() { this.showTab('fileupload'); return false; };
    this.swfupload_tab_click = function() { this.showTab('swfupload'); return false; };
    this.init = function() { this.showTab('fileupload'); };

    /***********************************************************/

    this.fileCount = 0;

    this.getFileHtml = function(fileID, fileName)
    {
        return '<table>'
            +'<tr>'
                +'<td class="uploadPreview">'
                    +'<div class="previewProgress" id="'+this.prefixID+'picPrg_'+fileID+'"><img src="/img/uploadWait.gif" /></div>'
                    +'<div class="previewFon"><img id="'+this.prefixID+'picImg_'+fileID+'" style="display:none" /></div>'
                +'</td>'
                +'<td class="uploadData">'
                    +'<div id="'+this.prefixID+'picError_'+fileID+'" class="uploadError">&nbsp;</div>'
                    +'<div>'
                        +'<label>Файл:</label><input type="text" id="'+this.prefixID+'picFile_'+fileID+'" class="picName" value="'+fileName+'" readonly="readonly" /><br />'
                        +'<label>Название:</label><input type="text" id="'+this.prefixID+'picName_'+fileID+'" maxlength="50" /><br />'
                        +'<label>Метки:</label><input type="text" id="'+this.prefixID+'picTags_'+fileID+'" /><br />'
                        +'<span class="bottomLabel">Укажите не менее трёх меток через запятую</span><br />'
                        +'<input type="hidden" id="'+this.prefixID+'picTempFileName_'+fileID+'" /><br />'
                    +'</div>'
                +'</td>'
            +'</tr>'
            +'</table>';
    };

    this.loadPreview = function(fileID, picFile)
    {
        var img = this.q('#picImg_'+fileID);
        var prg = this.q('#picPrg_'+fileID);
        img.load(function() {
            img.fadeIn();
            img.css('margin-top', Math.round((115-img.height())/2));
            prg.fadeOut();
        });
        img.attr('src','/uploads/pre-'+picFile);
    };

    this.fileUploaded = function(fileID, serverData)
    {
        var err = this.q('#picError_'+fileID);
        if (!serverData.startsWith('ERROR'))
        {
            this.loadPreview(fileID, serverData);
            this.q('#picTempFileName_'+fileID).val(serverData);
            this.fileCount++;
            err.remove();
        }
        else
        {
            if (serverData=='ERROR1') err.html('Неверный формат файла.');
            else
            if (serverData=='ERROR2') err.html('Неподдерживаемое соотношение сторон картинки.');
            else
            if (serverData.startsWith('ERROR3'))
            {
                var pic = eval("(" + serverData.substr(6) + ")");
                err.html('Похоже, что такая картинка уже есть: <a href="/pic/'+pic.id+'">'+pic.name+'</a>');
            }
            else
            if (serverData=='ERROR4') err.html('Размер картинки должен быть не менее 1280x1024.');
            err.fadeIn();
            this.q('#picPrg_'+fileID).fadeOut();
            return false;
        }
    };

    this.picSendedSuccess = function()
    {
        if (this.fileCount>0)
        {
            this.q('#sm').html('<span class="ok">'+(this.fileCount==1 ? 'Картинка успешно сохранена':'Картинки успешно сохранены')+'.</span>');
        }
        this.fileCount = 0;
        this.components['picFile'].reset();
        this.q('#loadedPics').html('');
        this.q('#loadedPics2').html('');

        this.components['picSave'].setActive(true);
        this.components['picSave2'].setActive(true);
    };


    this.picFile_select = function(fileName)
    {
        this.fileCount = 0;
        this.q('#sm').html('');
        this.q('#loadedPics').html(this.getFileHtml(0, fileName));
        this.q('#picName_0').focus();
        this.components['picSave'].setActive(false);
    };

    this.picFile_complete = function(serverData)
    {
        var r = this.fileUploaded(0, serverData);
        this.components['picSave'].setActive(true);
        return r;
    };

    this.picFile_filterNotMatch = function()
    {
        this.q('#sm').html('Можно загружать только файлы jpg, png или gif!');
    };

    this.picFile2_select = function(numFilesSelected, numFilesQueued)
    {
        this.fileCount = 0;
        this.q('#sm').html('');
        this.q('#loadedPics2').html('');

        if (numFilesQueued>10)
        {
            this.components['picFile2'].clearQueue();
            alert("Вы выбрали слишком много файлов. Вы можете загружать не более 10 картинок за раз.");
            return;
        }

        var swfu = this.components['picFile2'].swfu;
        swfu.stopUpload();
        var kol = 0; while ((file=swfu.getFile(kol))!=null) kol++;

        for (var i=0;i<numFilesQueued;i++)
        {
            var file = swfu.getFile(kol-numFilesQueued+i);
            $(this.getFileHtml(file.id, file.name)).appendTo(this.q('#loadedPics2'));
        }

        if (numFilesQueued>0) this.components['picSave2'].setActive(false);
    };

    this.picFile2_uploadProgress = function(file, bytesLoaded)
    {
        try
        {
            var prg = this.q('#picPrg_'+file.id);
            var percent = Math.round(bytesLoaded / file.size * 100);
            prg.html(percent+"%");
        }
        catch(ex)
        {
            this.components['picFile2'].swfu.debug(ex);
        }
    };

    this.picFile2_fileUploaded = function(file, serverData)
    {
        this.fileUploaded(file.id, serverData);
    };

    this.picFile2_complete = function()
    {
        this.components['picSave2'].setActive(true);
    };

    this.validateAndSave = function(isActive, groupSelectorName, isOneFile)
    {
        var g = this.components[groupSelectorName].getGroupID();
        if (!g || g==1) { this.components[groupSelectorName].focus(); return false; }

        var pn;

        if (isOneFile)
        {
            pn = this.q('#picName_0');
            if (pn.length>0)
            {
                pn.val(pn.val().trim());
                if (pn.val()=='') { pn.focus(); return false; }

                pn = this.q('#picTags_0');
                pn.val(pn.val().trim());
                if (pn.val()=='') { pn.focus(); return false; }
            }
        }
        else
        {
            var swfu = this.components['picFile2'].swfu;
            var kol = 0; while (swfu.getFile(kol)) kol++;
            for (var i=0;i<kol;i++)
            {
                var file = swfu.getFile(i);
                pn = this.q('#picName_'+file.id);
                if (pn.length && this.q('#picTempFileName_'+file.id).val())
                {
                    pn.val(pn.val().trim());
                    if (pn.val()=='') { pn.focus(); return false; }

                    pn = this.q('#picTags_'+file.id);
                    pn.val(pn.val().trim());
                    if (pn.val()=='') { pn.focus(); return false; }
                }
            }
        }

        return this.fileCount>0 ? isActive : false;
    };

    this.picSave_click = function(isActive)
    {
        var r = this.validateAndSave(isActive, 'gs', true);
        if (r) this.components['picSave'].setActive(false);
        return r;
    };

    this.picSave2_click = function(isActive)
    {
        var r = this.validateAndSave(isActive, 'gs2', false);
        if (r) this.components['picSave2'].setActive(false);
        return r;
    };
};
SyqComponent_uploadform.prototype = new SyqComponent;
