$(document).ready(function(){

    var 
        $body = $('body'),
        $foldersContentWrap = $('.b-preview'),
        $loading = $('.b-loading'),
        colorsActive = $foldersContentWrap.data('colors'),
        freeNumbers = [1,2,3,4,5],
        pairsCount = $foldersContentWrap.data('pairs_count'),
        currentNumToSelect = {},
        hasSelectedFoto = {};
    
    function StartLoading()
    {
        $loading.show();
    }
    
    function StopLoading()
    {
        $loading.hide();
    }
    
    function MarkFolderSelected($folderName)
    {
        $('.b-list_folders-item').removeClass('active');
        $folderName.addClass('active');
    }
    
    function MarkFolderViewed($folderName)
    {
        $folderName.addClass('viewed');
    }
    
    function RenderFilesList(folderName, data)
    {
        // Добавляем содержимое папки:
        
        var templateFolderContent = _.template('' +
            '<div class="b-folder-content row active" data-folder="<%= folder %>">' +
            '   <div class="sorted">' +
            '   </div>' +
            '   <div class="not-sorted col row">' +
            '   <% _.each(files, function(item, ind) { %>   \n' +
            '       <div class="b-foto col-<%= cols %> order-<%= ind+1 %>" data-id="<%= item %>" data-ind="<%= ind+1 %>">' +
            '           <div class="b-foto_inner" style="background-image: url(/fotos/<%= folder %>/<%= item %>)" data-foto="<%= item %>" data-num="">' +
            '              <div class="b-foto_number"></div>' +
            '           </div>' +
            '       </div>' +
            '   <% }) %>  \n' +
            '   </div>' +
            '</div>'
        );
        
        /*
        var templateFolderContent = _.template('' +
            '<div class="b-folder-content row active" data-folder="<%= folder %>">' +
            '   <% _.each(files, function(item) { %>   \n' +
            '       <div class="b-foto col-<%= cols %> order-12" data-id="<%= item %>">' +
            '           <div class="b-foto_inner" style="background-image: url(/fotos/<%= folder %>/<%= item %>)" data-foto="<%= item %>" data-num="">' +
            '              <div class="b-foto_number"></div>' +
            '           </div>' +
            '       </div>' +
            '   <% }) %>  \n' +
            '</div>'
        );
        */
        var cols;
        
        switch (data.length) {
            case 2:
            case 3:
                cols = 4;
                break;
            case 4:
                cols = 6;
                break;
            case 5:
            case 6:
                cols = 4;
                break;
            case 7:
            case 8:
                cols = 3;
                break;
            case 9:
            case 10:
                cols = 2;
                break;
            default:
              cols = 2;
        }

        $foldersContentWrap.append(templateFolderContent({folder: folderName, files: data, cols: cols}));
        currentNumToSelect[folderName] = 1;
        hasSelectedFoto[folderName] = false; // Выбрали одну картинку (есть подсвеченное фото)
    }
    
    function getCurrenNumToSelect($folderWrap)
    {
        for (let n = 1; n <= pairsCount; 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 SetDataGroupContents($currentFolderWrap)
    {
        var
            $sorted = $('.sorted', $currentFolderWrap),
            $notSorted = $('.not-sorted', $currentFolderWrap),
            $fotoSorted = $('.b-foto', $sorted),
            $fotoNotSorted = $('.b-foto', $notSorted),
            $fotoAll = $('.b-foto', $currentFolderWrap),
            sorted = $fotoSorted.length,
            notSorted = $('.b-foto', $fotoNotSorted).length,
            common = $fotoAll.length,
            sortedCol, notSortedCol, fotoSortedCol, fotoNotSortedCol;
            
            // [sorted-Col, notSorted-Col, fotoSorted-Col, fotoNotSorted-Col]
            var configColNumbers = {
                2: {0:[0,12,0,4], 2:[12,0,4,0]},
                3: {0:[0,12,0,4], 2:[8,4,6,12]},
                4: {0:[0,12,0,6], 2:[6,6,12,12], 4: [12,0,6,0]},
                5: {0:[0,12,0,4], 2:[4,8,12,6], 4: [8,4,6,12]},
                6: {0:[0,12,0,4], 2:[4,8,12,6], 4: [8,4,6,12], 6: [12,0,4,0]},
                7: {0:[0,12,0,3], 2:[3,9,12,4], 4: [6,6,6,6], 6: [9,3,4,12]},
                8: {0:[0,12,0,3], 2:[3,9,12,4], 4: [6,6,6,6], 6: [9,3,4,12], 8: [12,0,3,0]},
                9: {0:[0,12,0,2], 2:[3,9,12,3], 4: [5,7,6,4], 6: [6,6,4,5], 8: [9,3,3,12]},
                10: {0:[0,12,0,2], 2:[2,10,12,4], 4: [4,8,6,4], 6: [6,6,4,5], 8: [10,2,3,12]},
            }
            
    
            //console.log('AAA common = ', common, ' ', sorted, ' ', notSorted);
            if (sorted == 0) {
                $sorted.removeClass('row');
            } else {
                $sorted.addClass('row');
            }
            
            for (let i = 0; i <= 12; i++) {
                $sorted.removeClass('col-' + i);
                $notSorted.removeClass('col-' + i);
                $fotoAll.removeClass('col-' + i);
            }
            
            sortedCol = configColNumbers[common][sorted][0];
            notSortedCol = configColNumbers[common][sorted][1];
            fotoSortedCol = configColNumbers[common][sorted][2];
            fotoNotSortedCol = configColNumbers[common][sorted][3];

            $sorted.addClass('col-' + sortedCol);
            $notSorted.addClass('col-' + notSortedCol);
            $fotoSorted.addClass('col-' + fotoSortedCol);
            $fotoNotSorted.addClass('col-' + fotoNotSortedCol);
            
            
    }
    
    // Клик на папку для загрузки фотографий:
    $('.b-list_folders-item').on('click', function(){
        
        var
            $this = $(this),
            $foldersContent = $('.b-folder-content'),
            $form = $('#load-folder-form'),
            action = $form.attr('action'),
            method = $form.attr('method'),
            folderName = $(this).data('folder'),
            data = {
                folder: folderName
            };
            
        $foldersContent.hide().removeClass('active');
       
        if ($('.b-folder-content[data-folder="' + folderName + '"]').length>0) {
            console.log('AAA отображаем');
            $('.b-folder-content[data-folder="' + folderName + '"]').show().addClass('active');
            MarkFolderSelected($this);
        } else {
            console.log('AAA подгружаем');
            StartLoading();
            $.ajax(action, {
                type: method,
                data: data,
                success: function(data) {
                    //console.log('AAA success', data);
                    StopLoading();
                    RenderFilesList(folderName, data);
                    MarkFolderSelected($this);
                    MarkFolderViewed($this);
                },
                error: function(rew, status, err) {
                    console.log(status, err);                    
                }
            });
        }
       
        return false; 
    });
    
    // Клик на фото:
    $foldersContentWrap.on('click', '.b-foto_inner', function(){
        
        var
            $this = $(this),
            num,
            $currentFolderWrap = $this.parents('.b-folder-content'),
            folderName = $currentFolderWrap.data('folder'),
            $pairedFoto,
            fadeDuration = 100;
        
        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);
                $this.addClass('paired');
                $pairedFoto.addClass('paired');
                
                var
                    $fotoThis = $this.parent('.b-foto'),
                    $fotoPair = $pairedFoto.parent('.b-foto'),
                    foto1 = $pairedFoto.parent('.b-foto').remove(),
                    foto2 = $this.parent('.b-foto').remove();

                $fotoPair.removeClass('order-' + $fotoPair.data('ind') ).addClass('order-' + num);
                $fotoThis.removeClass('order-' + $fotoThis.data('ind') ).addClass('order-' + (num+5));
                foto1.appendTo($('.sorted',$currentFolderWrap));
                foto2.appendTo($('.sorted',$currentFolderWrap));
                SetDataGroupContents($currentFolderWrap);

                
                currentNumToSelect[folderName] = getCurrenNumToSelect($currentFolderWrap);
                hasSelectedFoto[folderName] = false;
                $currentFolderWrap.removeClass('has-selected');
                
            }
            
            $('.b-foto_number', $this).text(num);
            $this.attr('data-num', num);
            $this.css('border-color', colorsActive[num]);
            $this.addClass('selected');
            
            // Если осталось одно неразмеченное фото, то выбираем и его автоматически:
            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')) {
                $pairedFotos.each(function(){
                    var
                        $this = $(this).parent('.b-foto'),
                        foto = $this.remove();
                    $this.removeClass('order-' + pairedNum).removeClass('order-' + (pairedNum+5)).addClass('order-' + $this.data('ind') );
                    foto.appendTo($('.not-sorted',$currentFolderWrap));
                });
                SetDataGroupContents($currentFolderWrap);
            }
            
            $('.b-foto_number', $pairedFotos).text('');
            $pairedFotos.attr('data-num', '')
                        .removeClass('paired')
                        .removeClass('selected')
                        .css('border-color', '#8D9094');
            
            hasSelectedFoto[folderName] = false;
            $currentFolderWrap.removeClass('has-selected');
            currentNumToSelect[folderName] = getCurrenNumToSelect($currentFolderWrap);
        }
        
        SetCountPairedInFolderItemList(folderName);
    });        

    // Обработка нажатия клавиш:
    $body.keyup(function(e) {
        
        // Пробел
        if (e.keyCode == 32)
        {
            var
                $activeFolder = $('.b-folder-content.active', $foldersContentWrap),
                $fotos = $('.b-foto_inner', $activeFolder);
                
            if ($fotos.length == 2) {
                $fotos.first().click();
            }
        }
        
        // Вниз
        if (e.keyCode == 40)
        {
            var
                $activeFolderItemList = $('.b-list_folders-item.active'),
                $nextFolderItem = $activeFolderItemList.next();
            
            $nextFolderItem.click();
        }
        
        // Вверх
        if (e.keyCode == 38)
        {
            var
                $activeFolderItemList = $('.b-list_folders-item.active'),
                $previousFolderItem = $activeFolderItemList.prev();
            
            $previousFolderItem.click();
        }
    
    });

    // Клик на "Сохранить" для объявления:
    $('.btn.btn-primary.save-folders').on('click', function(){
        
        
        //if (!confirm('Применить действия над изображениями?')) return false;
        
        
        // Формируем данные о картинках-парах:
        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);
                    
                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;
            }
            
        });
        
        
        var
            $form = $('#save-folders-form'),
            action = $form.attr('action'),
            method = $form.attr('method');
       
        console.log('AAA data = ', data);
        
        $.ajax(action, {
            type: method,
            data: data,
            success: function(data) {
                console.log('AAA success', data);
                /*
                if(data) {
                    if(data.result === true && data.redirect) {
                        document.location.href = data.redirect;
                    }
                    if(data.result === false && data.msg) {
                        $.showMessage('error', data.msg);
                    }
                }
                */
            },
            error: function(rew, status, err) {
                console.log(status, err);                    
            }
        });
        
        return false;
        
    });        
    

    // Отображаем содержимое первой папки при загрузке страницы:
    $('.b-list_folders-item').first().click();

});