;(function ($, undefined) {

    $(function () {

        $('.multi-img-container').each(function() {

            var container = $(this),
                container_ul = container.find('ul');

            /**
             * Function called on page load and on item insert
             * Tries to load the image from the given image path
             *
             * @param {DOMElement} el Item add/needs updating
             */
            var fnUpdateImgPreview = function (el) {
                var img_container = el.find('.js-img-container'),
                    thumb_url = img_container.attr('data-thumb-url'),
                    img_path = el.find('.js-img-path').val();

                img_container.html('');
                if (img_path === '') {
                    return;
                }

                var img = $('<img />').attr('src', thumb_url + '?bg=' + encodeURIComponent('#fff') + '&url=' + encodeURIComponent(img_path));
                img_container.append(img);
            };

            /**
             * Add new item
             *
             * @param {String} path Path of image
             */
            var fnAddImage = function (path) {
                var prototype = container_ul.attr('data-prototype'),
                    index = container_ul.data('index'),
                    n_item;

                // Create item from prototype and set img path
                n_item = $(prototype.replace(/__name__/g, index));
                n_item.find('.js-img-path').val(path);

                // Increase index
                container_ul.data('index', index + 1);

                // Update preview
                fnUpdateImgPreview(n_item);

                // Append to container
                container_ul.append(n_item);
            };

            /**
             * Save Order of items and save this in the corresponding field
             */
            var fnUpdateOrdering = function () {
                var cnt = 1;
                container_ul.find('>li').each(function () {
                    $(this).find('.js-img-order').val(cnt);
                    cnt++;
                });
            };

            // Set index
            container_ul.data('index', container_ul.find(' > li').length);

            // Update existing items with thumbnail
            $(container_ul).find(' > li').each(function () {
                fnUpdateImgPreview($(this));
            });

            // Make items sortable
            container_ul.sortable({
                items: "> li",
                forcePlaceholderSize: true,
                update: fnUpdateOrdering
            }).disableSelection();


            // Add event for removing items
            container_ul.on('click', '[data-action="remove-img"]', function () {
                $(this).parents('.multi-img-item').first().remove();
                fnUpdateOrdering();
            });

            // Add image
            container.find('[data-action="add-image"]').on('click', function () {
                var $this = $(this),
                        config = $this.attr('data-mediamanager-config'),
                        path = $this.attr('data-mediamanager-path');

                MediaManager.openMultiple(config, function (items) {
                    for (var x = 0; x < items.length; x++) {
                        fnAddImage(items[x].webpath);
                    }
                    fnUpdateOrdering();
                }, path);
            });


        });

        

    });



})(jQuery);