var AssetsHelper = (function () {

    // Remove of list elements
    var bindRemove = function () {
        //$('a.cs-asset [data-action="remove"]').off().on('click', function (e) {
        //    e.preventDefault();
        //    var holder = $(this).parents('.cs-asset');
        //    var type = holder.data('content-type');
        //    var id = holder.data('id-content');
        //    var deleteUrl = Routing.generate('designer_assets_delete');
        //

        //
        //    $.ajax({
        //        url: deleteUrl,
        //        method: 'POST',
        //        data: {
        //            'ids': id
        //        },
        //        error: function () {
        //            //window.bootstrap.modal.show(
        //            //    Translator.trans("cs_core.messages.deleting_error"),
        //            //    Translator.trans("cs_core.messages.deleting_error"),
        //            //    Translator.trans("cs_core.action.accept"));
        //        },
        //        success: function (data) {
        //
        //            if (data.status != 200) {
        //                //window.bootstrap.modal.show(
        //                //    Translator.trans("cs_core.messages.deleting_error"),
        //                //    Translator.trans("cs_core.messages.deleting_error"),
        //                //    Translator.trans("cs_core.action.accept"));
        //                return;
        //            }
        //
        //            holder.fadeOut(500, function () {
        //                holder.remove();
        //            });
        //
        //            showToastrNotification('success',
        //                Translator.transChoice('cs_assets.messages.image.success_deleted', 1));
        //        }
        //    });
        //
        //});
    };

    return {
        //main function to initiate the module
        init: function () {

            bindRemove();

            AssetsHelper.currentType = $('.nav-tabs .active a').data('type');
            var searchForm = $('.cs_assets form.form-search-list');
            searchForm.attr('action', Routing.generate('admin_assets_search', {type: AssetsHelper.currentType}));

            // For global index
            $('.cs_assets a[data-toggle="tab"][data-load="ajax"]').on('load.bs.tab', function (e) {

                contentSelected.reset();
                contentSelected.setTotalItems();

                AssetsHelper.currentType = $(e.target).data('type');

                var targetTab = $($(e.target).attr('href'));
                var searchForm = $('.cs_assets form.form-search-list');
                var input = searchForm.find('input.ajax-search');

                searchForm.attr('action', Routing.generate('admin_assets_search', {type: AssetsHelper.currentType}));

                input.data('container', '#' + targetTab.find('.pagination-container').attr('id'));

                //Pagination.onChange.dispatch();
                contentSelected.totalItems = targetTab.find('.pagination-container').data('total-items');

            });
            AssetsHelper.bindTitleInput();

            //contentSelected.init('.cs-asset',null, {
            //    'delete': Routing.generate('admin_assets_delete')
            //});

            //Pagination.onChange.dispatch();


        },
        loadById: function(widget, data, callback) {

            var _dropzone = AssetsHelper.getDropzone(widget.find('.dropzone'));
            var element   = $(AssetsHelper.buildTemplate(widget));

            if (typeof data === "object") {
                populate(data.id,data.src,data.title);
            } else {
                $.ajax({
                    url: Routing.generate('designer_ck_asset_fetch', { id: data}),
                    async:true,
                    method: 'post',
                    success: function(response) {

                        var src  = response.url;
                        var title = response.title;
                        var editUrl = response.editUrl;

                        populate(data, src, title, editUrl);
                    }
                });
            }

            function populate(id, src, title, editUrl) {
                if('image' != _dropzone.type) {
                    element.find('[data-dz-thumbnail]').attr('src', '/bundles/comitium5designer/layout/img/asset-' + _dropzone.type + '.gif');
                }

                _dropzone.elementContainer.append(element);
                element.find('[data-entity="title"]').val(title);
                element.data('id-content', id);


                element.attr('id', 'library-asset-' + id + '_selected');

                //element.attr('id', id + '_selected');
                element.attr('data-id-content', id);
                element.find('.asset-image').append("<img src='"+src+"'/>");

                //Add editable link
                // var editUrl = Routing.generate('admin_assets_edit', { id: id, ignoreReferer: 1, contentLocale: ComitiumUtils.getURLParameter("contentLocale") });
                element.find('[data-type="edit-link"]').attr('href', editUrl ).fadeIn('slow');
                //element.find('.btn-remove').fadeIn('slow');

                AssetsHelper.bindTitleInput(element, title);
                AssetsHelper.addSelected(_dropzone.element, id);

                element.find('[data-action="unselect"]').on("click", function(e){
                    e.preventDefault();

                    var _this = this;
                    var parent = $(this).closest('.asset-wrapper');
                    var parentId = parent.data('id-content');
                    var origObject = $('#library-asset-' + parentId);

                    AssetsHelper.removeSelected(widget.find('.dropzone'), parentId);

                    parent.slideUp(function () {
                        parent.remove();
                        AssetsHelper.signals.afterLibraryRemove.dispatch(origObject);
                    });
                });

                element.find('.opts >').fadeIn();

                if (typeof callback === "function") {
                    callback.call(this, widget, element);
                }
            }

        },
        // Function signals
        signals: {
            onWidgetInit: new signals.Signal(),
            onNewAdd: new signals.Signal(),
            onNewRemove: new signals.Signal(),
            onLibraryAdd: new signals.Signal(),
            onLibraryRemove: new signals.Signal(),
            onNewAfterRemove: new signals.Signal(),
            afterLibraryRemove: new signals.Signal(),
            onNewCreate: new signals.Signal()
        },
        // Function initForm
        initForm: function(form) {
            var $metadataInput = $('[name$="[metadata][embed]"]', form);
            $metadataInput.data('original', $metadataInput.val());
            var $metadataButton = $('.btn-apply', form);
            var $video = $('span.video', form);
            var $urlRegex = new RegExp(/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/)


                $metadataInput.on('keyup', function() {

                if($metadataInput.val() != $metadataInput.data('original')) {
                    $metadataButton
                        .removeClass('disabled')
                        .attr('disabled', false);
                }


                    $metadataButton.on('click', function(e) {
                        e.preventDefault();

                        var value = $metadataInput.val();

                        if(value.match($urlRegex)) {
                            $video.html($('<video id="asset_video" controls>' +
                            '<source src="' + value + '"  type="video/mp4"></source>' +
                            '</video>'));

                            window.formVideo = videojs('asset_video');

                        } else {
                            $video.html($.parseHTML(value));
                        }

                    })
            });



        },
        // Function initWidget
        initWidget: function (parent) {

            if (!parent) {
                parent = $('body');
            }

            FormDropzone.init(parent);

            $('.assets-widget', parent).each(function (i, e) {
                var widget = $(e);

                Pagination.onChange.add(function (container) {

                    if (typeof container != 'undefined' &&
                        container.hasClass('widget-library')) {
                        var widget = container.parents('.assets-widget:first');
                        AssetsHelper.bindLibrary(widget);
                    }
                    contentSelected.reset();
                });

                var $dropzone = widget.find('.dropzone');
                widget.data('dropzoneElement', $dropzone);

                _dropzone = AssetsHelper.getDropzone($dropzone);

                AssetsHelper.initLibrary(widget);
                AssetsHelper.initSearch(widget);


                AssetsHelper.signals.onWidgetInit.dispatch(widget);


                $('a[data-toggle="tab"][data-load="ajax"]', widget)
                    .off('load.bs.tab')
                    .on('load.bs.tab', function (e) {

                        AssetsHelper.bindLibrary(widget);
                    });

                $('.asset-add-external', widget).on('click', function(e) {
                    e.preventDefault();

                    var source = $('.asset-external-input', widget).val();

                    if (!source) {
                        return;
                    }

                    var _dropzone = AssetsHelper.getDropzone(widget.find('.dropzone'));

                    $.ajax({
                        url: Routing.generate('designer_assets_create_external'),
                        method: 'POST',
                        data: {
                            type:  _dropzone.type,
                            source: source
                        },
                        success: function(response) {
                            var element = $(DropzoneDefaults.previewTemplate);

                            if('image' != _dropzone.type) {
                                element.find('[data-dz-thumbnail]').attr('src', '/bundles/comitium5designer/layout/img/asset-' + _dropzone.type + '.gif');
                            }

                            _dropzone.elementContainer.append(element);
                            element.find('[data-entity="title"]').val(response.metadata.title);
                            element.attr('data-id-content', response.metadata.id);

                            element.attr('id', 'library-asset-' + response.metadata.id + '_selected');

                            //Add editable link
                            // var editUrl = Routing.generate('admin_assets_edit', { id: response.metadata.id, ignoreReferer: 1, contentLocale: ComitiumUtils.getURLParameter("contentLocale") });
                            var editUrl = "domain.com"
                            element.find('[data-type="edit-link"]').attr('href', editUrl ).fadeIn('slow');
                            element.find('.btn-remove').fadeIn('slow');


                            ErrorHandler.handle(response.status);

                            var titleInput = element.find('input[data-entity="title"]');
                            var title = '';

                            if(response.metadata.hasOwnProperty('title')) {
                                title = response.metadata.title;
                            }

                            if (widget.find('[data-upload-locale]').length > 1) {
                                $.each(widget.find('[data-upload-locale]'), function () {
                                    var option = AssetsHelper.createOptionFromDiv($(this), title);
                                    AssetsHelper.afterUploadLocaleCreation(title, $(this).attr("data-lang-code"), response.metadata.id);

                                    if ($(this).attr("data-lang-code") === $(this).attr("data-default")) {
                                        AssetsHelper.selectDefaultOptionAndSetTitle(option, titleInput);
                                    }

                                    element.find('select[data-lang-field-selector]').append(option);

                                    AssetsHelper.langChangeEvent(element);
                                });
                            } else {
                                var localeCode = widget.find('[data-lang-name]').attr("data-lang-code");
                                AssetsHelper.afterUploadLocaleCreation(title, localeCode, response.metadata.id);
                                titleInput.val(title);
                                titleInput.attr("data-title-locale", localeCode);
                                element.find('[data-lang-field-delete]').remove();
                            }

                            AssetsHelper.setLangBeforeChange(element);
                            AssetsHelper.bindTitleInput(element, title);
                            AssetsHelper.addSelected(_dropzone.element, response.metadata.id);
                            AssetsHelper.signals.onNewCreate.dispatch(response, _dropzone.element);
                            var $element = element;

                            element.find('.btn-remove').on("click", function(e) {
                                // Make sure the button click doesn't submit the form:
                                e.preventDefault();
                                e.stopPropagation();


                                AssetsHelper.signals.onNewRemove.dispatch(_dropzone.widgetContainer, $element);

                                $.ajax({
                                    url: Routing.generate('designer_assets_delete', { type: _dropzone.type }),
                                    method: 'POST',
                                    data: {
                                        'type': _dropzone.type,
                                        'ids': element.data('id-content'),
                                        'toast': 0
                                    },
                                    success: function(data) {

                                        if(data.status != 200) {
                                            return;
                                        }

                                        AssetsHelper.removeSelected(_dropzone.element, $element.data('id-content'));
                                        $element.slideUp(function(){
                                            $(this).remove();
                                        });
                                        _dropzone.checkContainer();
                                    }
                                });


                            });

                            element.find('.opts >').fadeIn();
                        }
                    });

                });


                // Selected asset remove
                $('.cs-selected-assets .asset-wrapper', widget).each(function (i, element) {

                    AssetsHelper.bindTitleInput(element);
                    AssetsHelper.langChangeEvent($(element));
                    AssetsHelper.setLangBeforeChange($(element));


                    $('[data-action="unselect"]', element).on('click', function (e) {
                        e.preventDefault();

                        var _this = this;
                        var parent = $(this).closest('.asset-wrapper');
                        var parentId = parent.data('id-content');
                        var origObject = $('#library-asset-' + parentId);



                        AssetsHelper.removeSelected(widget.find('.dropzone'), parentId);
                        //AssetsHelper.unselectLibraryElement(origObject, parent);

                        parent.slideUp(function () {
                            parent.remove();
                            AssetsHelper.signals.afterLibraryRemove.dispatch(origObject);
                        });
                    });
                });

            });
        },
        // Function initLibrary
        initLibrary: function (widget) {
            var selected = widget.data('selectedElements');

            if (typeof selected === 'undefined') {
                selected = [];

                if (widget.find('.dropzone').data('multiple')) {
                    $('[data-asset]', widget).each(function (i, e) {
                        selected.push(Number(AssetsHelper.valueParse($(e).val())));
                    });
                }

                widget.data('selectedElements', selected);
            }
        },
        // Function bindLibrary
        bindLibrary: function (widget) {


            widget.find('.tab-asset-library').removeClass('loading');
            AssetsHelper.updateLibrarySelection(widget);
            widget.find('.cs-library-asset').each(function (i, e) {
                var libraryElement = $(e);
                libraryElement.data('parent-widget', widget);
                AssetsHelper.initlibraryElement(widget, libraryElement);
            });
        },
        // Function updateLibrarySelection
        updateLibrarySelection: function (widget) {
            var library = $('.widget-asset-library', widget);
            var selectedElements = widget.data('selectedElements');

            $('.cs-library-asset', library).each(function (i, e) {
                var libraryAsset = $(e);
                var id = libraryAsset.data('id-content');
                if (selectedElements.indexOf(id) != -1) {

                    libraryAsset.addClass('selected');
                } else {

                    libraryAsset.removeClass('selected');
                }
            });
        },
        // Function initlibraryElement
        initlibraryElement: function (widget, libraryElement) {

            var selected = widget.data('selectedElements');
            var identifier = libraryElement.data('id-content');

            if (selected.indexOf(identifier) != -1) {
                libraryElement.addClass('selected');
                libraryElement.data('selected', true);
                //AssetsHelper.selectLibraryElement(libraryElement);
            } else {
                libraryElement.data('selected', false);
            }

            libraryElement.off('click').on('click', AssetsHelper.handleSelectLibraryElement);
        },
        handleSelectLibraryElement: function (e) {

            var origObject = $(this);
            var widget = origObject.data('parent-widget');

            var destObject = $(AssetsHelper.buildTemplate(widget));

            var selectionContainer = widget.find('.cs-selected-assets');

            //SET EDIT URL TO DESTOBJECT
            // var editUrl = Routing.generate('admin_assets_edit', { id:origObject.data('id-content') , ignoreReferer: 1, contentLocale: ComitiumUtils.getURLParameter("contentLocale") });
            var editUrl = origObject.data("editUrl");
            destObject.find('[data-type="edit-link"]').attr('href', editUrl);

            if (origObject.data('selected')) {
                AssetsHelper.unselectLibraryElement(
                    origObject,
                    selectionContainer
                        .find('#' + origObject.attr('id') + '_selected'));
            } else {

                AssetsHelper.selectLibraryElement(
                    origObject,
                    destObject);
            }
        },
        // Function unselectLibraryElement
        unselectLibraryElement: function (origObject, destObject) {


            var parentWidget = origObject.data('parent-widget');
            var selected = parentWidget.data('selectedElements');
            var dropzone = parentWidget.find('.dropzone');

            AssetsHelper.removeSelected(dropzone, origObject.data('id-content'));
            origObject.data('selected', false);

            destObject.slideUp(function () {
                destObject.remove();
                origObject.removeClass('selected');
                AssetsHelper.signals.afterLibraryRemove.dispatch(destObject);
            });

            AssetsHelper.signals.onLibraryRemove.dispatch(parentWidget, origObject, destObject);
        },
        // Function selectLibraryElement
        selectLibraryElement: function (origObject, destObject) {
            var parentWidget = origObject.data('parent-widget');
            var selectionContainer = parentWidget.find('.cs-selected-assets');
            var selected = parentWidget.data('selectedElements');

            var id = origObject.data('id-content');

            origObject.data('selected', true);

            if (typeof destObject != 'undefined') {

                var dropzone = parentWidget.find('.dropzone');
                var input = destObject.find('[data-lang-field-container] input[data-entity="title"]');

                AssetsHelper.addSelected(dropzone, origObject.data('id-content'));

                origObject.addClass('selected');
                destObject.attr('id', origObject.attr('id') + '_selected');
                destObject.data('id-content', origObject.data('id-content'));
                destObject.attr('data-id-content', origObject.data('id-content'));
                destObject.attr('data-width', origObject.data('width'));
                destObject.attr('data-height', origObject.data('height'));
                destObject.find('.asset-image').append(origObject.find('.asset-image img').clone());


                if (origObject.find('[data-lang-name]').length > 1) {
                    $.each(origObject.find('[data-lang-name]'),function () {
                        var option = AssetsHelper.createOptionFromDiv($(this));

                        if ($(this).attr("data-lang-code") === $(this).attr("data-default")) {
                            AssetsHelper.selectDefaultOptionAndSetTitle(option, input);
                        }

                        destObject.find('select[data-lang-field-selector]').append(option);
                    });

                    AssetsHelper.langChangeEvent(destObject);
                } else {
                    input.val(origObject.find('[data-lang-name]').attr("data-lang-title"));
                    input.attr("data-title-locale", origObject.find('[data-lang-name]').attr("data-lang-code"));
                    destObject.find('[data-lang-field-delete]').remove();
                }


                if (parentWidget.data('insert') == 'append' || !parentWidget.data('insert')) {
                    selectionContainer.append(destObject);
                } else {
                    selectionContainer.prepend(destObject);
                }

                destObject.hide();
                destObject.slideDown();

                //AssetsHelper.bindUnselect(destObject);
                AssetsHelper.bindTitleInput(destObject, origObject.attr('data-title-content'));

                destObject.find('[data-action="unselect"]').on('click', function (e) {
                    e.preventDefault();
                    AssetsHelper.unselectLibraryElement(origObject, destObject);
                });
            }

            AssetsHelper.signals.onLibraryAdd.dispatch(parentWidget, origObject, destObject);

        },
        setLangBeforeChange: function (destObject) {
            var input = destObject.find('[data-lang-field-container] input[data-entity="title"]');
            var option = destObject.find("select[data-lang-field-selector] option:selected");
            input.val(option.attr("data-lang-title"));
            input.attr("data-title-locale", option.val());
        },
        createOptionFromDiv: function (element, title) {

            if (title === undefined) {
                title = element.attr("data-entity-title");
            }

            return $("<option/>", {
                'value': element.attr("data-lang-code"),
                'text': element.attr("data-lang-name"),
                'data-lang-title': title,
            });
        },
        selectDefaultOptionAndSetTitle: function (option, input) {
            option.prop("defaultSelected", true);
            input.val(option.attr("data-lang-title"));
            input.attr("data-title-locale", option.val());
        },
        langChangeEvent: function (destObject) {

            if($().selectpicker()) {
                destObject.find('select[data-lang-field-selector]').selectpicker('refresh');
            }

            destObject.find('select[data-lang-field-selector]').on("change", function () {
                var input = destObject.find('[data-lang-field-container] input[data-entity="title"]');
                var option = destObject.find("select[data-lang-field-selector] option:selected");
                input.val(option.attr("data-lang-title"));
                input.attr("data-title-locale", option.val());
            });
        },
        // Function addSelected
        addSelected: function (dropzone, id) {
            var _dropzone = AssetsHelper.getDropzone(dropzone);
            var widget = _dropzone.widgetContainer;


            AssetsHelper.push(widget, id); // Push to array container

            _dropzone.checkContainer();
        },
        // Removes an element from dropzone (from input and from array)
        removeSelected: function (dropzone, id) {
            var _dropzone = AssetsHelper.getDropzone(dropzone);
            var widget = _dropzone.widgetContainer;


            AssetsHelper.pop(widget, id); // Pop from array container

            _dropzone.checkContainer();
        },
        // Function getDropzone
        getDropzone: function (element) {
            return Dropzone.forElement($(element).get(0));
        },
        // Function initSearch
        initSearch: function (widget) {
            var input = $('.widget-search', widget);

            widget.on('keyup', '.widget-search',function () {
                var _this = $(this);
                clearTimeout(_this.data('launchSearch'));
                _this.data('launchSearch', setTimeout(function () {
                    var xhr = _this.data('request');

                    if(xhr) {
                        xhr.abort();

                    }

                    xhr = $.ajax({
                        url: _this.data('url'),
                        data: {
                            search: _this.val(),
                            type: AssetsHelper.getDropzone(widget.find('.dropzone')).type
                        },
                        success: function (data) {
                            widget.find('.pagination-container').replaceWith(data);
                            AssetsHelper.bindLibrary(widget);

                        }
                    });
                    _this.data('request', xhr);
                }, 250));
            });

        },
        // Function valueParse
        valueParse: function (value) {
            var matches = value.match(/\d+$/i);
            return matches === null ? false : value.match(/\d+$/i).pop();
        },
        // Function pop
        pop: function (widget, id) {
            var selectedElements = widget.data('selectedElements');

            if (selectedElements.indexOf(id) != -1) {
                selectedElements.splice(selectedElements.indexOf(id), 1);
            }

            widget.data('selectedElements', selectedElements);

            // Remove input[type="hidden"]
            var $input = AssetsHelper.findInputById(widget, id);
            $input.remove();
        },
        // Function push
        push: function (widget, id) {
            var selectedElements = widget.data('selectedElements');
            var _dropzone = AssetsHelper.getDropzone(widget.data('dropzoneElement'));
            selectedElements.push(id);
            widget.data('selectedElements', selectedElements);

            var input = _dropzone.inputContainer.find('input[type="hidden"][data-asset]');

            if (_dropzone.multiple || !(input.length)) {
                var prototype = $('<input>', {
                    'type': 'hidden',
                    'name': _dropzone.inputName,
                    'value': id,
                    'data-asset': ''
                });
                _dropzone.inputContainer.append(prototype);
            } else {
                input.val(id);
            }
        },
        // Function findInputById
        findInputById: function (widget, id) {
            var _dropzone = AssetsHelper.getDropzone($(widget).data('dropzoneElement'));
            return $(_.find($(_dropzone.inputContainer).find('input[data-asset]'), function (el) {
                return AssetsHelper.valueParse($(el).val()) == id;
            }));
        },
        afterUploadLocaleCreation: function(title, locale, idContent) {
            $.ajax({
                url: Routing.generate('designer_assets_set_title'),
                method: 'POST',
                data: {
                    'title': title,
                    'locale': locale,
                    'id': idContent
                },
                success: function (response) {
                    if (response.status != 200) {
                        return;
                    }
                }
            });
        },
        // Function bindTitleInput
        bindTitleInput: function (parent, text) {

            var destObj;

            if (typeof parent == 'undefined') {
                destObj = $('.asset-wrapper input[data-entity="title"]');
            } else {
                destObj = $('input[data-entity="title"]', parent);
            }

            if (typeof text != 'undefined') {
                destObj.val(text);
            }

            destObj.on('change', function () {

                var parent = $(this).parents('.asset-wrapper:first');

                var locale = $(this).attr('data-title-locale');

                var title = $(this).val();

                $.ajax({
                    url: Routing.generate('designer_assets_set_title'),
                    method: 'POST',
                    data: {
                        'title': title,
                        'locale': locale,
                        'id': parent.data('id-content')
                    },
                    success: function (response) {
                        if (response.status != 200) {
                            showToastrNotification('error', Translator.trans("cs_core.messages.generic_error"));
                            return;
                        }

                        var origObj = $('div.asset-wrapper[data-id-content="' + parent.data('id-content') + '"]');

                        origObj.each(function (i, elem) {
                            $(elem).find('[data-lang-code="' + locale + '"]').attr('data-entity-title', title);

                            var defaultLocale = $(elem).find('[data-default]').attr('data-default');

                            var selectedOption = $(elem).find('select[data-lang-field-selector] option:selected');

                            if(selectedOption.length > 0) {
                                selectedOption.attr("data-lang-title", title);
                            }

                            if (locale == defaultLocale) {
                                $(elem).attr('data-title-content', title);
                            }
                        });
                    }
                });

            });
        },
        // Function currentType
        currentType: null,
        // Function acceptedMimeTypes
        acceptedMimeTypes: {
            image: 'image/jpeg,image/jpg,image/png,image/gif',
            sound: 'audio/*',
            video: 'video/mp4',
            document: 'application/excel,' +
              'application/msword,' +
              'text/plain, text/html,' +
              'application/pdf,' +
              'application/epub+zip,' +
              'application/vnd.amazon.ebook,' +
              'application/x-mobipocket-ebook,' +
              'application/vnd.ms-excel,' +
              'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        },
        // Function remove
        remove: function (_dropzone, callback) {
            var type = _dropzone.type;
            var id = _dropzone.contentId;
            var url = Routing.generate('admin_assets_delete', {type: type});

            $.ajax({
                url: url,
                method: 'POST',
                data: {
                    'type': type,
                    'ids': id
                },
                success: function (data) {
                    if (data.status == 200) {
                        callback(data);
                        AssetsHelper.removeSelected(_dropzone.element, id);
                    }
                }
            });
        },
        // Function reset
        reset: function(parent) {
            $('.assets-widget', parent).each(function() {
                var widget = $(this);
                widget.data('selectedElements', []);
                widget.find('[data-toggle="tab"]:first').tab('show');
                var _dropzone = AssetsHelper.getDropzone(widget.data('dropzoneElement'));
                _dropzone.inputContainer.find('input[type="hidden"][data-asset]').remove();
                _dropzone.elementContainer.children().remove();
                _dropzone.checkContainer();
            });
        },
        // Function previewTemplate
        previewTemplate: '<div class="row asset-wrapper cs-selectable">\n' +
            '    <div class="image-inner">\n' +
            '        <div class="col-md-3 col-xs-4 image asset-image">\n' +
            '            <span class="opts">\n' +
            '                <a href="#" class="btn btn-icon-only btn-circle blue" target="_blank" data-type="edit-link"><i class="fa fa-pencil"></i></a>\n' +
            '                <a href="#" class="btn btn-icon-only btn-circle yellow-gold" data-action="unselect"><i class="fa fa-minus"></i></a>\n' +
            '            </span>\n' +
            '        </div>\n' +
            '        <div class="col-md-9 col-xs-8 image-info">\n' +
            '            <div class="form-group">\n' +
            '                <div class="input-group" data-lang-field-container>\n' +
            '                    <div class="input-group-btn" data-lang-field-delete>\n' +
            '                        <select id="search-order" class="bs-select form-control no-select2" data-style="clean" data-lang-field-selector>\n' +
            '                        </select>\n' +
            '                    </div>\n' +
            '                    <div class="input-icon asset-title">\n' +
            '                        <i class="fa fa-pencil"></i>\n' +
            '                        <input type="text" class="form-control" data-entity="title" data-seo-image="text" placeholder="Untitled" />\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '            <!--<div class="link">\n' +
            '            <i class="fa fa-link"></i>\n' +
            '            <a href="http://192.168.1.42/metronic/theme/templates/admin/form_editable.html" id="link" data-type="text" data-pk="1" data-original-title="Set link">Set link</a>\n' +
            '            </div>-->\n' +
            '        </div>\n' +
            '    </div>\n' +
            '</div>',
        buildTemplate: function(widget) {

            var multiple = widget.find('#_dropzone').attr('data-multiple');

            if (!multiple || multiple === 'false' || !widget.data('is_advanced')) {
                return $(this.previewTemplate);
            }

            var template = $(this.previewTemplate);
            var addon = '<div class="checkbox-list">\
                <div class="checker"><span class=""><input type="checkbox" data-action="select"></span></div></div>\
                <div class="clearfix"></div>\
                    <div class="input-group margin-top-10 portlet-sortable-empty gf-spinner">\
                        <input aria-required="true" class="form-control spinner-input input-small" type="text" data-action="position">\
                        <button type="button" class="btn spinner-up default">\
                            <i class="fa fa-angle-down"></i>\
                        </button><button type="button" class="btn spinner-down default">\
                        <i class="fa fa-angle-up"></i>\
                    </button>\
                </div>';

            template.find('.image-info').append(addon);

            return template;
        }
    }
})();

//$(window).load(function() {
//    $deleteAction.on('success', function(params) {
//        params.managed = true;
//        window.location = Routing.generate('admin_assets_index', { type: AssetsHelper.currentType });
//
//    });
//});

$(document).ready(function () {

    var parent = $('body.cs_assets');
    if (parent.length) {
        AssetsHelper.init();
        var form = $('.form', parent);
        if (form.length) {
            AssetsHelper.initForm(form);
        }
    }

    AssetsHelper.initWidget();
});
