
'use strict';
(function ($) {

	if (typeof $.fn.aqPostFormatMediaPopup != 'function') {
		$.fn.aqPostFormatMediaPopup = function (opts) {
			var $self = $(this),
				defaults = {
					parent   : '',
					title    : 'My Photos',
					button   : 'Sellect',
					multiple : true,
					imageSize: 'thumbnail',
					init     : function () {
					},
					select   : function () {
					}
				},
				options = $.extend(defaults, $self.data(), opts);

			var $insert = '';
			var AQPostFormatMediaPopup = {
				$el       : $self,
				options   : options,
				$button   : $('.kd-button', $self),
				$input    : $('.kd-media-value', $self),
				template  : '<li class="kd-image"><img src="" alt=""/><div class="kd-control-wrap"><i class="kd-edit dashicons dashicons-edit"></i><i class="kd-close dashicons dashicons-no-alt"></i></div></li>',
				$showImage: '',
				media     : null,
				init      : function () {
					var _this = this;

					_this.createHTML();
					_this.setMedia();
					_this.events();
				},
				createHTML: function () {
					var _this = this, $parent;

					if (_this.options.parent == '') {
						$parent = _this.$el;
					}
					else {
						if ($(_this.options.parent).length) {
							$parent = $(_this.options.parent)
						}
						else {
							$parent = _this.$el;
						}
					}
					if (!$('ul.list-kd-image-media', $parent).length) {
						$parent.prepend('<ul class="list-kd-image-media"></ul>');
					}
					_this.$showImage = $('.list-kd-image-media', $parent);
				},
				events    : function () {
					var _this = this;

					_this.$input.change(function () {
						var listID = [];
						_this.$showImage.children('.kd-image').each(function () {
							if ($(this).data('src')) {
								listID.push($(this).data('src'));
							}
						});
						listID = listID.join(',');
						_this.$input.val(listID);
					});
					if (_this.options.multiple) {
						_this.$showImage.sortable({
							//placeholder: 'kd-sort-placeholder',
							revert     : 200,
							containment: "parent",
							update     : function () {
								_this.$input.trigger('change');
							}
						});
					}

					_this.$button.on('click', function (event) {
						event.preventDefault();
						$insert = _this.$showImage;
						_this.media.open();
					});

					_this.$showImage.on('click', '.kd-edit', function (event) {
						event.preventDefault();
						$insert = $(this).closest('.kd-image');
						_this.media.open();
					});

					_this.$showImage.on('click', '.kd-close', function (event) {
						event.stopPropagation();
						event.preventDefault();
						$(this).closest('li').remove();
						_this.$input.trigger('change', {action: 'remove'});
					});
					_this.media.on('select', function () {
						var selection = _this.media.state().get('selection'),
							attachments = [];
						selection.each(function (attachment, id) {
							attachment = attachment.toJSON();
							var url = attachment.sizes && attachment.sizes[_this.options.imageSize] && attachment.sizes[_this.options.imageSize].url ? attachment.sizes[_this.options.imageSize].url : attachment.url,
								$image = $(_this.template).attr({
									'data-id': attachment.id,
									'data-src' : url
								});
							attachments.push(attachment);
							$('img', $image).attr('src', url);
							// Select in case multiple set is true
							if (_this.options.multiple) {

								// Add images
								if ($insert.hasClass('list-kd-image-media')) {
									$insert.append($image);
								}
								// Change image
								else {
									if (id === 0) {
										$insert.attr('data-id', attachment.id);
										$('img', $insert).attr('src', url);
									}
									else {
										$insert.after($image);
									}
								}
							}
							// Select in case multiple set is false
							else {
								_this.$showImage.empty().append($image);
							}
						});
						_this.$input.trigger('change', {attachments: attachments});
					});

				},
				setMedia  : function () {
					var _this = this;

					_this.media = wp.media({
						title   : options.title,
						button  : {
							text: options.button
						},
						multiple: options.multiple
					});
				}
			};

			return AQPostFormatMediaPopup.init();
		};
	}

	$(document).ready( function () {
		$('.kd-upload').each( function() {
			$(this).aqPostFormatMediaPopup();
		});
	});
})(jQuery);