$(document).ready(function(){

    var 
        $body = $('body'),
        $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'),
        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 MarkFolderViewed($folderName, type)
    {
        if (type == 'new') {
            $folderName.addClass('viewed');
            $saveButton.removeClass('disabled');
        }
    }
    
    function MarkArchFolderViewed(folderName, $this)
    {
        if ($this.parents('.b-preview_inner').hasClass('arch')) {
            console.log('AAA MarkArchFolderViewed ', folderName);
            $('.b-list_folders-item[data-folder="' + folderName + '"]').addClass('viewed');
            $saveButton.removeClass('disabled');
        }
    }
    
    function RenderFilesList(folderName, folderType, data)
    {
        // Добавляем содержимое папки:
        var
            $target,
            folder,
            cols,        
            templateFolderContent = _.template('' +
                '<div class="b-folder-content row active" data-folder="<%= folderName %>">' +
                '   <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(<%= folder %>/<%= item %>)" data-foto="<%= item %>" data-num="">' +
                '              <div class="b-foto_number"></div>' +
                '           </div>' +
                '       </div>' +
                '   <% }) %>  \n' +
                '   </div>' +
                '</div>'
            );
        
        if (folderType == 'new') {
            folder = '/fotos/' + folderName;
            $target = $foldersNewContentWrap;
        }
        if (folderType == 'arch') {
            folder = '/fotos-arch/' + folderName;
            $target = $foldersArchContentWrap;
        }
        
        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;
        }

        $target.append(templateFolderContent({folderName: folderName, folder: folder, files: data, cols: cols}));
        currentNumToSelect[folderName] = 1;
        hasSelectedFoto[folderName] = false; // Выбрали одну картинку (есть подсвеченное фото)
    }
    
    function SetPairedFotos(folderName, folderType)
    {
        if (folderType == 'arch') {
            if (archiveData[folderName]) {
                var pairs = Object.keys(archiveData[folderName]);
                if (pairs > 0)
                {
                    var $folderContentWrap = $('.b-folder-content[data-folder="' + folderName + '"]', $foldersArchContentWrap);
                    
                    pairs.forEach(function(pair){
                        $('.b-foto_inner[data-foto="' + archiveData[folderName][pair][0] + '"] ', $folderContentWrap).click();
                        $('.b-foto_inner[data-foto="' + archiveData[folderName][pair][1] + '"] ', $folderContentWrap).click();
                    });
                    
                    $('.b-list_folders-item[data-folder="' + folderName + '"]').removeClass('viewed');
                    $saveButton.addClass('disabled');
                }
            }
        }
    }
    
    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; 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,3], 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);
            
            
    }
    
    function ShowFoldersNew()
    {
        $listFoldersNew.show();
        $foldersNewContentWrap.show();
    }
    
    function ShowFoldersArch()
    {
        $listFoldersArch.show();
        $foldersArchContentWrap.show();
    }
    
    // Обработка нажатия клавиш:
    $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();
        }
    
    });
    
    // Клик на фото:
    $foldersContentWrap.on('click', '.b-foto_inner', function(){
        
        var
            $this = $(this),
            num,
            $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);
                $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);
                MarkArchFolderViewed(folderName, $this);
                
                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);
                MarkArchFolderViewed(folderName, $this);
            }
            
            $('.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);
    });        
    
    // Клик на папку для загрузки фотографий:
    $listFolders.on('click', '.b-list_folders-item', function(){
        
        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 отображаем');
            $('.b-folder-content[data-folder="' + folderName + '"]').show().addClass('active');
            MarkFolderSelected($this, folderType);
        } else {
            //console.log('AAA подгружаем');
            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);
                    MarkFolderViewed($this, folderType);
                },
                error: function(rew, status, err) {
                    console.log(status, err);
                    $foldersContent.show().addClass('active');
                }
            });
        }
       
        return false; 
    });
    
    // Изменение типа отображаемой папки:
    $('.b-list_select-folders').on('change', function(){
        var type = $(this).val();
        
        $listFolders.hide();
        $foldersContentWrapInner.hide();
        
        if (type == 'new')  ShowFoldersNew();
        if (type == 'arch') ShowFoldersArch();
        
        // Загрузка списка папок:
        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();
                    RenderFoldersList(type, data['folders']);
                    archiveData = data['archive'];
                },
                error: function(rew, status, err) {
                    console.log(status, err);                    
                }
            });
            
        }
        
        
    });
    
    // Клик на "Сохранить" для объявления:
    $saveButton.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);
                    
                data[folderName] = null;
                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) {
                if(data) {
                    console.log('AAA success', data);
                    if(data.result === true) {
                        //document.location.href = data.redirect;
                        document.location.reload();
                    }
                    if(data.result === false && data.msg) {
                        //$.showMessage('error', data.msg);
                    }
                    
                }
            },
            error: function(rew, status, err) {
                console.log(status, err);                    
            }
        });
        
        return false;
    });        

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

});