/**
 * Druga wersja pluginu:
 *  - usunięte element zwiazane z sekcjami - zostaną przeniesione do innego pluginu
 *  - dropbox do uploadu plików
 *  - osobna karta do ładowania pluginów z ustawieniem url'a
 *  - widok miniatur z checkboxem
 */
(function ($) {

    Array.prototype.inArray = function (value) {
        // Returns true if the passed value is found in the
        // array. Returns false if it is not.
        var i;
        for (i = 0; i < this.length; i++) {
            if (this[i] == value) {
                return true;
            }
        }
        return false;
    };

    $.fn.bitResource = function (options) {
        return this.each(function () {
            if (undefined == $(this).data('bitResource')) {
                var plugin = new $.bitResource(this, options);
                $(this).data('bitResource', plugin);
            }
        });
    };

    $.bitResource = function (element, options) {

        var $element = $(element);

        var plugin = this;
        var defaults = {
            /**
             * Filtr formatów: klucz określa nazwę, wartość (tablica) - rozszerzenia formatów,
             * filterFormat: {
             *      Obrazy: ['bmp','png'],
             *      PDF: ['pdf'],
             *      'Dokumenty worda': ['docx','doc'],
             *      Filmy: {
             *          extensions: ['avi','flv','mp4'],
             *          active: true,
             *          disabled: true
             *      }
             * }
             */
            title: 'Lista sekcji', //Tytuł okna
            filterFormat: {}, //filtrowanie formatów
            selectedId: null, // ID sekcji która ma być zaznaczona i pobrana
            treeviewMaxHeight: null, // maxymalna wysokość drzewa
            filesMaxHeight: null, //maksymalna wysokość okna z plikami
            dirsUrl: '/resource/index/get-dirs', //url pobierania plików
            dirsType: 'Zasoby', // 'Zasoby' lub 'Sekcje' //typ plików (na potrzeby akcji .../get-dirs)
            filesUrl: '/resource/index/get-resources',
            uploadUrl: '/resource/index/upload-file',
            searchContainers: false,
            searchFiles: false,
            upload: false,
            hideResource: false,
            hideTree: false,
            displayActions: false,
            containerInfoUrl: '/resource/index/get-container-info',
            pageInfoUrl: '/resource/index/get-page-info',
            filePresentation: 'miniatures', // 'miniatures', 'list'
            componentId: 'bitresource-' + Math.floor((Math.random() * 999999) + 1),
            currentNodeInputId: 'hidden-container-id',

            dropzone: false,  // zakładka dropzone
            dropzoneUrl: '/', // adres url wysyłanych plików
            dropzoneSuccessCallback: function (file, response) {
            },
            dropzoneErrorCallback: function (file, response) {
            },
            dropzoneAcceptCallback: function (file, done) {
                done();
            },
            dropzonePostParams: {},
            /**
             * pliki można zaznaczyć
             */
            filesCheckable: false,
            onlyOneFile: false,
            jsTreeCallback: function (tree) {
            },
            jsTreeCache: true,
            //źródła bibliotek
            pathSource: {
                css: {
                    dropzoneCss: '/assets/css/dropzone.css',
                    jsTreeCss: '/js/jstree/dist/themes/default/style.css',
                    resourceCss: '/app/css/resource/index/index.css'
                },
                js: {
                    dropzoneJs: '/assets/js/dropzone.min.js',
                    jsTreeJs: '/js/jstree/dist/jstree.min.js',
                    bitFileContainer: '/app/js/bit.fileContainer.js'
                }
            },
            // Czy prezentować strony w sekcji
            showPagesInTree: false,
            sort: false,
            changeListType: false,
            canGeneratePdf: false
        };
        plugin.settings = {};       //ustawienia pluginu
        var selectedElements = {};  //zaznaczone elementy {tablica asocjacyjna: klucz - id zasobu, wartość obiekt z wierszem z bazy danych} - filesCheckable, pobieranie przez metode getSelected
        var currentDir = null;      //id aktualnego elementu drzewa
        var currentDirType = null;  //typ aktualnego elementu drzewa
        var libraries = [];

        var $treeview = null;

        var filteredFormats = []; //zmienne filtrów
        var searchContainerString = '', searchFilesString = ''; //zmienne wyszukiwarek

        //private methods

        /**
         * Tworzy szkielet
         * (elementy z klasami br-* są kluczowe - w nich umieszczane są poszczególne komponenty)
         */
        function createSkeleton() {
            var $html = $('<div id="' + plugin.settings.componentId + '" class="col-xs-12">' +
                '<input type="hidden" name="' + plugin.settings.componentId + '-fkContainer" class="' + plugin.settings.currentNodeInputId + '" value="' + plugin.settings.selectedSectionId + '" />' +
                '<div class="row"><div id="tree-modal-container"></div></div></div>');

            if (!plugin.settings.hideTree) {

                var skeletonUrlFile = plugin.settings.displayActions ?
                    '/app/js/bitresource2/html/jsTreeSkeletonWithActions.html'
                    : '/app/js/bitresource2/html/jsTreeSkeleton.html';

                var lgn1 = plugin.settings.hideResource ? '12' : '4';
                jQuery.ajax({
                    url: skeletonUrlFile,
                    success: function (html) {
                        $html.find('.row').append(html);
                    },
                    async: false
                });
            }

            if (!plugin.settings.hideResource) {
                var lgn2 = plugin.settings.hideTree ? '12' : '8';
                jQuery.ajax({
                    url: '/app/js/bitresource2/html/jsTreeFilesSkeleton.html',
                    success: function (html) {
                        $html.find('.row').append(html);
                    },
                    async: false
                });
            }

            if (plugin.settings.filePresentation == 'miniatures') {
                $html.find('.files-list').addClass('ace-thumbnails clearfix filter-show-all');
            }

            if (plugin.settings.treeviewMaxHeight) {

                $html.find('.br-treeview').css('max-height', plugin.settings.treeviewMaxHeight);
            }

            if (plugin.settings.filesMaxHeight) {

                $html.find('.br-content').css({
                    'max-height': plugin.settings.filesMaxHeight,
                    overflow: 'auto'
                });
            }

            $html.find('.widget-title').html(plugin.settings.title);
            $element.append($html);
        }


        /**
         * Tworzy widok drzewa.
         *
         * @param element
         * @param simple - Jeśli true nie są podpiane zdarzenie przy onchange i ready
         */
        function createTreeBox(element, simple) {
            var $treeview = element;
            $treeview.jstree({
                'core': {
                    multiple: false,
                    'data': {
                        url: plugin.settings.dirsUrl,
                        data: function (node) {
                            if (node.id !== '#') {
                                return {
                                    id: node.li_attr['data-id'],
                                    type: plugin.settings.dirsType,
                                    showPages: plugin.settings.showPagesInTree ? 1 : 0,
                                    selected: plugin.settings.selectedId
                                };
                            } else {
                                return {
                                    id: 0,
                                    search: searchContainerString,
                                    type: plugin.settings.dirsType,
                                    showPages: plugin.settings.showPagesInTree ? 1 : 0,
                                    selected: plugin.settings.selectedId
                                };
                            }
                        }
                    },
                    'strings': {
                        'Loading ...': 'Proszę czekać...'
                    },
                    'check_callback': function (o, n, p, i, m) {
                        if (m && m.dnd && m.pos !== 'i') {
                            return false;
                        }
                        if (o === "move_node" || o === "copy_node") {
                            if (this.get_node(n).parent === this.get_node(p).id) {
                                return false;
                            }
                        }
                        return true;
                    }
                },
                plugins: [
                    // plugin.settings['jsTreeCache'] ? "state" : null,
                    "types",
                    plugin.settings.displayActions ? "contextmenu" : null,
                    "themes",
                    "html_data",
                    "ui"
                ],
                contextmenu: {
                    items: function (node) {
                        return setContextMenuActions(node);
                    }
                }
            });

            if (!simple) {
                $treeview.on("changed.jstree", function (e, data) {
                    if (typeof data.node !== 'undefined') {
                        //set current dir
                        currentDir = data.node.li_attr['data-id'];
                        currentDirType = data.node.li_attr['data-type'];
                        if (plugin.settings.displayActions) {
                            setTopToolbarActionsAllowed(data.node);
                        }

                        //get folder files
                        getDirFiles(currentDir);
                        $('#' + plugin.settings.componentId + '-hidden-upload-container-id').val(currentDir).trigger('change');
                        $('#' + plugin.settings.componentId + ' .' + plugin.settings.currentNodeInputId).val(currentDir).trigger('change');

                    }
                }).on('ready.jstree', function () {
                    $treeview.jstree(true).deselect_all();
                    $treeview.jstree(true).select_node('jstree-node-300');

                    plugin.settings['jsTreeCallback']($treeview);
                    $('#' + plugin.settings.componentId).closest('.tabbable').find('.nav-tabs li').removeClass('hidden');
                }).on('changed.jstree', function () {
                    $('#show-file-uploader2').prop('disabled', false);
                });
            }
        }

        function setContextMenuActions(node) {
            var items = {};
            if (node.li_attr['data-new'] == true) {
                items.addItem = {
                    label: "Dodaj",
                    action: function () {
                        $element.find('#add-node').click();
                    }
                };
            }
            if (node.li_attr['data-edit'] == true) {
                items.editItem = {
                    label: "Edytuj",
                    action: function () {
                        $element.find('#edit-node').click();
                    }
                };
            }
            if (node.li_attr['data-delete'] == true) {
                items.deleteItem = {
                    label: "Usuń",
                    action: function () {
                        $element.find('#remove-node').click();
                    }
                };
            }

            if ($(node).hasClass("folder")) {
                // Delete the "delete" menu item
                delete items.deleteItem;
            }

            return items;
        }

        function setTopToolbarActionsAllowed(node) {
            var $treeview = $element.find('.br-treeview');

            if (node.li_attr['data-new'] == true) {
                setEnabled($element.find('#add-node'));
                createNewActionHandler($treeview);
            } else {
                setDisabled($element.find('#add-node'));
            }
            if (node.li_attr['data-edit'] == true) {
                setEnabled($element.find('#edit-node'));
                createEditActionHandler($treeview);
            } else {
                setDisabled($element.find('#edit-node'));
            }
            if (node.li_attr['data-delete'] == true) {
                setEnabled($element.find('#remove-node'));
                createDeleteActionHandler($treeview);
            } else {
                setDisabled($element.find('#remove-node'));
            }
        }

        function setDisabled(node) {
            node.unbind('click');
            node.css('cursor', 'no-drop');
            node.css('opacity', '0.65');
        }

        function setEnabled(node) {
            node.unbind('click');
            node.css('cursor', '');
            node.css('opacity', '');
        }

        /**
         * pobiera listę plików aktualnego katalogu
         * @param node
         */
        function getDirFiles(id) {
            $filesBox = $element.find('.br-files ul');
            //$filesBox = $('.files-list ul');
            if ($filesBox)
                $filesBox.empty();

            var _data = {
                id: id
            };

            if (plugin.settings.sort) {
                var _sortBtn = $element.find('.sort-buttons').find('.sort_button.active');
                var _sortBtnClass = _sortBtn.attr('class').split(' ');
                _data.sn = _sortBtnClass.shift();
                _data.sd = _sortBtnClass.reverse().shift();

            }

            if(plugin.settings.dirsType === 'Zasoby'){
                $.ajax({
                    type: 'POST',
                    url: plugin.settings.filesUrl,
                    data: _data,
                    success: function (data) {
                        var $fEmpty = $element.find('.br-files .f-empty');
                        $fEmpty.remove();
                        if (data.length) {
                            $(data).each(function (i, v) {
                                var $eee = createFileElement(v);
                                $filesBox.append($eee);
                            });
                            filterRun();
                        } else {
                            $filesBox.append('<div class="folder-is-empty f-empty alert alert-warning"><h4>Brak elementów</h4></div>');
                        }


                    }
                });
            }
        }

        /**
         * pobiera listę plików aktualnego katalogu
         * @param node
         */
        function getSearchedFiles(string) {
            $filesBox = $element.find('.br-files ul');
            if ($filesBox)
                $filesBox.empty();

            $.ajax({
                type: 'POST',
                url: plugin.settings.filesUrl,
                data: {string: string},
                success: function (data) {
                    var $fEmpty = $element.find('.br-files .f-empty');
                    $fEmpty.remove();
                    if (data.length) {
                        $(data).each(function (i, v) {
                            var $eee = createFileElement(v);
                            $filesBox.append($eee);
                        });
                    } else {
                        $filesBox.append('<div class="folder-is-empty f-empty alert alert-warning"><h4>Brak wyników wyszukiwania</h4></div>');
                    }
                    filterRun();
                }
            });
        }

        function clearMark() {
            //Zdjęcie znacznika
            $('.files-list li input:checkbox').each(function () {
                var _this = $(this);
                _this.prop('checked', false);
                _this.parent().addClass('hidden');
            });
        }

        /**
         * tworzy pojedyńczy element
         * @param data
         * @returns {*|HTMLElement}
         */
        function createFileElement(data) {

            if (plugin.settings.filePresentation == 'miniatures') {
                var FileCntnr = new FilesContainer();
                var fileImage = FileCntnr.fileImagePath(data);
                var fSize = FileCntnr.fileSize(data);
                var html = '<li data-type="' + data.TYPE + '" data-tags="' + data.TAGS + '" data-extension="' + data.EXTENSION + '" data-id="' + data.ID + '" data-name="' + data.NAME + '" data-container="' + data.FK_CONTAINER + '">' +
                    '<a>' +
                    '<img src="' + fileImage + '" class="filemanager-thumb" onerror="this.height=180;this.width=180;this.onerror=null;this.src=\'/app/img/filemanager/' + data.EXTENSION + '.png\';" alt="' + data.EXTRA + '">' +
                    '</a>' +
                    '<div class="tags">' +
                    '<span class="label-holder file-name"><span class="label label-info arrowed">' + data.NAME + '</span></span>' +
                    '<span class="label-holder"><span class="label label-danger">' + fSize + '</span></span>' +
                    '</div>' +
                    '<div class="tools tools-top in hidden">' +
                    '</div>' +
                    '</li>'
                ;

            } else if (plugin.settings.filePresentation == 'list') {
                var html =
                    '<li data-type="' + data.TYPE + '" data-LibraryResourceServicetags="' + data.TAGS + '" data-extension="' + data.EXTENSION + '" data-id="' + data.ID + '" data-name="' + data.NAME + '" data-container="' + data.FK_CONTAINER + '">' +
                    '<div class="checkbox element file-element"  >' +
                    '<label>' +
                    '<span class="lbl filename"> ' + data.NAME + '</span>' +
                    '</label>' +
                    '</div>' +
                    '</li>';
            }


            var $html = $(html);

            //zapis danych do obiektu
            $html.data('dbRow', data);

            if (plugin.settings.filesCheckable) {
                var $checkbox = $('<input type="checkbox" name="file-checked form-field-checkbox" class="ace" value="' + data.ID + '">');

                if (plugin.settings.filePresentation == 'miniatures') {

                    $html.find('div.tools').append($checkbox).append('<span class="lbl filename">&nbsp;</span>');
                } else if (plugin.settings.filePresentation == 'list') {

                    $html.find('label').prepend($checkbox);
                }

                if (typeof selectedElements[data.ID] != 'undefined') {
                    $checkbox.prop('checked', true);
                    $html.find('div.tools').removeClass('hidden');
                }

                if (plugin.settings.canGeneratePdf && FileCntnr.convertableToPdf.indexOf(data.EXTENSION) >= 0) {
                    $html.append($('<div/>', {'class': 'tools tools-bottom'}).append($('<a href="#" class="generate-pdf" title="Konwersja pliku do PDF"><i class="ace-icon fa fa-file-pdf-o"></i></a>')));
                }

                $html.click(function (e) {

                    if (!$(e.target).parent().hasClass('generate-pdf')) {
                        if (plugin.settings.onlyOneFile) {
                            // Wyczyszczenie tablicy zaznaczonych elementów
                            selectedElements = {};

                            clearMark();
                        }

                        $checkbox.prop('checked', !$checkbox.is(':checked'));
                        if ($checkbox.is(':checked')) {
                            $html.find('div.tools-top').removeClass('hidden');
                            selectedElements[data.ID] = data;
                        } else {
                            $html.find('div.tools-top').addClass('hidden');
                            delete selectedElements[data.ID];
                        }
                    } else {
                        e.preventDefault();
                        $.ajax({
                            type: 'POST',
                            url: FileCntnr.pdfUrl,
                            data: {id: data.ID},
                            success: function (data) {
                                if (data.status == 1) {
                                    getDirFiles(currentDir);
                                } else {
                                    alert('Nie udało się wygenerować pliku PDF');
                                }
                            }
                        });
                    }


                });
            } else {
                $html.unbind().click(function (e) {
                    e.preventDefault();
                    if ($(this).hasClass('selected')) {
                        selectedElements = {};
                        $(this).removeClass('selected');
                    } else {
                        $(this).parent().find('li').removeClass('selected');
                        $(this).addClass('selected');
                        selectedElements = {};
                        selectedElements[data.ID] = data;
                        var alttext = $('#tinymce-image-modal').find('input[name="alt"]').val(data.EXTRA);
                    }
                })
            }

            return $html;
        }

        /**
         * tworzy przełączniki filtrów typów oraz ich obsługę
         */
        function createFilters() {
            var $filtersBox = $element.find('.br-filters');
            var $filterElement = $(
                '<label>' +
                '<small class="green">' +
                '</small>' +
                '<input type="checkbox"  class="ace ace-switch ace-switch-4" id="show-miniatures">' +
                '<span class="lbl middle"></span>' +
                '</label>'
            );
            if (typeof plugin.settings.filterFormat != 'undefined') {
                $.each(plugin.settings.filterFormat, function (name, data) {
                    $filter = $filterElement.clone();
                    $filter.find('small').text(name);

                    if (Object.prototype.toString.call(data) === '[object Object]') {
                        var extensions = data.extensions;
                        if (data.active) {
                            $filter.find('input[type="checkbox"]').prop('checked', true);
                        }
                        if (data.disabled) {
                            $filter.find('input[type="checkbox"]').attr('disabled', 'disabled');
                        }
                    } else {
                        var extensions = data;
                    }

                    $filter.find('input[type="checkbox"]').change(function () {

                        if ($(this).is(':checked')) {
                            filteredFormats = filteredFormats.concat(extensions);
                        } else {

                            $.each(extensions, function (k, v) {

                                var kk = filteredFormats.indexOf(v);
                                if (kk > -1) {
                                    filteredFormats.splice(kk, 1);
                                }
                            });
                        }
                        filterRun();
                    });
                    $filter.find('input[type="checkbox"]').change();

                    $filtersBox.append($filter);
                });
            }
        }

        /**
         * wykonuje filtrowanie
         */
        function filterRun() {
            if (filteredFormats.length > 0) {

                $element.find('.br-files .files-list li').each(function () {
                    if (filteredFormats.inArray($(this).data('extension'))) {

                        $(this).removeClass('hidden');
                    } else {

                        $(this).addClass('hidden');
                    }

                });

                var $filteredEmpty = $element.find('.br-files .filtered-empty');
                //$filteredEmpty.remove();

                if ($element.find('.br-files .files-list li:not(.hidden)').length == 0
                    && $element.find('.br-files .files-list li').length > 0
                    && $element.find('.br-files .folder-is-empty').length == 0
                ) {
                    $element.find('.br-files').append('<div class="filtered-empty f-empty alert alert-warning"><h4>Brak elementów do wyświetlenia</h4></div>');
                }
            } else {
                $element.find('.br-files .files-list li').removeClass('hidden');
            }


        }

        /**
         * tworzy element wyszukiwarki
         */
        function createSearchContainer() {
            var $search = $(
                '<div class=\"row\">' +
                '<div class="col-xs-12">' +
                '<div class="input-group search-block">' +
                '<label class="sr-only" for="searchSectionTree">Wyszukaj sekcji</label><input type="text" class="form-control search-container" placeholder="Wyszukaj..." id="searchSectionTree">' +
                '<span class="input-group-btn"><button class="btn btn-purple btn-sm no-border search-container-start" type="button"><i class="ace-icon fa fa-search icon-on-right bigger-110"></i><span class="sr-only">Szukaj</span></button></span>' +
                '<span class="input-group-btn hidden reset-block"><button class="btn btn-red btn-sm no-border search-container-reset" type="button"><i class="ace-icon glyphicon glyphicon-remove icon-on-right bigger-110"></i><span class="sr-only">Wyczyść</span></button></span>' +
                '</div>' +
                '</div>' +
                '</div>'
            );

            if (plugin.settings.displayActions ===false){
                $search.find('.search-block').css('margin-left','8px');
            }

            $search.find('input.search-container').on('keypress', function (e) {
                if (e.which == 13) {
                    $search.find('.search-container-start').trigger('click');
                }
            });
            $search.find('.search-container-start').click(function () {
                searchContainerString = $search.find('.search-container').val();
                $element.find('.br-treeview').jstree('refresh');
                $element.find('.reset-block').removeClass('hidden');
            });

            $search.find('.search-container-reset').click(function () {
                searchContainerString = '';
                $search.find('.search-container').val('');
                $element.find('.br-treeview').jstree('refresh');
                $element.find('.reset-block').addClass('hidden');
            });

            $element.find('.br-search-container').parent().show();
            $element.find('.br-search-container').parent().css('padding-left', 0);
            $element.find('.br-search-container').append($search);
        }


        /**
         * tworzy wyszukiwarkę plików
         */
        function createSearchFiles() {
            var $search = $(
                '<div class=\"row\">' +
                '<div class="col-xs-6 col-lg-6">' +
                '<div class="input-group hidden search-block">' +
                '<input type="text" class="form-control search-query" name="search-files" placeholder="Wyszukaj pliki ...">' +
                '<span class="input-group-btn">' +
                '<button type="button" class="btn btn-purple btn-sm no-border search-files-start">' +
                'Szukaj' +
                '<i class="ace-icon fa fa-search icon-on-right"></i>' +
                '</button>' +
                '</span>' +
                '</div>' +
                '</div>' +
                '<div class="col-xs-6 col-lg-6">' +
                '<div class="widget-toolbar no-border">' +
                '<label><small class="green">Wyszukiwarka </small><input type="checkbox" class="ace ace-switch ace-switch-4 show-search btn-flat"><span class="lbl middle"></span></label>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '<div class="hr hr-1">'
            );

            $search.find('button.search-files-start').click(function () {
                var string = $search.find('input[name="search-files"]').val();
                getSearchedFiles(string);

            });
            $search.find('.show-search').change(function () {
                var $searchBlock = $search.find('.search-block');
                if ($(this).is(':checked')) {

                    $searchBlock.removeClass('hidden d-none');
                    $element.find('.disable-treeview').removeClass('hidden d-none')

                } else {
                    $searchBlock.addClass('hidden d-none');
                    $element.find('.disable-treeview').addClass('hidden d-none');
                    getDirFiles(currentDir);
                }
            });

            $element.find('.br-search-file').append($search);
        }

        /**
         * tworzy uploader plików
         */
        function createUpload() {
            var $upload = $(
                '<div style="display:none;">' +
                '<div style="min-height:200px; margin-bottom:10px; overflow: hidden;">' +
                '<form class="dropzone" id="dropzone-gallery">' +
                '<input name="container" id="' + plugin.settings.componentId + '-hidden-upload-container-id" type="hidden"/>' +
                '<div class="fallback">' +
                '<input name="file" type="file" multiple=""/>' +
                '</div>' +
                '</form>' +
                '</div>' +
                '</div>'
            );

            $element.find('.br-upload-file').append($upload);
            var $dropzone2 = $upload.find('form');
            Dropzone.autoDiscover = false;
            var myDropzone2 = $dropzone2.dropzone({
                paramName: "file",
                url: plugin.settings.uploadUrl,
                maxFilesize: typeof __resource_max_file_size != "undefined" ? __resource_max_file_size : 2000,
                autoProcessQueue: true,
                uploadMultiple: false,
                maxFiles: 100,
                parallelUploads: 100,
                dictDefaultMessage:
                    '<span class="bigger-150 bolder"><i class="ace-icon fa fa-caret-right red"></i> Przeciągnij</span> pliki aby załadować \
                    <span class="smaller-80 grey">(lub kliknij)</span> <br /> \
                    <span class="smaller-80 grey">aby dodać do zasobów</span> <br />\
                    <i class="upload-icon ace-icon fa fa-cloud-upload blue fa-3x"></i>'
                ,
                dictResponseError: 'Błąd podczas ładowania pliku!',
                previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n  <div class=\"dz-details\">\n    <div class=\"dz-filename\"><span data-dz-name></span></div>\n    <div class=\"dz-size\" data-dz-size></div>\n    <img data-dz-thumbnail />\n  </div>\n  <div class=\"progress progress-small progress-striped active\"><div class=\"progress-bar progress-bar-success\" data-dz-uploadprogress></div></div>\n  <div class=\"dz-success-mark\"><span></span></div>\n  <div class=\"dz-error-mark\"><span></span></div>\n  <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n</div>",
                init: function () {
                    var _this = this;
                    this.on('success', function (file, response) {
                        if (typeof response['virus'] !== 'undefined') {
                            alert('Plik ' + file.name + ' zawiera wirusy - ze względów bezpieczeństwa nie może zostać zapisany');
                            getDirFiles(currentDir);
                        }

                        getDirFiles(currentDir);
                    });
                },
                accept: function (file, done) {
                    /*var _done = plugin.settings.dropzoneAcceptCallback(file, done);
                    if (typeof _done == 'undefined'){
                        _done = done();
                    }
                    return _done;*/
                    plugin.settings.dropzoneAcceptCallback(file, done);
                }
            });

            var $checkbox = $(
                '<div class="widget-toolbar no-border" style="display: inline-block; padding-right: 0;">' +
                '<label>' +
                '<small class="green">Dodawanie plików </small>' +
                '<input type="checkbox" class="ace ace-switch ace-switch-4" id="show-file-uploader2" disabled>' +
                '<span class="lbl middle"></span>' +
                '</label>' +
                '</div>'
            );


            $checkbox.find('#show-file-uploader2').change(function () {
                if ($(this).prop('checked')) {
                    $upload.slideDown();
                } else {
                    $upload.slideUp();
                    getDirFiles(currentDir);
                    $dropzone2.dropzone().removeAllFiles();
                }
            });


            $element.find('.widget-header-flat .widget-toolbar > .br-filters').before($checkbox);

        }

        function createTabUploadBox() {
            if ($element.find('.resource-wrapper').length != 0) {
                $element.find('.resource-wrapper').parent().closest('.col-xs-12')
                    .wrap('<div class="tabbable col-xs-12 col-lg-12"/>')
                    .wrap('<div class="tab-content"/>')
                    .wrap('<div class="tab-pane" id="resources-tab"/>')
                    .wrap('<div class="row"/>')
                    .closest('.tabbable').prepend('<ul id="myTab" class="nav nav-tabs"><li class="active"><a href="#upload-tab" data-toggle="tab">Dodaj pliki</a></li><li class="hidden"><a href="#resources-tab" data-toggle="tab">Wybierz pliki</a></li></ul>')
                    .find('.tab-content').prepend('<div class="tab-pane active" id="upload-tab"><div style="min-height: 200px;"></div></div>')
                ;
            } else {
                $element.find('#tree-modal-container').append($('<div/>', {
                    id: 'upload-tab',
                    'class': 'row',
                    html: $('<div/>', {'class': 'col-xs-12 col-lg-12', style: 'min-height:200px'})
                }));
            }


            //$element.find('.resource-wrapper').removeClass('col-lg-9').addClass('col-lg-12');


            //DROPZONE
            var $dropzone = $(
                '<form class="dropzone" id="dropzone">' +
                '<div class="fallback">' +
                '<input name="file" type="file" multiple=""/>' +
                '</div>' +
                '</form>'
            );

            $.each(plugin.settings.dropzonePostParams, function (k, v) {
                $dropzone.prepend('<input type="hidden" name="' + k + '" value="' + v + '"/>');
            });

            $element.find('#upload-tab div').append($dropzone);

            let types = [];
            Object.values(plugin.settings.filterFormat).forEach(function (e) {
                if (e.extensions) {
                    e.extensions.forEach(function (f) {
                        types.push('.' + f);
                    })
                }
            });
            const myDropzone = $dropzone.dropzone({
                paramName: "file",
                url: plugin.settings.dropzoneUrl,
                maxFilesize: typeof __resource_max_file_size !== "undefined" ? __resource_max_file_size : 2000,
                autoProcessQueue: true,
                maxFiles: 100,
                parallelUploads: 100,
                acceptedFiles: types.length > 0 ? types.join(',') : null,
                dictDefaultMessage:
                    '<span class="bigger-150 bolder"><i class="ace-icon fa fa-caret-right red"></i> Przeciągnij</span> pliki aby załadować \
                    <span class="smaller-80 grey">(lub kliknij)</span> <br /> \
                    <i class="upload-icon ace-icon fa fa-cloud-upload blue fa-3x"></i>'
                ,
                dictResponseError: 'Error while uploading file!',
                previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n  <div class=\"dz-details\">\n    <div class=\"dz-filename\"><span data-dz-name></span></div>\n    <div class=\"dz-size\" data-dz-size></div>\n    <img data-dz-thumbnail />\n  </div>\n  <div class=\"progress progress-small progress-striped active\"><div class=\"progress-bar progress-bar-success\" data-dz-uploadprogress></div></div>\n  <div class=\"dz-success-mark\"><span></span></div>\n  <div class=\"dz-error-mark\"><span></span></div>\n  <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n</div>",
                init: function () {
                    const _this = this;
                    this.on('success', function (file, response) {
                        plugin.settings.dropzoneSuccessCallback(file, response);
                    });
                    this.on('error', function (file, response) {
                        plugin.settings.dropzoneErrorCallback(file, response);
                    });
                },
                accept: function (file, done) {
                    /*var _done = plugin.settings.dropzoneAcceptCallback(file, done);
                    console.debug(_done);
                    if (typeof _done == 'undefined'){
                        _done = done();
                    }
                    return _done;*/
                    plugin.settings.dropzoneAcceptCallback(file, done);
                }
            });

        }

        function createContainerEditModal() {
            $('#tree-modal-container').load("/app/js/bitresource2/html/editModal.html");

            const $treeview = $element.find('.br-treeview');

            // buttony drzewa
            createNewActionHandler($treeview);
            createEditActionHandler($treeview);
            createDeleteActionHandler($treeview);
            createMoveActionHandler($treeview);
        }

        function createNewActionHandler($treeview) {
            const $modal = $('#modal-wraper-edit-container');

            $element.find('#add-node').unbind('click').click(function () {
                let position = 'first';
                let parent = $treeview.jstree('get_selected');
                if(parent.length > 0){
                    let parentNodeId = $('#' + parent).data('id');
                    const newNode = {
                        'id': 'jstree-node-new',
                        'text': 'nowy_katalog',
                        'children': false,
                        'li_attr': {'data-id': 'new'}
                    };

                    getResourceFormRequest(null, parentNodeId);
                    $modal.find('.manage').click();
                    $modal.find('.move').hide();

                    $modal.on('hidden.bs.modal', function () {
                        // $jsTree.create_node(parent, newNode, position);
                        $modal.unbind();
                    });
                }else {
                    bootbox.alert('Proszę wybrać sekcję nadrzędną');
                }
            });
        }

        /**
         * Funkcja pobiera formularz edycji kontenera i osadza go w oknie modalnym
         *
         * @param id - Id kontenera
         * @param parentId
         */
        function getResourceFormRequest(id,parentId = null) {
            const modal = $('#modal-wraper-edit-container');

            $.ajax({
                type: 'GET',
                url: '/cms/admin-page/get-resource-form',
                data: {
                    id,
                    dirsType: plugin.settings.dirsType,
                    parentId
                },
                success: function (dataContainer) {

                    modal.find('#manage').html(dataContainer);
                    modal.modal('show');
                    modal.find('#save-container').unbind();
                    $(modal.find('#form-field-type')[0]).val(plugin.settings.dirsType === 'Zasoby' ? 2 : 1);
                    $('#save-container').click(function (e) {
                        e.preventDefault();
                        let dateFrom = $(modal.find('[name="dateFrom"]')).val();
                        let dateTo = $(modal.find('[name="dateTo"]')).val();

                        if (dateFrom && dateTo) {
                            if (Date.parse(dateFrom) < Date.parse(dateTo)) {
                                saveContainer();
                            } else {
                                $.flashMessenger('Data końcowa obowiązywania sekcji musi być późniejsza niż data początkowa', 'error');
                            }
                        } else {
                            saveContainer();
                        }
                    });
                    createMoveActionHandler($treeview);
                }
            });
        }

        function createEditActionHandler($treeview) {
            const $modal = $('#modal-wraper-edit-container');
            $element.find('#edit-node').unbind('click').click(function () {
                const current = $treeview.jstree('get_selected');
                const nodeId = $('#' + current).data('id');

                getResourceFormRequest(nodeId);
                $modal.find('.move').show();

                createTreeBox($('#jstree-move'), true);
            });
        }

        function createMoveActionHandler($treeview) {
            const moveTree = $('#jstree-move');
            $('#move-container').unbind().click(function () {
                const current = $('#' + $element.find('.br-treeview').jstree('get_selected')).data('id');
                const newParent = $('#' + moveTree.jstree('get_selected')).data('id');

                $.ajax({
                    type: 'GET',
                    url: '/cms/admin-section/move',
                    data: {
                        id: current,
                        containerId: newParent
                    },
                    success: function (response) {
                        $.flashMessenger('Pomyślnie zapisano', 'success');
                        $('#modal-wraper-edit-container').modal('hide');

                        $element.find('.br-treeview').jstree().rename_node(current, $('#container-form').find('[name="nameDisplay"]').val());
                        $element.find('.br-treeview').jstree(true).refresh();
                    }
                });
            });
        }

        function saveContainer() {
            const $treeview = $element.find('.br-treeview');
            const current = $('#' + $treeview.jstree('get_selected')).data('id');
            const formData = $('#container-form').serialize();
            const id = $('#container-form').find('input[name="id"]').val();
            const text = $('#container-form').find('input[name="nameDisplay"]').val();

            if (id !== '') {
                $.ajax({
                    type: 'POST',
                    url: '/resource/index/edit-folder',
                    data: formData + '&parent=' + current,
                    success: function (response) {
                        if (response.status === 1) {
                            $.flashMessenger('Pomyślnie zapisano', 'success');
                            $('#modal-wraper-edit-container').modal('hide');

                            $element.find('.br-treeview').jstree().rename_node(current, $('#container-form').find('[name="nameDisplay"]').val());
                        } else {
                            $.flashMessenger(response.message, 'warning');
                        }

                    }
                });
            } else {
                const newNode = {
                    'id': 'jstree-node-new',
                    'text': 'nowy_katalog',
                    'children': false,
                    'li_attr': {'data-id': 'new'}
                };
                $.ajax({
                    type: 'POST',
                    url: '/resource/index/add-folder',
                    data: formData + '&parent=' + current,
                    success: function (response) {
                        if (response.status === 1) {
                            $.flashMessenger(response.message, 'success');
                            $('#modal-wraper-edit-container').modal('hide');

                            newNode.li_attr['data-id'] = response.id;

                            $treeview.jstree('refresh');
                        } else {
                            $.flashMessenger(response.message, 'error');
                        }
                    }
                });
            }
        }

        function createDeleteActionHandler($treeview) {
            $element.find('#remove-node').unbind('click').click(function (e) {
                if (confirm('Czy na pewno chcesz usunąć katalog wraz z zawartością?')) {
                    const current = $treeview.jstree('get_selected');
                    const node = $treeview.jstree().get_node(current);

                    $treeview.jstree().delete_node(current);

                    $.ajax({
                        type: 'POST',
                        url: '/resource/index/remove-folder',
                        data: {'id': node.li_attr['data-id']},
                        success: (data, textStatus, jqXHR) => {
                            if (data.status === 1) {
                                $.flashMessenger('Pomyślnie usunięto sekcję', 'success');
                            } else {
                                $.flashMessenger('Nie udało się usunąć sekcji', 'errror');

                            }
                        }
                    });

                    e.preventDefault();
                }
            });
        }

        function createChangeListType() {
            const _container = $element.find('.br-list-type');
            const _label = $('<span/>').text('Miniatury');
            const _checkbox = $('<label>');

            _checkbox.append($('<input/>', {
                'class': 'ace ace-switch ace-switch-4',
                type: 'checkbox',
                name: 'br-list-type',
                value: 0,
                checked: true
            }));
            _checkbox.append($('<span/>', {'class': 'lbl'}));
            _checkbox.find('span').css('vertical-align', 'inherit');

            _container.append(_label);
            _container.append(_checkbox);

            _checkbox.on('change', 'input', function (e) {
                var _list = $element.find('.files-list');
                if ($(this).is(':checked')) {
                    _list.removeClass('list-mode');
                } else {
                    _list.addClass('list-mode');
                }
            });
        }

        function createSortOrder() {
            var _container = $element.find('.br-order');

            _container.addClass('sort-buttons').addClass('btn-group');

            _container.append($('<a/>', {
                'class': 'sort_1 sort_button active sorting_asc',
                href: '#',
                text: 'Nazwa'
            }));

            _container.append($('<a/>', {
                'class': 'sort_2 sort_button sorting',
                href: '#',
                text: 'Data dodania'
            }));

            _container.append($('<a/>', {
                'class': 'sort_3 sort_button sorting',
                href: '#',
                text: 'Rozmiar'
            }));

            _container.append($('<a/>', {
                'class': 'sort_4 sort_button sorting',
                href: '#',
                text: 'Autor'
            }));

            //filtr sortowania plików
            _container.on('click', '.sort_button', function (e) {
                e.preventDefault();
                var _this = $(this);

                $element.find('.sort-buttons .sort_button').removeClass('active').addClass('sorting');

                _this.addClass('active').removeClass('sorting');

                if (_this.hasClass('sorting_asc')) {
                    _this.removeClass('sorting_asc').addClass('sorting_desc');
                } else {
                    if (_this.hasClass('sorting_desc')) {
                        _this.removeClass('sorting_desc').addClass('sorting_asc');
                    } else {
                        $element.find('.sort-buttons .sort_button').removeClass('sorting_asc sorting_desc').addClass('sorting');
                        _this.addClass('sorting_asc');
                    }
                }

                $('.jstree-clicked').last().trigger("click");
            });
        }

        function includeLibraries(callback) {
            var csss = plugin.settings.pathSource.css;
            $.each(csss, function (k, v) {
                if (0 == $('link[href="' + v + '"]').length) {
                    $('html head').append('<link media="screen" rel="stylesheet" type="text/css" href="' + v + '"/>');
                }
            });

            var jss = plugin.settings.pathSource.js;
            //$.each(jss, function (k, v) {
            //    if (0 == $('script[src="' + v + '"]').length) {
            //        console.log(v);
            //        $('html head').append('<script type="text/javascript" src="' + v + '"');
            //    }
            //});
            $.when(
                $.getScript(jss.bitFileContainer),
                $.getScript(jss.dropzoneJs),
                $.getScript(jss.jsTreeJs),
                $.Deferred(function (deferred) {
                    $(deferred.resolve);
                })
            ).done(callback);
        }


        //public methods

        plugin.getSelected = function () {
            return selectedElements;
        };

        //szalewski #4636

        /**
         * Funckja umożłiwia skasowanie wszystkich wybranych elementów
         */
        plugin.clearSelected = function () {
            selectedElements = {};
            clearMark();
        };

        plugin.getCurrentDir = function () {
            return currentDir;
        };

        /**
         * Pobiera dane o aktualnie zazanczonym katalogu
         * Uwaga!: Jeżeli aktywowana jest opcja wyświetlania stron w drzewie i zostanie zaznaczona strona to funkcja zwróci pusty obiekt
         * Do weryfikacji uzyj metody getCurrentTreeElementType()
         * @param successCallback
         * @param errorCallback
         */
        plugin.getCurrentDirData = function (successCallback, errorCallback) {
            let url = plugin.settings.containerInfoUrl;
            let id = currentDir;
            if (currentDirType === 'page') {
                url = plugin.settings.pageInfoUrl;
                id = currentDir.split('-')[1];
            }

            $.ajax({
                type: 'POST',
                url: url,
                data: {id: id},
                error: function (jqXHR) {
                    if (Object.prototype.toString.call(errorCallback) == "[object Function]") {
                        errorCallback(jqXHR);
                    }
                },
                success: function (_data) {
                    if (_data.status == 1) {
                        if (Object.prototype.toString.call(successCallback) == "[object Function]") {
                            successCallback(_data.data);
                        }
                    }
                }
            });
        };

        /**
         * Zwraca typ zaznaczonego elementu w drzewie
         * @returns string "container" | "page"
         */
        plugin.getCurrentTreeElementType = function () {
            return currentDirType;
        };

        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);

            includeLibraries(function () {
                createSkeleton();
                if (plugin.settings.displayActions) {
                    createContainerEditModal();
                }
                if (!plugin.settings.hideTree) {
                    createTreeBox($element.find('.br-treeview'), false);
                }
                createFilters();
                if (plugin.settings.searchContainers) {
                    createSearchContainer();
                }

                if (plugin.settings.searchFiles) {
                    createSearchFiles();
                }

                if (plugin.settings.upload) {
                    createUpload();
                }

                if (plugin.settings.dropzone) {
                    createTabUploadBox();
                }

                if (plugin.settings.sort) {
                    createSortOrder();
                }

                if (plugin.settings.changeListType) {
                    createChangeListType();
                }
            });
        };

        plugin.init();

    };

})(jQuery);