$(document).ready(function(){

    var 
        $body = $('body'),
        $selectFoldersType = $('.b-list_select-folders'),
        $listFolders = $('.b-list_folders'),
        $listFoldersNew = $('.b-list_folders.new'),
        $listFoldersArch = $('.b-list_folders.arch'),
        $foldersContentWrap = $('.b-preview'),
        $foldersContentWrapInner = $('.b-preview_inner'),
        $foldersNewContentWrap = $('.b-preview_inner.new'),
        $foldersArchContentWrap = $('.b-preview_inner.arch'),
        $loading = $('.b-loading'),
        $saveButton = $('.btn.btn-primary.save-folders'),
        colorsActive = $foldersContentWrap.data('colors'),
        pairsCount = $foldersContentWrap.data('pairs_count'),
        storageName = 'im_fotos1',
        dataLS = null,
        folderTypeStorage = null,
        folderStorage = null,
        dataStorage = null,
        currentNumToSelect = {},    // Номер пары для очередного выбора
        hasSelectedFoto = {},       // Выбрали одну картинку (есть подсвеченное фото)
        archiveData = {};           // Данные о фото, находящихся в архиве
    
    function StartLoading()
    {
        $loading.show();
    }
    
    function StopLoading()
    {
        $loading.hide();
    }
    
    function getFoldersList(type)
    {
        if (type == 'new')  return $listFoldersNew;
        if (type == 'arch') return $listFoldersArch;
    }
    
    function MarkFolderSelected($folder, type)
    {
        var $foldersList = getFoldersList(type);
        $('.b-list_folders-item', $foldersList).removeClass('active');
        $folder.addClass('active');
    }
    
    function MarkNewFolderViewed($folderName, type)
    {
        if (type == 'new') {
            //console.log('AAA MarkNewFolderViewed');
            if (!$folderName.hasClass('viewed')) {
                $folderName.addClass('viewed');
                $saveButton.removeClass('disabled');
            }
        }
    }
    
    function MarkArchFolderViewed(folderName, $this)
    {
        if ($this.parents('.b-preview_inner').hasClass('arch')) {
            //console.log('AAA MarkArchFolderViewed');
            $('.b-list_folders-item[data-folder="' + folderName + '"]').addClass('viewed');
            $saveButton.removeClass('disabled');
        }
    }
    
    function RenderFilesList(folderName, folderType, data)
    {
        // Добавляем содержимое папки:
        var
            $target,
            folder,
            templateFolderContent,
            templateFolderContentCommon = _.template('' +
                '<div class="b-folder-content row align-items-center active" data-folder="<%= folderName %>">' +
                '   <div class="b-foto-double col">' +
                '   <% _.each(files, function(item, ind) { %>   \n' +
                '       <div class="b-foto" data-id="<%= item %>" data-ind="<%= ind+1 %>">' +
                '           <div class="b-foto_inner" data-foto="<%= item %>" data-num="">' +
                '               <img class="b-foto_img" src="<%= folder %>/<%= item %>" >' +
                '               <div class="b-foto_border"></div>' +
                '               <div class="b-foto_number"></div>' +
                '           </div>' +
                '       </div>' +
                '   <% if (((ind % 2) != 0) && (ind<files.length-1)) { %>' +
                '   </div>' +
                '   <div class="b-foto-double col">' +
                '   <% } %>' +
                '   <% }) %>  \n' +
                '   <% if ((files.length % 2) != 0) { %>' +
                '   <div class="b-foto fict"><div class="b-foto_inner-fict"></div></div>' +
                '   <% } %>' +
                '   </div>' +
                '</div>'
            ),
            templateFolderContent23 = _.template('' +
                '<div class="b-folder-content row align-items-center active" data-folder="<%= folderName %>">' +
                '   <% _.each(files, function(item, ind) { %>   \n' +
                '   <div class="b-foto-double col">' +
                '       <div class="b-foto" data-id="<%= item %>" data-ind="<%= ind+1 %>">' +
                '           <div class="b-foto_inner single-row" data-foto="<%= item %>" data-num="">' +
                '               <img class="b-foto_img" src="<%= folder %>/<%= item %>" >' +
                '               <div class="b-foto_border"></div>' +
                '               <div class="b-foto_number"></div>' +
                '           </div>' +
                '       </div>' +
                '   </div>' +
                '   <% }) %>  \n' +
                '</div>'
            );
            
        
        if (folderType == 'new') {
            folder = '/fotos/' + folderName;
            $target = $foldersNewContentWrap;
        }
        if (folderType == 'arch') {
            folder = '/fotos-arch/' + folderName;
            $target = $foldersArchContentWrap;
        }
        
        if (data.length > 3) {
            templateFolderContent = templateFolderContentCommon;
        } else {
            templateFolderContent = templateFolderContent23;
        }
        

        $target.append(templateFolderContent({folderName: folderName, folder: folder, files: data}));
        currentNumToSelect[folderName] = 1;
        hasSelectedFoto[folderName] = false;
    }
    
    function SetPairedFotos(folderName, folderType)
    {
        //console.log('AAA SetPairedFotos ', folderName, folderType);

        var sourceData = null;

        if (folderType == 'new') {
            
            if (dataStorage && dataStorage[folderName]) sourceData = dataStorage[folderName];
            
            if (sourceData) {
                var pairs = Object.keys(dataStorage[folderName]);
                if (pairs.length > 0)
                {
                    var $folderContentWrap = $('.b-folder-content[data-folder="' + folderName + '"]', $foldersNewContentWrap);
                    pairs.forEach(function(pair){
                        $('.b-foto_inner[data-foto="' + sourceData[pair][0] + '"] ', $folderContentWrap).trigger( "click", {data: 'emul'});
                        $('.b-foto_inner[data-foto="' + sourceData[pair][1] + '"] ', $folderContentWrap).trigger( "click", {data: 'emul'});
                    });
                }
            }
        }
        
        
        if (folderType == 'arch') {
            
            if (archiveData && archiveData[folderName]) sourceData = archiveData[folderName];
            if (dataStorage && dataStorage[folderName]) sourceData = dataStorage[folderName];
            
            if (sourceData) {
                var pairs = Object.keys(sourceData);
                if (pairs.length > 0)
                {
                    var $folderContentWrap = $('.b-folder-content[data-folder="' + folderName + '"]', $foldersArchContentWrap);
                    pairs.forEach(function(pair){
                        $('.b-foto_inner[data-foto="' + sourceData[pair][0] + '"] ', $folderContentWrap).trigger( "click", {data: 'emul'});
                        $('.b-foto_inner[data-foto="' + sourceData[pair][1] + '"] ', $folderContentWrap).trigger( "click", {data: 'emul'});
                    });
                }
            }
        }
    }
    
    function RenderFoldersList(type, data)
    {
        var
            $target,
            templateFoldersList = _.template('' +
                '<% _.each(folders, function(item) { %>   \n' +
                '   <li class="b-list_folders-item" data-folder="<%= item %>"><%= item %><b></b></li>' +
                '<% }) %>  \n'
            );
            
        if (type == 'new')  $target = $listFoldersNew;
        if (type == 'arch') $target = $listFoldersArch;
        $target.append(templateFoldersList({folders: data}));
    }
    
    function getCurrenNumToSelect($folderWrap)
    {
        for (let n = 1; n <= pairsCount+1; n++) {
            if ($('.b-foto_inner[data-num="' + n + '"]', $folderWrap).length == 0) return n;
        }
    }
    
    function SetCountPairedInFolderItemList(folderName)
    {
        var
            pairsCount = currentNumToSelect[folderName]-1,
            $folderListItem = $('.b-list_folders-item[data-folder="' + folderName + '"]');
        
        $folderListItem.attr('data-pairsCount', pairsCount);
        $('b', $folderListItem).text((pairsCount == 0) ? '' : pairsCount);
    }
    
    function CreatePair($currentFolderWrap, $pairedFoto, $this)
    {
        //console.log('AAA CreatePair ', $currentFolderWrap);
        $pairedFoto.addClass('paired');
        $this.addClass('paired');
        
        var countFotosInFolder = $('.b-foto', $currentFolderWrap).length;
        
        if (countFotosInFolder == 2) {
            return false;
        }
        
        if (countFotosInFolder == 3) {
            
            var
                $divDoublePair1 = $('<div class="b-foto-double col pair">'),
                $divDoublePair2 = $('<div class="b-foto-double col pair">'),
                $fotoPair = $pairedFoto.parent('.b-foto'),
                $fotoThis = $this.parent('.b-foto'),
                foto1 = $fotoPair.remove(),
                foto2 = $fotoThis.remove();

            foto1.appendTo($divDoublePair1);
            foto2.appendTo($divDoublePair2);

            $divDoublePair2.prependTo($currentFolderWrap);
            $divDoublePair1.prependTo($currentFolderWrap);
            
            RegroupRemainingFotos($currentFolderWrap);
            return false;
        }
         
        
        var
            $divDoublePair = $('<div class="b-foto-double col pair">'),
            $doublePaired = $('.b-foto-double.pair', $currentFolderWrap),
            $fotoPair = $pairedFoto.parent('.b-foto'),
            $fotoThis = $this.parent('.b-foto'),
            foto1 = $fotoPair.remove(),
            foto2 = $fotoThis.remove();
    
        foto1.appendTo($divDoublePair);
        foto2.appendTo($divDoublePair);
        
        if ($doublePaired.length > 0) {
            $divDoublePair.insertAfter($doublePaired.last());
        } else {
            $divDoublePair.prependTo($currentFolderWrap);
        }
        
        RegroupRemainingFotos($currentFolderWrap);
    }
    
    function DestroyPair($currentFolderWrap, $pairedFotos)
    {
        $pairedFotos.parents('.b-foto-double').removeClass('pair');
        
        var countFotosInFolder = $('.b-foto', $currentFolderWrap).length;
        
        if (countFotosInFolder == 2) {
            return false;
        }

        if (countFotosInFolder == 3) {
            SetLastPairClasses($currentFolderWrap);
            return false;
        }
        
        RegroupRemainingFotos($currentFolderWrap);
    }
    
    function RegroupRemainingFotos($currentFolderWrap)
    {
        // Перегруппируем оставшиеся фото:
        var
            $remainingFotos = $('.b-foto-double:not(.pair) .b-foto', $currentFolderWrap);
        
        
        $remainingFotos.remove();
        $('.b-foto-double:not(.pair)', $currentFolderWrap).remove();
        
        if ($remainingFotos.length>0) {
            var
                $divDoublePair = $('<div class="b-foto-double col">');
                
            $remainingFotos.each(function(ind){
                $(this).appendTo($divDoublePair);
                if (((ind % 2) != 0) && (ind<$remainingFotos.length-1)) {
                    $divDoublePair.appendTo($currentFolderWrap);
                    $divDoublePair = $('<div class="b-foto-double col">');
                }
            });
            $divDoublePair.appendTo($currentFolderWrap);
        }
        
        SetLastPairClasses($currentFolderWrap);
    }
    
    function SetLastPairClasses($currentFolderWrap)
    {
        var
            $pairs = $('.b-foto-double.pair', $currentFolderWrap),
            $doubles = $('.b-foto-double', $currentFolderWrap);
        if ($pairs.length>0) {
            $pairs.removeClass('last-pair');
            $pairs.last().addClass('last-pair');
            //$doubles.last().addClass('last-pair');    // 1й способ
            $doubles.first().addClass('first-pair');    // 2й способ
        } else {
            //$doubles.last().removeClass('last-pair'); // 1й способ
            $doubles.first().removeClass('first-pair'); // 2й способ
        }
    }
    
    function ShowFoldersNew()
    {
        //console.log('AAA ShowFoldersNew');
        $listFolders.removeClass('active');
        $foldersContentWrapInner.removeClass('active');
        
        $listFoldersNew.addClass('active');
        $foldersNewContentWrap.addClass('active');
    }
    
    function ShowFoldersArch()
    {
        //console.log('AAA ShowFoldersArch');
        $listFolders.removeClass('active');
        $foldersContentWrapInner.removeClass('active');
        
        $listFoldersArch.addClass('active');
        $foldersArchContentWrap.addClass('active');
    }
    
    function SaveLsState()
    {
        var
            data = {
                data: GetFoldersDataState(),
                folder: $('.b-list_folders.active .b-list_folders-item.active').data('folder'),
                type: $('.b-list_folders.active').data('type'),
            };
    
        //console.log('AAA SaveLsState ', data);
        localStorage.setItem(storageName, JSON.stringify(data));
    }
    
    function SetStateFromLs()
    {
        //console.log('AAA SetStateFromLs');
        
        dataLS = JSON.parse(localStorage.getItem(storageName));
        folderTypeStorage = dataLS.type;
        folderStorage = dataLS.folder;
        dataStorage = dataLS.data;

        if (folderTypeStorage == 'new')     ShowFoldersNew();
        if (folderTypeStorage == 'arch')    ShowFoldersArch();
        
        $selectFoldersType.val(folderTypeStorage);

        Object.keys(dataStorage).forEach(function(item){
            $('.b-list_folders-item[data-folder="' + item + '"]', $listFolders).addClass('viewed');
            if (dataStorage[item]) {
                $('.b-list_folders-item[data-folder="' + item + '"] b', $listFolders).text(Object.keys(dataStorage[item]).length);
            }
        });
        
        if (folderTypeStorage == 'new')     ShowFoldersNew();
        if (folderTypeStorage == 'arch')    ShowFoldersArch();
        
        var $curFolder = $('.b-list_folders-item[data-folder="' + folderStorage + '"]');
        $curFolder.parents('.b-list_folders').animate({
            scrollTop: $curFolder.offset().top-88
        }, 100);
        $curFolder.trigger( "click", {data: 'emul'});

        $saveButton.removeClass('disabled');
    }
    
    function GetFoldersDataState()
    {
        // Формируем данные о картинках-парах:
        var data = {};
        
        $('.b-list_folders-item').each(function(){
            var $this = $(this);
            
            if ($this.hasClass('viewed')) {
                var
                    dataPaired = {},
                    folderName = $this.data('folder'),
                    folderContent = $('.b-folder-content[data-folder="' + folderName +  '"]'),
                    $pairedFoto = $('.b-foto_inner.paired', folderContent);
                
                data[folderName] = null;
                
                if (folderContent.length == 0) {
                    //console.log('AAA Берём данные из LS, если они там имеются ');
                    if (dataStorage[folderName]) data[folderName] = dataStorage[folderName];
                } else {
                    if ($pairedFoto.length>0) {
                        $pairedFoto.each(function(){
                            var
                                $this = $(this),
                                pairNum = $this.data('num');

                            if (!dataPaired[pairNum]) {
                                dataPaired[pairNum] = [];
                            }
                            dataPaired[pairNum].push($this.data('foto'));
                        });
                        data[folderName] = dataPaired;
                    }
                }
                
                
                
            }
        });
        return data;
    }
    
    function GetArchiveData(callback)
    {
        //console.log('AAA получаем архивные данные');
            
        var
            $form = $('#load-folders-list-form'),
            action = $form.attr('action'),
            method = $form.attr('method');

        StartLoading();
        $.ajax(action, {
            type: method,
            success: function(data) {
                console.log('AAA success', data);
                StopLoading();
                archiveData = data['archive'];

                // Выставляем кол-во пар в архивных сетах
                if (archiveData) {
                    Object.keys(archiveData).forEach(function(item){
                        if (archiveData[item]) {
                            $('.b-list_folders-item[data-folder="' + item + '"] b', $listFoldersArch).text(Object.keys(archiveData[item]).length);
                        }
                    });
                }
                
                if (callback && $.isFunction(callback)) {
                    callback();
                }
            },
            error: function(rew, status, err) {
                console.log(status, err);                    
            }
        });
        
    }
    
    // Обработка нажатия клавиш:
    $body.keyup(function(e) {
        
        // Пробел
        if (e.keyCode == 32)
        {
            var
                $activeFolder = $('.b-preview_inner.active .b-folder-content.active', $foldersContentWrap),
                $fotoFolder = $('.b-foto', $activeFolder),
                $fotoFocused = $('.b-foto.focus', $activeFolder);
            
            // Пробел на подсвеченном сете, в котором 2 картинки:
            if ($fotoFolder.length == 2) {
                $('.b-foto_inner', $fotoFolder.first()).click();
                return false;
            }
            
            // Пробел на подсвеченном фото:
            if ($fotoFocused.length>0) {
                $('.b-foto_inner', $fotoFocused).click();
            }
        }
        
        // Вниз
        if (e.keyCode == 40)
        {
            var
                $activeFolderList = $('.b-list_folders.active'),
                $activeFolderItemList = $('.b-list_folders-item.active', $activeFolderList),
                $nextFolderItem;
            
            if ($activeFolderItemList.length>0) {
                $nextFolderItem = $activeFolderItemList.next();
            } else {
                $nextFolderItem = $('.b-list_folders-item', $activeFolderList).first();
            }
            
            $nextFolderItem.click();
        }
        
        // Вверх
        if (e.keyCode == 38)
        {
            var
                $activeFolderList = $('.b-list_folders.active'),
                $activeFolderItemList = $('.b-list_folders-item.active', $activeFolderList),
                $previousFolderItem;
            
            if ($activeFolderItemList.length>0) {
                $previousFolderItem = $activeFolderItemList.prev();
            } else {
                $previousFolderItem = $('.b-list_folders-item', $activeFolderList).first();
            }
            
            $previousFolderItem.click();
        }
        
        // Влево
        if (e.keyCode == 37)
        {
            var
                $activePreviewInner = $('.b-preview_inner.active'),
                $folderContent = $('.b-folder-content.active', $activePreviewInner),
                $fotoFocused = $('.b-foto.focus', $folderContent),
                $prevFoto,
                unFocusAll = false;
                
            if ($fotoFocused.length>0) {
                var
                    $double = $fotoFocused.parents('.b-foto-double'),
                    $prevDouble;
                    
                    if ($folderContent.hasClass('has-selected')) {
                        $prevDouble = $double.prev('.b-foto-double:not(.pair)');
                    } else {
                        $prevDouble = $double.prev('.b-foto-double');
                    }
                    
                
                if ($fotoFocused.index($('.b-foto', $double)) == 0) {
                    if ($prevDouble.length>0) {
                        $prevFoto = $('.b-foto', $prevDouble).first();
                    } else {
                        unFocusAll = true;
                    }
                } else {
                    if ($prevDouble.length>0) {
                        $prevFoto = $('.b-foto', $prevDouble).last();
                        if ($prevFoto.hasClass('fict')) $prevFoto = $fotoFocused;
                    } else {
                        //console.log('AAA Переход на 1-ю строку');
                        $prevDouble = $('.b-foto-double', $folderContent).last();
                        $prevFoto = $('.b-foto', $prevDouble).first();
                    }
                }
            } else {
                return false;
            }
            
            $('.b-foto', $folderContent).removeClass('focus');
            if (!unFocusAll) {
                $prevFoto.addClass('focus');
            }
        }
        
        // Вправо
        if (e.keyCode == 39)
        {
            var
                $activePreviewInner = $('.b-preview_inner.active'),
                $folderContent = $('.b-folder-content.active', $activePreviewInner),
                $fotoFocused = $('.b-foto.focus', $folderContent),
                $nextFoto;
                
            if ($fotoFocused.length>0) {
                var
                    $double = $fotoFocused.parents('.b-foto-double'),
                    $nextDouble = $double.next('.b-foto-double');
                
                if ($fotoFocused.index($('.b-foto', $double)) == 0) {
                    if ($nextDouble.length>0) {
                        $nextFoto = $('.b-foto', $nextDouble).first();
                    } else {
                        //console.log('AAA Переход на 2-ю строку');
                        if ($folderContent.hasClass('has-selected')) {
                            $nextDouble = $('.b-foto-double:not(.pair)', $folderContent).first();
                        } else {
                            $nextDouble = $('.b-foto-double', $folderContent).first();
                        }
                        $nextFoto = $('.b-foto', $nextDouble).last();
                    }
                } else {
                    if ($nextDouble.length>0) {
                        $nextFoto = $('.b-foto', $nextDouble).last();
                        if ($nextFoto.hasClass('fict')) $nextFoto = $fotoFocused;
                    } else {
                        $nextFoto = $fotoFocused;
                    }
                }
                
            } else {
                
                if ($folderContent.hasClass('has-selected')) {
                    $nextFoto = $('.b-foto-double:not(.pair) .b-foto', $folderContent).first();
                } else {
                    $nextFoto = $('.b-foto', $folderContent).first();
                }
                
                
            }
            
            $('.b-foto', $folderContent).removeClass('focus');
            $nextFoto.addClass('focus');
        }
        
    
    });
    
    // Клик на фото:
    $foldersContentWrap.on('click', '.b-foto_inner', function(event, param){
        
        var isEmul = false;
        if (param && (param['data'] == 'emul')) {
            isEmul = true;
        }
        
        var
            $this = $(this),
            num,
            isStateToSave = false,
            $currentFolderWrap = $this.parents('.b-folder-content'),
            folderName = $currentFolderWrap.data('folder'),
            $pairedFoto;
        
        //console.log('AAA folderName ', folderName);
        
        if (!$this.hasClass('selected'))
        {
            // Клик по фото без рамки
            
            if (!hasSelectedFoto[folderName]) {
                //console.log('AAA выбор 1-е фото для пары');
                num = currentNumToSelect[folderName];
                hasSelectedFoto[folderName] = true;
                $currentFolderWrap.addClass('has-selected');
            } else {
                //console.log('AAA выбор 2-е фото для пары (пара сформирована)');
                num = currentNumToSelect[folderName];
                $pairedFoto = $('.b-foto_inner[data-num="' + num + '"]', $currentFolderWrap);
                
                CreatePair($currentFolderWrap, $pairedFoto, $this);
                
                if (!isEmul) {
                    MarkArchFolderViewed(folderName, $this);
                }
                
                currentNumToSelect[folderName] = getCurrenNumToSelect($currentFolderWrap);
                hasSelectedFoto[folderName] = false;
                $currentFolderWrap.removeClass('has-selected');
                
                isStateToSave = true;
            }
            
            $('.b-foto_number', $this).text(num);
            $('.b-foto_border', $this).css('border-color', colorsActive[num]);
            $this.attr('data-num', num);
            $this.addClass('selected');
            
            // Если осталось одно неразмеченное фото, то выбираем и его автоматически:
            if (!isEmul) {
                if (hasSelectedFoto[folderName]) {
                    var notSelectedFotos = $('.b-foto_inner:not(.selected)', $currentFolderWrap);
                    if (notSelectedFotos.length == 1) {
                        notSelectedFotos.click();
                    }
                }
            }
            
        }
        else
        {
            //console.log('AAA Клик по фото с рамкой');
            
            var
                pairedNum = parseInt($this.attr('data-num')),
                $pairedFotos = $('.b-foto_inner[data-num="' + pairedNum + '"]', $currentFolderWrap),
                isFromPair = $this.hasClass('paired');
            
            if (hasSelectedFoto[folderName] && isFromPair) {
                return false;
            }
            
            if ($this.hasClass('paired')) {
                //console.log('AAA расформировываем пару');
                DestroyPair($currentFolderWrap, $pairedFotos);
                MarkArchFolderViewed(folderName, $this);
                isStateToSave = true;
            }
            
            $('.b-foto_number', $pairedFotos).text('');
            $('.b-foto_border', $pairedFotos).css('border-color', '#8D9094');
            $pairedFotos.attr('data-num', '')
                        .removeClass('paired')
                        .removeClass('selected');
            
            hasSelectedFoto[folderName] = false;
            $currentFolderWrap.removeClass('has-selected');
            currentNumToSelect[folderName] = getCurrenNumToSelect($currentFolderWrap);
        }
        
        SetCountPairedInFolderItemList(folderName);
        
        if (isStateToSave && !isEmul) {
            SaveLsState();
        }
        
    });        
    
    // Клик на папку для загрузки фотографий:
    $listFolders.on('click', '.b-list_folders-item', function(event, param){
        
        var isEmul = false;
        if (param && (param['data'] == 'emul')) {
            isEmul = true;
        }
        
        var
            $this = $(this),
            $form = $('#load-folder-form'),
            action = $form.attr('action'),
            method = $form.attr('method'),
            folderName = $this.data('folder'),
            folderType = $this.parent('.b-list_folders').data('type'),
            $foldersContent = $('.b-preview_inner.' + folderType + ' .b-folder-content'),
            data = {
                folder: folderName,
                type: folderType
            };
        
        
        $foldersContent.hide().removeClass('active');
       
        if ($('.b-folder-content[data-folder="' + folderName + '"]').length>0) {
            //console.log('AAA отображаем ', folderName);
            $('.b-folder-content[data-folder="' + folderName + '"]').show().addClass('active');
            MarkFolderSelected($this, folderType);
            //if (folderType == 'new') {
                SaveLsState();
            //}
            
        } else {
            //console.log('AAA подгружаем ', folderName);
            StartLoading();
            $.ajax(action, {
                type: method,
                data: data,
                success: function(data) {
                    //console.log('AAA success', data);
                    StopLoading();
                    RenderFilesList(folderName, folderType, data);
                    SetPairedFotos(folderName, folderType);
                    MarkFolderSelected($this, folderType);
                    MarkNewFolderViewed($this, folderType);
                    //if (!isEmul && folderType == 'new') {
                    if (!isEmul) {
                        SaveLsState();
                    }
                },
                error: function(rew, status, err) {
                    console.log(status, err);
                    $foldersContent.show().addClass('active');
                }
            });
        }
       
        return false; 
    });
    
    // Изменение типа отображаемых папок:
    $selectFoldersType.on('change', function(){
        console.log('AAA Изменение типа отображаемых папок:');
        
        var type = $(this).val();
        
        if (type == 'new')  ShowFoldersNew();
        if (type == 'arch') ShowFoldersArch();
        
        SaveLsState();
        
        $selectFoldersType.blur(); // убираем фокус
        
        // Загрузка списка папок:
        /*
        if ($('li', $('.b-list_folders.' + type)).length == 0) {
            //console.log('AAA загружаем список папок');
            
            var
                $form = $('#load-folders-list-form'),
                action = $form.attr('action'),
                method = $form.attr('method'),
                data = {
                    type: type
                };
            
            StartLoading();
            $.ajax(action, {
                type: method,
                data: data,
                success: function(data) {
                    console.log('AAA success', data);
                    StopLoading();
                    archiveData = data['archive'];
                    RenderFoldersList(type, data['folders']);
                    SetStateFromLs(type);
                },
                error: function(rew, status, err) {
                    console.log(status, err);                    
                }
            });
        }
        */
        
    });
    
    // Клик на "Сохранить":
    $saveButton.on('click', function(){
        
        if (!confirm('Применить действия над изображениями?')) return false;
        
        var data = GetFoldersDataState();
        
        var
            $form = $('#save-folders-form'),
            action = $form.attr('action'),
            method = $form.attr('method');
       
        console.log('AAA data = ', data);
        //return false;
        
        $.ajax(action, {
            type: method,
            data: data,
            success: function(data) {
                if(data) {
                    console.log('AAA success', data);
                    if(data.result === true) {
                        //document.location.href = data.redirect;
                        localStorage.removeItem(storageName);
                        document.location.reload();
                    }
                    if(data.result === false && data.msg) {
                        //$.showMessage('error', data.msg);
                    }
                    
                }
            },
            error: function(rew, status, err) {
                console.log(status, err);                    
            }
        });
        
        return false;
    });        
    
    
    GetArchiveData(function(){
        // Отображаем содержимое первой папки new при загрузке страницы:
        if (localStorage.getItem(storageName)) {
            SetStateFromLs();
        } else {
            ShowFoldersNew();
            $('.b-list_folders-item', $listFoldersNew).first().trigger( "click", {data: 'emul'});
        }
    });

});