<div id="media" class="modal fade" tabindex="-1" style="display: none;" aria-hidden="true">
	<div class="modal-dialog modal-full media-modal">
		<div class="modal-content media-modal-content">
			<div class="media-frame">
				<div class="modal-header">
					<h6 class="modal-title">{fileManager:title}</h6>
					<button type="button" class="btn-close close" data-bs-dismiss="modal"></button>
				</div>

				<div class="media-frame-content">

					<div class="attachments-browser">
						<div class="breadcrumb breadcrumb-line header-elements-inline border-bottom">
							<div class="d-flex">
								<div class="breadcrumb breadcrumb_path"></div>
							</div>
							<div class="d-lg-block ms-lg-auto">
								<div class="breadcrumb justify-content-center py-2">
									<div class="media-actions">
										<div class="list-icons">
											<span class="count_check list-icons-item me-2"></span>
											<a href="javascript:void('')" class="list-icons-item select-all" data-popup="tooltip" data-placement="top" data-trigger="hover" data-action="select_all"  data-original-title="Выбрать все"><i class="ph-plus-circle"></i></a>
											<a href="javascript:void('')" class="list-icons-item deselect-all mx-1" data-popup="tooltip" data-placement="top" data-trigger="hover" data-action="deselect_all" data-original-title="Отменить"><i class="ph-minus-circle"></i></a>
											<a href="javascript:void('')" class="list-icons-item text-danger remove-files" data-popup="tooltip" data-placement="top" data-trigger="hover" data-action="delete" data-confirm="Вы действительно хотите удалить выбранные файлы? Не забывайте что картинка может прикреплена к контенту!!!" data-original-title="Удалить выбранные"><i class="ph-x-circle"></i></a>
										</div>
									</div>
								</div>
							</div>
						</div>
						<div class="media-toolbar border-bottom">
							<div class="media-toolbar-secondary">
								<ul class="nav nav-tabs nav-tabs-overline border-top-0 mb-0">

									<li class="nav-item"><a href="#listFiles" class="nav-link active show" data-bs-toggle="tab"><i class="ph-folder-notch"></i></a></li>
									<li class="nav-item"><a href="#uploadFile" class="nav-link" data-bs-toggle="tab"><i class="ph-cloud-arrow-up"></i></a></li>
									<li class="nav-item"><a href="javascript:void('')" class="nav-link new_folder" data-bs-path="{if isset($path)}{$path|escape}{else}/{/if}" data-action="new_folder" data-confirm="{fileManager:addFolder}"><i class="ph-folder-notch-plus"></i></a></li>
									<li class="nav-item px-3">
										<div class="input-group">
											<select id="attachment_filters_mime" name="type" class="form-control select" data-width="220">
												<option value="0" selected>Все медиафайлы</option>
												<option value="mine">Мои файлы</option>
											</select>
											<select id="attachment_filters" name="filters" class="form-control select" data-width="200">
												<option value="0" selected>Все</option>
												<option value="date">По новизне</option>
												<option value="size">По размеру</option>
												<option value="name">По имени файла</option>
											</select>
										</div>
									</li>
								</ul>
							</div>
							<div class="media-toolbar-primary">

								<div class="media-search">
									<div class="input-group">
										<input id="search_file" type="text" class="form-control" placeholder="Поиск по названию файла" style="min-width: 230px">
									</div>
								</div>
							</div>
						</div>

						<div class="attachments">
							<div class="tab-content border-top-0 rounded-top-0 mb-0">
								<div class="tab-pane fade show active" id="listFiles">
									<div id="file_list" class="row"></div>
									<div id="modal_show_more_trigger" data-page="1" data-max="" data-path="{if isset($path)}{$path|escape}{else}/{/if}"></div>
								</div>
								<div class="tab-pane fade" id="uploadFile">
									<div class="fileupload-process my-1">
                                        <div id="total-progress" class="progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" style="height: 0.625rem;">
                                            <div class="progress-bar progress-bar-striped progress-bar-animated  bg-success" style="width:0%;" data-dz-uploadprogress=""></div>
                                        </div>
                                    </div>
									<div id="upload_files" class="dropzone">
										<div class="dz-default dz-message"><span>Максимальный размер загружаемого файла: {$upload_max_filesize}.</span></div>
										<input type="hidden" name="send_path" value="{if isset($path)}{$path|escape}{else}/{/if}" id="send_path">
									</div>
								</div>
							</div>
						</div>
						<div class="media-sidebar bg-light border-start">
							<div class="media-uploader-status">
								<div class="attachment-details pt-2"></div>
							</div>
						</div>
					</div>
				</div>

				<div class="media-frame-toolbar">
					<div class="media-toolbar border-top">
						<div class="media-toolbar-secondary"> </div>
						<div class="media-toolbar-primary">
							<button type="button" class="btn btn-sm btn-link" data-bs-dismiss="modal">{general:cancel}</button>
							<button type="button" class="btn btn-sm btn-primary add-content" data-type="" data-action="" data-model="">{general:choose}</button>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
{literal}
<style>
    .dropzone .dz-preview.dz-success .dz-progress {
	    display: none !important;
        opacity: 0 !important;
        height: 0px;
    }
