$(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'),
        storageName = 'im_fotos',
        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') {
            if (!$folderName.hasClass('viewed')) {
                $folderName.addClass('viewed');
                $saveButton.removeClass('disabled');
                SaveLsState();
            }
        }
    }
    
    function MarkArchFolderViewed(folderName, $this)
    {
        if ($this.parents('.b-preview_inner').hasClass('arch')) {
            $('.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_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' +
                '   </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_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, dataStorage);

        var sourceData = null;

        if (folderType == 'new') {
            
            if (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[folderName]) sourceData = archiveData[folderName];
            if (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()
    {
        $listFoldersNew.show();
        $foldersNewContentWrap.addClass('active');
    }
    
    function ShowFoldersArch()
    {
        $listFoldersArch.show();
        $foldersArchContentWrap.addClass('active');
    }
    
    function SaveLsState()
    {
        var data = GetFoldersDataState();
        console.log('AAA SaveLsState ', data);
        localStorage.setItem(storageName, JSON.stringify(data));
    }
    
    function SetStateFromLs(folder)
    {
        var data = localStorage.getItem(storageName);
        if (data) {
            dataStorage = JSON.parse(data);
            console.log('AAA SetStateFromLs ', dataStorage);
            
            if (folder == 'new' || folder == 'arch') {
                Object.keys(dataStorage).forEach(function(item){
                    console.log('AAA  ', 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);
                    }
                    
                    
                });
            } else {
                
            }
            
        }
        
    }
    
    function GetFoldersDataState()
    {
        // Формируем данные о картинках-парах:
        var data = {};
        if (dataStorage) {
            data = dataStorage;
        }
        
        $('.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;
                }
            }
        });
        return data;
    }
    
    // Обработка нажатия клавиш:
    $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,
            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(){
        
        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);
                    MarkNewFolderViewed($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();
                    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 = {};
        $('.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;
                        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;
    });        

    
    // Отображаем содержимое первой папки new при загрузке страницы:
    ShowFoldersNew();
    SetStateFromLs('new');

});