$(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,
            templateFolderContent,
            templateFolderContentCommon = _.template('' +
                '<div class="b-folder-content row 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_number"></div>' +
                '           </div>' +
                '       </div>' +
                '   <% if (((ind % 2) != 0) && (ind<files.length-1)) { %>' +
                '   </div>' +
                '   <div class="b-foto-double col">' +
                '   <% } %>' +
                '   <% }) %>  \n' +
                '   </div>' +
                '</div>'
            ),
            templateFolderContent23 = _.template('' +
                '<div class="b-folder-content row 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" data-foto="<%= item %>" data-num="">' +
                '               <img class="b-foto_img" src="<%= folder %>/<%= item %>" >' +
                '               <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)
    {
        if (folderType == 'arch') {
            if (archiveData[folderName]) {
                var pairs = Object.keys(archiveData[folderName]);
                if (pairs.length > 0)
                {
                    var $folderContentWrap = $('.b-folder-content[data-folder="' + folderName + '"]', $foldersArchContentWrap);
                    pairs.forEach(function(pair){
                        $('.b-foto_inner[data-foto="' + archiveData[folderName][pair][0] + '"] ', $folderContentWrap).trigger( "click", {data: 'emul'});
                        $('.b-foto_inner[data-foto="' + archiveData[folderName][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">'),
            $fotoPair = $pairedFoto.parent('.b-foto'),
            $fotoThis = $this.parent('.b-foto'),
            foto1 = $fotoPair.remove(),
            foto2 = $fotoThis.remove();
    
        foto1.appendTo($divDoublePair);
        foto2.appendTo($divDoublePair);
        
        var $doublePaired = $('.b-foto-double.pair', $currentFolderWrap);
        
        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) {
            return false;
        }
        
        
        RegroupRemainingFotos($currentFolderWrap);
    }
    
    function RegroupRemainingFotos($currentFolderWrap)
    {
        // Перегруппируем оставшиеся фото:
        var
            $remainingFotos = $('.b-foto-double:not(.pair) .b-foto', $currentFolderWrap);
        
        console.log('AAA $remainingFotos ', $remainingFotos.length);
        
        $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){
                //console.log('AAA $remainingFotos ', 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);
        }
    }
    
    function ShowFoldersNew()
    {
        $listFoldersNew.show();
        $foldersNewContentWrap.addClass('active');
    }
    
    function ShowFoldersArch()
    {
        $listFoldersArch.show();
        $foldersArchContentWrap.addClass('active');
    }
    
    // Обработка нажатия клавиш:
    $body.keyup(function(e) {
        
        // Пробел
        if (e.keyCode == 32)
        {
            var
                $activeFolder = $('.b-preview_inner.active .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(event, param){
        
        var isEmul = false;
        if (param && (param['data'] == 'emul')) {
            isEmul = true;
        }
        
        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);
                
                CreatePair($currentFolderWrap, $pairedFoto, $this);
                
                if (!isEmul) {
                    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 (!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);
            }
            
            $('.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.removeClass('active');
        
        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);
        //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;
                        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();

});