</style>
<script>

    var modal_block_show = false, countSelected = 0;

    function capitalize(s) {
        return s[0].toUpperCase() + s.slice(1);
    }

    // название функции переименовывать нельзя (подвязно к tinymce)
    function media_content(path, type) {

        $("#media").modal('show');
        // set parameters in localStorage
        settingPath(path, 1);
        localStorage.setItem('type', type);

        if (path === undefined  || path === null) {
            $('.breadcrumb_path').html('<a href="index.php?mod=uploads&path=/" data-path="/" class="breadcrumb-item read-more">'+ capitalize('uploads') +'</a>');
        } else {
            var nav = '<a href="index.php?mod=uploads&path=/" data-path="/" class="breadcrumb-item read-more">'+ capitalize('uploads') +'</a>';
            var breadcrumb = path.split('/'), prevLink = "";
            $.each(breadcrumb, function(u, i) {
                if (i.length > 0) {
                    prevLink += '/'+i;
                    nav += '<a href="index.php?mod=uploads&path=' + path + '" data-path="'+ prevLink +'" class="breadcrumb-item read-more">' + capitalize(i) + '</a> ';
                }
            });
            $('.breadcrumb_path').html(nav);
            $(".attachment-details").hide();

            $(".add-content").attr('data-type', localStorage.getItem('type'));
        }

        uploadingData();
    }


    function mediaMenuItem(path) {
        settingPath(path, 1);
        media_content (path, localStorage.getItem('type'))
    }

    function uploadingData() {
        var query = localStorage.getItem('query'), path = localStorage.getItem('path'), type = localStorage.getItem('mime'), filters = localStorage.getItem('filter');
        document.getElementById('file_list').innerHTML = '';
        $("#file_list").load("index.php?mod=uploads&action=read_more", { query: query, path: path, type: type, filters: filters }, function(response) {
            selectCount(0);
            $("#media").modal('show');
        });
    }

    function settingPath(path, page) {

        const modalShowMoreTrigger = $('#modal_show_more_trigger');
        localStorage.setItem('path', path);
        localStorage.setItem('page', page);

        $('.new_folder').attr("data-path", localStorage.getItem('path'));
        modalShowMoreTrigger.attr('data-page', localStorage.getItem('page'));
        modalShowMoreTrigger.attr("data-path", localStorage.getItem('path'));

        var searchQuery = localStorage.getItem('query');
        if (searchQuery) {
            $('#search_file').val(searchQuery);
        }
        // установить selected option attachment_filters_mime
        uploadingSelectMime();
        // установить selected option attachment_filters
        uploadingSelectFilter();

        $('#attachment_filters').trigger('change');
        $('#attachment_filters_mime').trigger('change');
    }

    // установить selected option attachment_filters_mime
    function uploadingSelectMime() {
        let selectMime = document.querySelector("#attachment_filters_mime");
        selectOption(selectMime, localStorage.getItem('mime'));
    }

    // установить selected option attachment_filters
    function uploadingSelectFilter() {
        let selectFilter = document.querySelector("#attachment_filters");
        selectOption(selectFilter, localStorage.getItem('filter'));
    }

    // если есть ранее выбранный элемент в select то устанавливаем его как выбранный
    function selectOption(select, value) {
        for ( var i = 0, len = select.options.length; i < len; i++ ) {
            if (select.options[i].value === value) {
                select.options[i].selected = true;
                break;
            }
        }
    }

    // установить кол-во выбранных элементов
    function selectCount(count) {
        if (count > 0) {
            $('.media-actions').show();
            $('.count_check').html('Выбрано (<b>' + count + '</b>)');
        } else {
            $('.media-actions').hide();
        }
    }


    // Setup module
    // ------------------------------
    var Files = function () {

        Dropzone.autoDiscover = false;

        var _componentDropzone = function() {
            if (typeof Dropzone == 'undefined') {
                console.warn('Warning - dropzone.min.js is not loaded.');
                return;
            }

            $(document).ready(function () {
                const id = "#upload_files";
                // const dropzone = document.querySelector(id);

                // $("#upload_files").dropzone({
				let dropzoneSingle = new Dropzone(id, {
                    dictDefaultMessage:             lang['dictDefaultMessage'],
                    dictFallbackMessage:            lang['dictFallbackMessage'],
                    dictFallbackText:               lang['dictFallbackText'],
                    dictFileTooBig:                 lang['dictFileTooBig'],
                    dictInvalidFileType:            lang['dictInvalidFileType'],
                    dictResponseError:              lang['dictResponseError'],
                    dictCancelUpload:               lang['dictCancelUpload'],
                    dictCancelUploadConfirmation:   lang['dictCancelUploadConfirmation'],
                    dictRemoveFile:                 lang['dictRemoveFile'],
                    dictRemoveFileConfirmation:     lang['dictRemoveFileConfirmation'],
                    dictMaxFilesExceeded:           lang['dictMaxFilesExceeded'],
                    paramName: "file",
                    url: "index.php?mod=uploads&action=upload",
                    addRemoveLinks: true,
                    maxFilesize:  1024,
                    maxFiles: 100,
                    params: { action: 'upload' },
				});

	            dropzoneSingle.on("totaluploadprogress", function(progress) {
		            document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
		            document.querySelector("#total-progress .progress-bar").innerHTML = Math.ceil(progress) + "%";
	            });

	            dropzoneSingle.on('sending', function (file, xhr, formData) {
		            $('#upload_files').addClass('dz-started');
		            formData.append('path', localStorage.getItem('path'));

		            document.querySelector("#total-progress").style.opacity = "1";
                    document.querySelectorAll(".dz-progress").forEach(e => e.remove());
	            });

	            dropzoneSingle.on("success", function (file, response) {
		            if (response.status !== 200) {
			            $(file.previewElement).find('.dz-error-mark').css('display', 'block').css('opacity', 1);
		            }
		            new Noty({ text: response.message, type: response.type }).show();
	            });

	            dropzoneSingle.on("queuecomplete", function () {
		            setTimeout(function () {
                        document.querySelector("#total-progress .progress-bar").style.opacity = "0";
                        document.querySelector("#total-progress .progress-bar").style.width = 0 + "%";
		            }, 300);

		            $("#file_list").load("index.php?mod=uploads&action=read_more", { query: localStorage.getItem('query'), path: localStorage.getItem('path'), type: localStorage.getItem('mime'), filters: localStorage.getItem('filter')}, function() {
			            setTimeout(function () {
				            $('.dz-success').fadeOut('slow');
				            setTimeout(function () {
					            $('#upload_files').removeClass('dz-started');
				            }, 800);
			            }, 1000);
		            });
	            });

	            dropzoneSingle.on('error', function (file, response) {
		            // $(file.previewElement).find('.dz-error-message');
		            console.log("error file => ", file);
		            console.log(response)
		            new Noty({ text: response, type: 'error' }).show();
	            });
            });
        }

        var _componentFileManager = function () {

            var index_color = '';
            // подгрузка всех данных по пути
            $(document).on('click', '.read-more', function(e) {
                e.preventDefault();
                var $this = $(this), type;
                modal_block_show = false;

                if ($this.data('type') === undefined) {
                    type = localStorage.getItem('type')
                } else {
                    localStorage.setItem('type', $this.data('type'))
                    type = localStorage.getItem('type')
                }

                if ($this.data('color') === undefined) {
                    index_color = localStorage.getItem('color')
                } else {
                    localStorage.setItem('color', $this.data('color'))
                    index_color = localStorage.getItem('color')
                }


                media_content ($this.data('path'), type)
            });


            // подгрузка всех данных по выбору
            $(document).on("change", "#attachment_filters", function () {
                localStorage.setItem('filter', $(this).val());
                uploadingData();
            });

            $(document).on("change", "#attachment_filters_mime", function () {
                localStorage.setItem('mime', $(this).val());
                uploadingData();
            });

            // читать файл
            $(document).on('click', '.card_file_item',  function() {
                var $this = $(this), template, fileIds = [], attachmentDetail = $(".attachment-details"), type = $('.add-content').attr('data-type');

                if (type === 'image') {
                    $('.file-manager-list').removeClass('selected details');
                    $('.file-manager-list .card').removeClass('border-primary border-opacity-50');

                    $this.closest('figure').addClass('selected details');
                    $this.closest('figure .card').addClass('border-primary border-opacity-50');
                    fileIds.push($(this).attr('data-id'));
                } else {
                    $this.closest('figure').toggleClass('selected details');
                    $this.closest('figure .card').toggleClass('border-primary border-opacity-50');
                    $('.media-actions').show();
                    $('.media-search').hide();
                    $('.file-manager-list.selected').each(function () {
                        fileIds.push($(this).attr('data-id'));
                    })
                }
                console.log(fileIds)
                if (fileIds.length === 0) {
                    $('.media-search').show();
                }
                countSelected = $('.file-manager-list.selected').length
                selectCount(countSelected);
                if (countSelected > 0 && countSelected < 2) {
                    $.post('index.php?mod=uploads&action=get_file', { fileIds: fileIds, path: localStorage.getItem('path') }).done(function (res) {
                        attachmentDetail.show();
                        $.each(res, function (i, item) {
                            if (item.class_ext === 2) {
                                template = itemCard.templateImage;
                            } else if (item.class_ext === 4) {
                                template = itemCard.templateVideo;
                            } else if (item.class_ext === 5) {
                                template = itemCard.templateAudio;
                            } else {
                                template = itemCard.templateDefault;
                            }
                            for (var idx in item) {
                                template = template.replace(new RegExp("{{" + idx + "}}", "gim"), item[idx]);
                            }
                            template = template.replace(/{{\w*}}/gim, "");
                            attachmentDetail.html(template);
                        });
                    }, "json")
                        .fail(function() {
                            console.log( "error" );
                        })
                        .always(function() {
                            console.log( "finished" );
                        });
                } else {
                    attachmentDetail.hide();
                }
            });

            // выделить все файлы
            $(document).on('click','.select-all', function() {
                $('.file-manager-list').each(function() {
                    $(this).closest('figure').addClass('selected details');
                    $(this).closest('figure .card').addClass('border-primary border-opacity-50');

                });
                countSelected = $('.file-manager-list.selected').length
                selectCount(countSelected);
                $('.attachment-details').hide();
            });

            // отмена выделенных файлов
            $(document).on('click','.deselect-all', function() {
                $('.file-manager-list').each(function() {
                    $(this).closest('figure').removeClass('selected details');
                    $(this).closest('figure .card').removeClass('border-primary border-opacity-50');
                });
                countSelected = $('.file-manager-list.selected').length
                selectCount(countSelected);
                $('.attachment-details').hide();
            });

            // Добавление к контенту, в галерею и основную картинку
            $(document).on('click','.add-content', function() {
                var fileIds = [], type = $(this).attr('data-type'), template;
                $('.file-manager-list.selected').each(function () {
                    fileIds.push($(this).attr('data-id'));
                })
                $.post("index.php?mod=uploads&action=get_file", { path: localStorage.getItem('path'), fileIds: fileIds }).done(function (response) {
                    $('.media-actions').hide();
                    $('.media-search').show();
                    $.each(response, function (i, item) {
                        $("#media").modal('hide');
                        console.log( item)
                        if (localStorage.getItem('path') == 'admin') {
                            $('.profile-thumb').replaceWith('<div class="profile-thumb">' +
                                '<img src="' + item.url + '" class="img-thumbnail rounded-circle shadow" width="100" height="100" alt="">' +
                                '<input type="hidden" name="image[fileId]" value="' + item.fileId + '" />' +
                                '</div>');
                        } else {
                            console.log(item)
                            if (item.class_ext === 2) {
                                // add preview
                                if (type === 'image') {
                                    // заменить текст кнопки при добавление картинки
                                    document.getElementById('content-image-preview-add').innerHTML = '<i class="ph-image me-2"></i>{general:changeFile}';

                                    // дабавляем блок с добавленной картинкой
                                    document.getElementById('content-image-preview').innerHTML =
                                    '<div class="card-img-actions card-image-preview" id="image_general-'+ item.fileId +'">' +
                                        '<input type="hidden" name="image[fileId]" value="'+ item.fileId +'" />' +
                                        '<img class="img-fluid" src="'+ item.url +'" alt="">' +
                                    '</div>';

	                                // проверить на существование кнопки, если нету то добавить кнопку удаления
                                    const element = document.getElementById('content-image-preview-remove');
                                    if (!element) {
                                        document.getElementById('preview-image-footer').innerHTML += '<button id="content-image-preview-remove" type="button" class="btn btn-sm btn-danger" onclick="removePreviewImage()"><i class="ph-trash me-2"></i>{/literal}{general:delete}{literal}</button>';
                                    }
                                }
                                else if (type === 'colors') {
                                    console.log(index_color);
                                    $("#color-" + index_color + " .preview").replaceWith('<div class="preview preview-md"><img src="'+ item.url +'" class="img-thumbnail w-80px"/></div>');
                                    $("#color-" + index_color + " .file_id").val( item.fileId);
                                }

                                // add content tinyMCE
                                else if (type === 'content') {
                                    parent.tinyMCE.execCommand('mceInsertContent', false, '<img class="" src="' + response[i].url + '"/>');
                                }

                                // add gallery
                                else {
                                    $(".btn-upload").html('<i class="ph-image me-2"></i> Еще добавить ');
                                    document.getElementById('fileList').innerHTML +=
	                                    '<figure class="gallery-item mb-0" id="gallery-item-'+ item.fileId +'" data-id="'+ item.fileId +'">' +
                                            '<div class="image">' +
                                                '<input type="hidden" name="gallery['+ item.fileId +'][fileId]" value="'+ item.fileId +'" />' +
                                                '<img src="'+ item.url +'"/>' +
                                                '<ul class="gallery-item-controls">' +
                                                    '<li><span onclick="removePicture('+ item.fileId +')"><i class="ph-trash"></i></span></li>' +
                                                '</ul>' +
                                            '</div>' +
                                        '</figure>';
                                }
                            }
							// add document
                            if (item.class_ext === 1) {
                                $(".btn-docs").html('<i class="ph-file-doc me-2"></i> Еще добавить ');

                                document.getElementById('pdf_docs').innerHTML +=
	                                '<figure class="docs mb-2" id="docs-item-'+ item.fileId +'">' +
                                        '<div class="input-group">' +
                                            '<span class="input-group-text"><img src="/admin/assets/ico/'+ item.extension +'.svg" width="30"/></span>' +
                                            '<input type="text" class="form-control" value="'+ item.fileName +'">' +
                                            '<input type="hidden" name="docs['+ item.fileId +'][fileId]" value="'+ item.fileId +'" />' +
                                            '<button type="button" class="btn btn-danger remove-docs" data-id="'+ item.fileId +'"><i class="ph-trash"></i></button>' +
                                        '</div>' +
                                    '</figure>'
                            }
                        }
                    });
                });

            });

            // добавление папки
            $(document).on('click', '.new_folder', function() {
                var confirm = $(this).attr("data-confirm");
                bootbox.prompt({
                    title: confirm,
                    callback: function (name) {
                        if (name !== null) {
                            $.post('index.php?mod=uploads&action=new_folder', { path: localStorage.getItem('path'), name: name }, function (response) {
                                if (response.status === 200) {
                                    $("#file_list").load("index.php?mod=uploads&action=read_more", { 'path': localStorage.getItem('path') }, function () {
                                        new Noty({ text: response.message, type: 'success' }).show();
                                    });
                                } else {
                                    new Noty({ text: response.error, type: 'error' }).show();
                                }
                            });
                        }
                    }
                })
            });

            // удаление файла или папки
            $(document).on('click','.remove_folder',function() {
                var confirm = $(this).attr("data-confirm"), folder = $(this).attr("data-folder");
                bootbox.confirm({
                    closeButton: false,
                    message: confirm,
                    callback: function(res) {
                        if (res === true) {
                            $.post("index.php?mod=uploads&action=delete_folder", { path: localStorage.getItem('path'), folder: folder }).done(function (response) {
                                // console.log(data);
                                if (response.status === 200) {
                                    $("#file_list").load("index.php?mod=uploads", { action: "read_more", 'path': localStorage.getItem('path') }, function() {
                                        new Noty({ text: response.message, type: 'success' }).show();
                                    });
                                } else {
                                    bootbox.confirm({
                                        closeButton: false,
                                        message: response.message,
                                        buttons: {
                                            confirm: { label: 'Yes',  className: 'btn-sm btn-success' },
                                            cancel: { label: 'No',  className: 'btn-sm btn-danger' }
                                        },
                                        callback: function(res) {
                                            // console.log(res)
                                            if (res === true) {
                                                $.post("index.php?mod=uploads&action=confirm_remove_folder", { path: localStorage.getItem('path'), folder: folder }).done(function (response) {
                                                    console.log(response)
                                                    if (response.status === 200) {
                                                        $("#file_list").load("index.php?mod=uploads", { action: "read_more", 'path': localStorage.getItem('path') }, function () {
                                                            new Noty({ text: response.message, type: 'success' }).show();
                                                        });
                                                    }
                                                }, 'json');
                                            }
                                        }
                                    });
                                }
                            }, 'json');
                        }
                    }
                })
            });

            //  удаление файла / удаление файлов
            $(document).on('click','.remove-files',function() {
                var confirm = $(this).attr("data-confirm"), fileIds = [$(this).attr("data-id")];
                bootbox.confirm({
                    closeButton: false,
                    message: confirm,
                    callback: function (result) {
                        if (result === true) {
                            $('.file-manager-list.selected').each(function () {
                                fileIds.push($(this).attr('data-id'));
                            })
                            console.log(fileIds);
                            $.post("index.php?mod=uploads&action=remove", { fileIds: fileIds, path: localStorage.getItem('path') }).done(function (response) {
                                if (response.status === 200) {
                                    $('.attachment-details').hide();
                                    uploadingData();
                                    new Noty({ text: response.message, type: 'success' }).show();
                                }
                            }, 'json');
                        }
                    }
                });
            });


            // $(document).on('click', '.remove-gallery-image', function() {
            //     var elem = document.getElementById($(this).attr('data-val') + '-' + $(this).attr('data-id'));
            //     elem.parentNode.removeChild(elem);
            //     return false;
            // });

            $(document).on('click','.remove-docs', function() {
                var elem = document.getElementById('docs-item-' + $(this).attr('data-id'));
                elem.parentNode.removeChild(elem);
                return false;
            });

            // поиск по названию файлу
            $("input#search_file").keyup(function count() {
                var query = $('#search_file').val();
                localStorage.setItem('query', query);
                console.log(localStorage.getItem('query'))
                uploadingData();
            })

            $(".info").on("click", function() {
                bootbox.alert('<div class="text-center"><br/><img src="{/literal}{$GLOBAL_URL}{literal}/admin/assets/img/logo-mnv.svg" alt="Файл менеджер"/><br/><br/><p><strong>Файл менеджер v.1.0.2</strong><br/><a href="https://www.life-style.uz/">life-style.uz</a></p><br/><p>Copyright © <a href="https://www.life-style.uz/" alt="Life Style">Life Style</a>. All rights reserved.</p><br/><p><i class="icon-medal"></i>License<br/><small><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc/3.0/">Creative Commons Attribution-NonCommercial 3.0 Unported License</a></small></p></div>');
            });

            const clipboard = new ClipboardJS('#button-copy', { text: function(trigger) {
                return $(this).attr('data-clipboard-text');
            }});

            clipboard.on('success', function (e) {
                console.info('Text:', e.text);
                $(e.trigger).removeClass('btn-light').addClass('btn-success').text('Скопировано');
                setTimeout(function(){
                    $(e.trigger).removeClass('btn-success').addClass('btn-light').text('Скопировать ссылку');
                }, 2000);
            });

            clipboard.on('error', function (e) {
                $(e.trigger).removeClass('btn-light').addClass('btn-danger').text('Ошибка копирования');
                setTimeout(function(){
                    $(e.trigger).removeClass('btn-danger').addClass('btn-light').text('Скопировать ссылку');
                }, 2000);
            });
        }

        var itemCard = {
            templateImage: '' +
                '<div class="card border shadow-sm">' +
                    '<div class="card-img bg-light rounded-top text-center"><img src="{{url}}" class="img-fluid rounded-top" /></div>'+
                    '<div class="card-file-upload-body p-2">' +
                        '<div class="img-apply">' +
	                        '<div class="card-title fw-semibold mb-1"><i class="ph-image text-muted me-2"></i>{{fileName}}</div>' +
	                        '<div class="font-size-sm text-muted mb-1"><i class="ph-image me-2"></i> {{size}}</div>' +
                            '<div class="font-size-sm text-muted mb-1"><input type="text" id="copy_link" value="{{url}}" class="form-control" readonly /></div>' +
                            '<div class="font-size-sm text-muted mb-1">' +
                                '<button id="button-copy" class="btn btn-light btn-sm" data-clipboard-action="copy" data-clipboard-target="#copy_link" data-clipboard-text="{{url}}">Скопировать ссылку</button>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>',
            templateVideo: '' +
                '<div class="card border shadow-sm video">' +
                    '<div class="card-img bg-light rounded-top text-center">' +
                        '<video width="400" controls class="img-fluid rounded-top" style="min-height: 100px;">' +
                            '<source src="{{url}}" type="video/{{extension}}">' +
                        '</video>' +
                    '</div>' +
                    '<div class="card-file-upload-body p-2">' +
                        '<div class="img-apply">' +
                            '<div class="card-title fw-semibold mb-1"><i class="ph-file-video text-muted"></i> {{fileName}}</div>' +
                            '<div class="font-size-sm text-muted mb-1"><i class="ph-file-video"></i> {{size}}</div>' +
                            '<div class="font-size-sm text-muted mb-1"><input type="text" id="copy_link" value="{{url}}" class="form-control" readonly /></div>' +
                            '<div class="font-size-sm text-muted mb-1">' +
                                '<button id="button-copy" class="btn btn-light btn-sm" data-clipboard-action="copy" data-clipboard-target="#copy_link" data-clipboard-text="{{url}}">Скопировать ссылку</button>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>',
            templateAudio: '' +
                '<div class="card border shadow-sm icon">' +
                    '<div class="card-img bg-light rounded-top text-center media-wrapper">' +
                        '<audio id="player2" preload="none" src="{{url}}" controls style="max-width:100%; background-color: #f1f3f4;">' +
                            '<source src="{{url}}" type="audio/{{extension}}">' +
                        '</audio>' +
                    '</div>' +
                    '<div class="card-file-upload-body p-2">' +
                        '<div class="img-apply">' +
                            '<div class="card-title fw-semibold mb-1"><i class="ph-file-audio text-muted"></i> {{fileName}}</div>' +
                            '<div class="font-size-sm text-muted mb-1"><i class="ph-file-audio"></i> {{size}}</div>' +
                            '<div class="font-size-sm text-muted mb-1"><input type="text" id="copy_link" value="{{url}}" class="form-control" readonly /></div>' +
                            '<div class="font-size-sm text-muted mb-1">' +
                                '<button id="button-copy" class="btn btn-light btn-sm" data-clipboard-action="copy" data-clipboard-target="#copy_link" data-clipboard-text="{{url}}">Скопировать ссылку</button>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>',
            templateIcon: '' +
                '<div class="card border shadow-sm icon">' +
                    '<div class="card-img bg-light rounded-top text-center"><img src="{{icon}}" class="img-fluid" style="min-height: 100px;"/></div>' +
                    '<div class="card-file-upload-body p-2">' +
                        '<div class="img-apply">' +
                            '<div class="card-title fw-semibold mb-1"><i class="ph-image text-muted"></i> {{fileName}}</div>' +
                            '<div class="font-size-sm text-muted mb-1"><i class="ph-image"></i> {{size}}</div>' +
                            '<div class="font-size-sm text-muted mb-1"><input type="text" id="copy_link" value="{{url}}" class="form-control" readonly /></div>' +
                            '<div class="font-size-sm text-muted mb-1">' +
                                '<button id="button-copy" class="btn btn-light btn-sm" data-clipboard-action="copy" data-clipboard-target="#copy_link" data-clipboard-text="{{url}}">Скопировать ссылку</button>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>',
            templateDefault: '' +
                '<div class="card default">' +
                    '<div class="card-img bg-light rounded-top text-center"><img src="{{icon}}" class="img-fluid" style="min-height: 100px;"/></div>' +
                    '<div class="card-file-upload-body p-2">' +
                        '<div class="img-apply">' +
                            '<div class="card-title fw-semibold mb-1">{{fileName}}</div>' +
                            '<div class="font-size-sm text-muted mb-1"><i class="ph-image"></i> {{size}}</div>' +
                            '<div class="font-size-sm text-muted mb-1"><input type="text" id="copy_link" value="{{url}}" class="form-control" readonly /></div>' +
                            '<div class="font-size-sm text-muted mb-1">' +
                                '<button id="button-copy" class="btn btn-light btn-sm" data-clipboard-action="copy" data-clipboard-target="#copy_link" data-clipboard-text="{{url}}">Скопировать ссылку</button>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>',
            templateSelectBColor:  '<figure class="gallery-item mb-0" id="gallery-bcolor-{{fileId}}" data-id="{{fileId}}">' +
                '<div class="image">' +
	            '<input type="hidden" name="colors[{{fileId}}][fileId]" value="{{fileId}}" />' +
                '<input type="hidden" name="colors[{{fileId}}][type]" value="bcolors" />' +
                '<img src="{{url}}"/>' +
                '<ul class="gallery-item-controls">' +
                '<li><span>0</span></li>' +
                '<li><span class="remove-image" data-val="gallery-item" data-id="{{fileId}}"><i class="icon-cross2"></i></span></li>' +
                '</ul></div></figure>',
            templateSelectIColor:  '<figure class="gallery-item mb-0" id="gallery-icolor-{{fileId}}" data-id="{{fileId}}">' +
                '<div class="image">' +
	            '<input type="hidden" name="colors[{{fileId}}][fileId]" value="{{fileId}}" />' +
                '<input type="hidden" name="colors[{{fileId}}][type]" value="icolors" />' +
                '<img src="{{url}}"/>' +
                '<ul class="gallery-item-controls">' +
                '<li><span>0</span></li>' +
                '<li><span class="remove-image" data-val="gallery-item" data-id="{{fileId}}"><i class="icon-cross2"></i></span></li>' +
                '</ul></div></figure>',

        }

        // подгрузка при скроле
        function modalScrollMore() {
            var $target = $('#modal_show_more_trigger'),
	            listFiles = $('#listFiles');

            if (modal_block_show) {
                return false;
            }

            var wt = $(window).scrollTop(),
	            wh = $(window).height(),
	            et = $target.offset().top,
	            eh = $target.outerHeight(),
	            dh = $(document).height();

            if (wt + wh >= et || wh + wt === dh || eh + et < wh) {
                var page = $target.attr('data-page');
                page++;
                modal_block_show = true;
                localStorage.setItem('page', page);
                $.ajax({
                    type: "POST",
                    url: 'index.php?mod=uploads&action=read_more_files&page=' + localStorage.getItem('page'),
                    dataType: 'JSON',
                    data : { query: localStorage.getItem('query'), path: localStorage.getItem('path'), type: localStorage.getItem('mime'), filters: localStorage.getItem('filter') },
                    beforeSend: function() {
                        listFiles.block({ centerY: false, centerX: false, message: '<i class="ph-spinner spinner"></i>',
                            overlayCSS: { 'z-index' : 98, backgroundColor: '#fff', opacity: 0.8, cursor: 'wait' },
                            css: { 'z-index' : 99,  border: 0, padding: 0, backgroundColor: 'none', position: 'fixed', margin: 'auto' }
                        });
                    },
                    success: function(response) {
                        if (response.status === 200) {
                            $('#file_list').append(response.items);
                            modal_block_show = false;
                            window.setTimeout(function () {
                                listFiles.unblock();
                                }, 400);
                        } else {
                            modal_block_show = true;
                            window.setTimeout(function () {
                                listFiles.unblock();
                            }, 400);
                        }
                    }
                });

                $target.attr('data-page', localStorage.getItem('page'));
                if (page === $target.attr('data-max')) {
                    $target.remove();
                }
            }
        }

        $('.attachments').scroll(function(){
            modalScrollMore();
        });

        return {
            initComponents: function() {
                _componentDropzone();
                _componentFileManager();
            },

            initCore: function() {
                Files.initComponents();
            }
        }
    }();

    document.addEventListener('DOMContentLoaded', function() {
        Files.initCore();
    });


</script>
{/literal}