;(function($, window, document, undefined) {

	$(window).on('load', function() {
		
	});
	
	
	$(document).ready(function() {
		
		if ($('.alert_box').length != 0){ setTimeout(function() { $('.alert_box').hide() }, 5000); }
		$('#login').focus();
		if ($('#update_parent').length != 0){
			if ($('#update_parent').val() && opener) {
				const form = opener.document.forms[0];
				const sendButton = form.querySelector('button.send, input.send');
			
				if (sendButton) {
					if (typeof form.submit === 'function') {
						form.submit();
					} else {
						HTMLFormElement.prototype.submit.call(form);
					}
				}
			}

		}
		
		
    var fixWidth = function(e, ui) {  
    	ui.children().each(function() {  
    		$(this).width($(this).width());
    	});
    	return ui;
    };
		
		defaults();
		toggle();
		
		quick_edit();
		context_menu();
		
		filter();
		filter_multi();
		upload();	
		multi_check();
		
		
		default_editor();
		richtext_editor();
		code_editor();
		
		sortdata(fixWidth);
		
		$('body').on('submit', 'form', function(){
			$(this).find('.images-suggestions').remove();
		});
		
		$('body').on('click', '.images-suggestions-toggle', function(event){
			event.preventDefault();
		
			var $button = $(this);
			var $wrap = $button.closest('.images-suggestions');
			var $grid = $wrap.find('.images-suggestions-grid');
		
			$grid.toggleClass('hidden');
		
			toggleButtonContent($button);
		
		});
		
		function imageSuggestionsControl($wrap){
			if ($wrap.find('.multicheck:checked').length){
				$wrap.find('.button.absolute').css('display', 'block');
				$wrap.find('.btn.select').css('display', 'inline-block');
			} else {
				$wrap.find('.button.absolute').hide();
			}
		}
		
		$('.images-suggestions').each(function(){
			imageSuggestionsControl($(this));
		});
		
		$('body').on('change', '.images-suggestions .multicheck', function(){
			imageSuggestionsControl($(this).closest('.images-suggestions'));
		});
		
		$('body').on('click', '.images-suggestions-grid .grid-box.multiselect', function(event){
			if ($(event.target).hasClass('multicheck')) return;
		
			event.preventDefault();
		
			var $checkbox = $(this).find('.multicheck');
		
			$checkbox.prop('checked', !$checkbox.prop('checked')).trigger('change');
		});
		
		$('body').on('click', '.images-suggestions-select', function(event){
			event.preventDefault();
		
			var form = $('form').first();
			var $wrap = $(this).closest('.images-suggestions');
			var $row = $('.upload-box.images').first();
		
			if (!$row.length) return;
		
			$wrap.find('.multicheck:checked').each(function(){
				var $insert = true;
				var $check = $(this).attr('id').replace('c_check_', '');
		
				if ($('.images-data').length){
					$('.images-data').each(function(){
						if ($(this).val() == $check) $insert = false;
					});
				}
		
				if ($insert === true){
					$('<input type="hidden" name="images_data['+$check+'][id_media]" class="images-data" value="'+$check+'" />').insertBefore($row);
					$('<input type="hidden" name="images_data['+$check+'][sortorder]" value="'+$('.images-data').length+'" />').insertBefore($row);
					$('<input type="hidden" name="images_data['+$check+'][c_enlarge]" value="1" />').insertBefore($row);
		
					$wrap.find('input[name^="ajax_data['+$check+']"]').each(function(){
						var $key = $(this).attr('name').replace('ajax_data['+$check+']', '');
						var $value = $(this).val();
		
						$('<input type="hidden" name="images_data['+$check+']'+$key+'" value="'+$value+'" />').insertBefore($row);
					});
				}
			});
		
			$wrap.remove();
		
			$.ajax({
				type: "POST",
				dataType: 'html',
				url: 'ajax_reload.php?module=images&backend_module=library&file=images',
				data: form.serialize() + '&reload_ajax=reload',
				success: function(data){
					$('#box_images').html(data);
		
					upload();
					sortdata(fixWidth);
					mediacontrol();
				}
			});
		});
		
		mediacontrol();
		
		$('.textarea-panel').each(function() {
      var $panel = $(this);
      var id = $panel.data('id');
      var def = $panel.data('default');

      if (!id || !def) return;

      switch (def) {
        case 'code':
        	$panel.find('.show_code-editor[data-id="'+id+'"]').trigger('click');
          break;
        case 'richtext':
          $panel.find('.show_richtext-editor[data-id="'+id+'"]').trigger('click');
          break;
        case 'default':
          $panel.find('.show_default-editor[data-id="'+id+'"]').trigger('click');
          break;
      }
    });
		
		
		$('[data-fancybox]').fancybox({
		  thumbs : {
		    autoStart : false
		  }
		});
		
		$('.label-date').click(function(event){
			event.preventDefault();
			var $dateID = $(this).attr('data-id');
			var d = new Date();
			var day = d.getDate();
			var month = d.getMonth()+1;
			var year = d.getFullYear();
			var output = year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
			$('#'+$dateID).val(output);
		});
		
		if ($('.container:not(.popup)').length != 0){
	  	$(window).scroll(function() {
	  		if($(window).scrollTop() + $(window).outerHeight() + 10 >= $(document).height()) {
  				var $this = $('.container:not(.popup) #sub_page');
	  			var $table = $this.closest('.table-body');
					if ($('.table + .table-grid').length > 0) $table = $this.closest('.table-grid');
					var $sub_page = $('#sub_page').val();
					var $module = $('.form-content').attr('data-module');
					var $backend_module = $('.form-content').attr('data-backend-module');
					$('#sub_page').remove();
					if ($sub_page && $module && $backend_module){
						var $url = 'ajax_filter.php?module='+$module+'&backend_module='+$backend_module+'&sub_page='+$sub_page;
						$.ajax({
							url: $url,
							type: 'GET',
							success: function(data) {
								var $data = $(data);
								$table.append($data);
								context_menu();
							}
						});
					}
		    }
		  });
		}
		
		
		if ($('.container.popup').length != 0){
	  	$(window).scroll(function() {
	  		if($(window).scrollTop() + $(window).outerHeight() + 10 >= $(document).height()) {
	  			if ($('.container .form:not(.hidden) .form-content .sub_page').length != 0){
	  				var $this = $('.container .form:not(.hidden) .form-content .sub_page');
		  			var $table = $this.closest('.table-body');
	  				var $sub_page = $this.val();
						var $module = $this.attr('data-module');
						var $backend_module = $this.attr('data-backend-module');
						var $file = $this.attr('data-file');
						var $id = $this.attr('data-id');
						$this.remove();
						if ($sub_page && $module && $backend_module && $file && $id){
							var $url = 'ajax_reload.php?module='+$module+'&backend_module='+$backend_module+'&sub_page='+$sub_page+'&file='+$file+'&id='+$id;
				      $.ajax({
								url: $url,
								type: 'GET',
								success: function(data) {
									var $data = $(data);
									if ($('#box_'+$file+' .table-grid').length > 0){
										$table.append($data);
									} else {
										$table.append($data);
									}
								}
							});
						}
	  			}
	  		}
	  	});
	  }
		
		
		
		$("body").on('click', ".chips li", function(event){
			event.preventDefault();
			if ($(this).parents('.chips').attr('data-id').length && $(this).attr('data-value')){
				insertIntoEditor($(this).parents('.chips').attr('data-id'), $(this).attr('data-value'));
			}
		});
		
		$('.change_folder').on('click', function (event){
			if (!$(event.target).parent('a').hasClass('edit') && !$(event.target).parent('a').hasClass('delete_level')){
				event.preventDefault();
				
				var $form = $(this).closest('form');
				if (!$form.length) $form = $('form').first();
		
				if (typeof clearMultiuploadInput === 'function') clearMultiuploadInput();
		
				$form.find('.parent_guidv4').remove();
		
				if ($(this).attr('data-folder')){
					$('<input type="hidden" name="parent_guidv4" class="parent_guidv4" id="parent_guidv4" value="'+$(this).attr('data-folder')+'" />').appendTo($form);
				}
		
				$form.find("button[type='submit']").val('reload');
				$form.find("button[type='submit']").trigger('click');
		  }
		});
		
		$('.multi_form select').on('change', function(){
			switch($(this).attr('name')){
				default:
					$('input[name="change['+$(this).attr('name')+']"]').val(1);
					break;
			}
		});
		
		$('.multi_form input').on('change', function(){
			switch($(this).attr('name')){
				case 'date':
					$('input[name="change[datetime]"]').val(1);
					break;
				default:
					$('input[name="change['+$(this).attr('name')+']"]').val(1);
					break;
			}
		});
		
		$('body').on('click', '.remove_ajax', function(event){
			event.preventDefault();
			$(this).parents('.form-sort-row').remove();
			$(this).parents('.form-row-group').remove();
			$(this).parents('.form-row').remove();
			
			$(this).parents('.ajax-form.sortable').sortable('refresh');
	    var data = $(this).parents('.ajax-form.sortable').sortable('toArray');
	    $.each(data, function (index, id) {
	    	var num = index+1;
	      	$('.ajax-form.sortable .form-row#'+id+' .sortorder').html(num);
	      	$('input[name="options_data['+id+'][sortorder]"]').val(num);
	    });
			var form = $("form")
			var $file = $(this).attr('data-file');
			var $url = 'ajax_reload.php?file='+$file;
			if ($(this).attr('data-module')) $url = $url+'&module='+$(this).attr('data-module');
			if ($(this).attr('data-backend-module')) $url = $url+'&backend_module='+$(this).attr('data-backend-module');
	  	$.ajax({
           type: "POST",
           dataType: 'html',
					 url: $url,
           data: form.serialize() + '&reload_ajax=reload',
           success: function(data){
              $('#box_'+$file).html(data);
           }
       });
		});
		
		
		$('body').on('click', '.append_ajax', function(event){
			event.preventDefault();
			var form = $("form")
			var $file = $(this).attr('data-file');
			var $url = 'ajax_reload.php?file='+$file;
			if ($(this).attr('data-module')) $url = $url+'&module='+$(this).attr('data-module');
			if ($(this).attr('data-backend-module')) $url = $url+'&backend_module='+$(this).attr('data-backend-module');
	  	$.ajax({
           type: "POST",
           dataType: 'html',
					 url: $url,
           data: form.serialize() + '&append_ajax=reload',
           success: function(data){
              $('#box_append_'+$file).append(data);
           }
       });
		});
		
		
		$('body').on('change', '.reload_ajax', function(event){
			var form = $("form")
			var $file = $(this).attr('data-file');
			var $url = 'ajax_reload.php?file='+$file;
			if ($(this).attr('data-module')) $url = $url+'&module='+$(this).attr('data-module');
			if ($(this).attr('data-backend-module')) $url = $url+'&backend_module='+$(this).attr('data-backend-module');
	  	$.ajax({
           type: "POST",
           dataType: 'html',
					 url: $url,
           data: form.serialize() + '&reload_ajax=reload',
           success: function(data){
              $('#box_'+$file).html(data);
              upload();
           }
       });
		});
		
		
		$("body").on('click', ".load", function(event){
			event.preventDefault();
			var $this = $(this);
			var $row = $this.closest('.table-row');
	    var $id = $(this).attr('data-id');
			var $module = $(this).attr('data-module');
		  var $backend_module = $(this).attr('data-backend-module');
		  var $tab = $(this).attr('data-tab');
		  
		  if ($row.next('.table-full').attr('data-id') != $tab){
		 		$row.next('.table-full').remove();
				var $url = 'ajax_reload.php?module='+$module+'&backend_module='+$backend_module+'&id='+$id+'&file='+$tab;
				$.ajax({
					url: $url,
					type: 'GET',
					success: function(data) {
						var $data = $(data);
						$data.insertAfter($row);
					}
				});
		 	} else {		 		
		 		$row.next('.table-full').remove();
		 	}
		  
		});
		
		$('body').on('click', '.edit-media', function(event) {
			event.preventDefault();
			var form = $("form")
			var $module = $(this).attr('data-module');
	    var $backend_module = $(this).attr('data-backend-module');
			var $file = $(this).attr('data-file');
			var $id = $(this).attr('data-id');
			$.fancybox.open({
				type: 'ajax',
				src: 'ajax.php?module='+$module+'&backend_module='+$backend_module+'&file='+$file+'&id='+$id,
				opts: {
					touch: false,
					afterLoad: function(instance, current){
						if ($file == 'images'){
							if ($('input[name^="images_data_ph['+$id+']"]').length){
								$('input[name^="images_data_ph['+$id+']"]').each(function(){
									var $key = $(this).attr('name').replace('images_data_ph['+$id+'][', '').replace(']', '');
									$('.fancybox-content .form-row').find('[name="'+$key+'"]').attr('placeholder', $(this).val());
								});
							}
							if ($('input[name^="images_data['+$id+']"]').length){
								$('input[name^="images_data['+$id+']"]').each(function(){
									var $key = $(this).attr('name').replace('images_data['+$id+'][', '').replace(']', '');
									if ($key.startsWith('c_') && $(this).val() == 1) $('.fancybox-content .form-row').find('[name="'+$key+'"]').prop('checked', true);
									else if ($key.startsWith('r_')) $('.fancybox-content .form-row').find('[name="'+$key+'"][value="'+$(this).val()+'"]').prop('checked', true);
									else $('.fancybox-content .form-row').find('[name="'+$key+'"]').val($(this).val());
								});
							}
						} else if ($file == 'files'){
							if ($('input[name^="files_data['+$id+']"]').length){
								$('input[name^="files_data['+$id+']"]').each(function(){
									var $key = $(this).attr('name').replace('files_data['+$id+'][', '').replace(']', '');
									if ($key.startsWith('c_') && $(this).val() == 1) $('.fancybox-content .form-row').find('[name="'+$key+'"]').prop('checked', true);
									else if ($key.startsWith('r_')) $('.fancybox-content .form-row').find('[name="'+$key+'"][value="'+$(this).val()+'"]').prop('checked', true);
									else $('.fancybox-content .form-row').find('[name="'+$key+'"]').val($(this).val());
								});
							}
						}
					},
					afterShow: function(instance, current){
						if ($file == 'images'){
							if ($('input[name^="images_data['+$id+']"]').length){
								$('input[name^="images_data['+$id+']"]').each(function(){
									var $key = $(this).attr('name').replace('images_data['+$id+'][', '').replace(']', '');
									if ($key.startsWith('c_') && $(this).val() == 1) $('.fancybox-content .form-row').find('[name="'+$key+'"]').prop('checked', true);
									else if ($key.startsWith('r_')) $('.fancybox-content .form-row').find('[name="'+$key+'"][value="'+$(this).val()+'"]').prop('checked', true);
									else $('.fancybox-content .form-row').find('[name="'+$key+'"]').val($(this).val());
								});
							}
						
							$('.save-image').click(function(event){
								event.preventDefault();
								$.each($(this).parents('form').serializeArray(), function(_, kv){
									if ($('input[name="images_data['+$id+']['+kv.name+']').length){
										$('input[name="images_data['+$id+']['+kv.name+']').val(kv.value);
									} else {
										$('<input type="hidden" name="images_data['+$id+']['+kv.name+']" value="'+kv.value+'" />').insertAfter($('input[name="images_data['+$id+'][id_media]'));
									}
								});
								if ($('input[name^="images_data['+$id+']"]').length){
									$('input[name^="images_data['+$id+']"]').each(function(){
										var $key = $(this).attr('name').replace('images_data['+$id+'][', '').replace(']', '');
										if ($key.startsWith('c_') && $('.fancybox-content .form-row').find('[name="'+$key+'"]').prop('checked')) $(this).val(1);
										else if ($key.startsWith('c_')) $(this).val(0);
									});
								}
								instance.close();
							});
						} else if ($file == 'files'){
							if ($('input[name^="files_data['+$id+']"]').length){
								$('input[name^="files_data['+$id+']"]').each(function(){
									var $key = $(this).attr('name').replace('files_data['+$id+'][', '').replace(']', '');
									if ($key.startsWith('c_') && $(this).val() == 1) $('.fancybox-content .form-row').find('[name="'+$key+'"]').prop('checked', true);
									else if ($key.startsWith('r_')) $('.fancybox-content .form-row').find('[name="'+$key+'"][value="'+$(this).val()+'"]').prop('checked', true);
									else $('.fancybox-content .form-row').find('[name="'+$key+'"]').val($(this).val());
								});
							}
						
							$('.save-file').click(function(event){
								event.preventDefault();
								$.each($(this).parents('form').serializeArray(), function(_, kv){
									if ($('input[name="files_data['+$id+']['+kv.name+']').length){
										$('input[name="files_data['+$id+']['+kv.name+']').val(kv.value);
									} else {
										$('<input type="hidden" name="files_data['+$id+']['+kv.name+']" value="'+kv.value+'" />').insertAfter($('input[name="files_data['+$id+'][id_media]'));
									}
								});
								if ($('input[name^="files_data['+$id+']"]').length){
									$('input[name^="files_data['+$id+']"]').each(function(){
										var $key = $(this).attr('name').replace('files_data['+$id+'][', '').replace(']', '');
										if ($key.startsWith('c_') && $('.fancybox-content .form-row').find('[name="'+$key+'"]').prop('checked')) $(this).val(1);
										else if ($key.startsWith('c_')) $(this).val(0);
									});
								}
								instance.close();
							});
						}
					}
				}
			});
			
		});    
    
    $('body').on('click', '.media-gallery', function(event) {
			event.preventDefault();
			var form = $("form")
			var $row = $(this).parents('.form-row');
			var $module = $(this).attr('data-module');
	    var $backend_module = $(this).attr('data-backend-module');
			var $file = $(this).attr('data-file');
			var $guidv4 = '';
			if ($(this).attr('data-guidv4')){
				$guidv4 = '&guidv4='+$(this).attr('data-guidv4');
			}
			var $session_module = '';
			if ($(this).attr('data-session-module')){
				$session_module = '&session_module='+$(this).attr('data-session-module');
			}
			$.fancybox.open({
				type: 'ajax',
				src: 'ajax.php?module='+$module+'&backend_module=library&file='+$file+$guidv4+$session_module,
				opts: {
					touch: false,
					afterShow: function(instance, current){
						
						multi_check();
						
						if ($module == 'images'){
							$('.btn.select').on('click', function(event){
								$('.multicheck:checked').each(function(){
				      		var $insert = true;
				      		var $check = $(this).attr('id').replace('c_check_', ''); 
				      		if ($('.images-data').length){
					      		$('.images-data').each(function(){
					      			if ($(this).val() == $check) $insert = false;
					      		});
					      	}
				      		if ($insert === true){
										$('<input type="hidden" name="images_data['+$check+'][id_media]" class="images-data" value="'+$check+'" />').insertBefore($row);
										$('<input type="hidden" name="images_data['+$check+'][sortorder]" value="'+$('.images-data').length+'" />').insertBefore($row);
										$('<input type="hidden" name="images_data['+$check+'][c_enlarge]" value="1" />').insertBefore($row);
										if ($('input[name^="ajax_data['+$check+']"]').length){
											$('input[name^="ajax_data['+$check+']"]').each(function(){
												var $key = $(this).attr('name').replace('ajax_data['+$check+']', '');
												var $value = $(this).val();
												$('<input type="hidden" name="images_data['+$check+']'+$key+'" value="'+$value+'" />').insertBefore($row);
											});
										}
									}
								});
								instance.close();
								
						  	$.ajax({
				           type: "POST",
				           dataType: 'html',
									 url: 'ajax_reload.php?module=images&backend_module='+$backend_module+'&file=images',
				           data: form.serialize() + '&reload_ajax=reload',
				           success: function(data){
				              $('#box_images').html(data);
											upload();
				              sortdata(fixWidth);
				              mediacontrol();
				           }
					       });
							});
						} else if ($module == 'files'){
							$('.btn.select').on('click', function(event){
								$('.multicheck:checked').each(function(){
				      		var $insert = true;
				      		var $check = $(this).attr('id').replace('c_check_', ''); 
				      		if ($('.files-data').length){
					      		$('.files-data').each(function(){
					      			if ($(this).val() == $check) $insert = false;
					      		});
					      	}
				      		if ($insert === true){
										$('<input type="hidden" name="files_data['+$check+'][id_media]" class="files-data" value="'+$check+'" />').insertBefore($row);
										$('<input type="hidden" name="files_data['+$check+'][sortorder]" value="'+$('.files-data').length+'" />').insertBefore($row);
										if ($('input[name^="ajax_data['+$check+']"]').length){
											$('input[name^="ajax_data['+$check+']"]').each(function(){
												var $key = $(this).attr('name').replace('ajax_data['+$check+']', '');
												var $value = $(this).val();
												$('<input type="hidden" name="files_data['+$check+']'+$key+'" value="'+$value+'" />').insertBefore($row);
											});
										}
									}
								});
								instance.close();
								
						  	$.ajax({
				           type: "POST",
				           dataType: 'html',
									 url: 'ajax_reload.php?module=files&backend_module='+$backend_module+'&file=files',
				           data: form.serialize() + '&reload_ajax=reload',
				           success: function(data){
				              $('#box_files').html(data);
											upload();
				              sortdata(fixWidth);
				              mediacontrol();
				           }
					       });
							});
						}
						
						$(".order").click(function(event){
							event.preventDefault();
							var $order = $("input[name='order']").val();
							var $lastorder = $("input[name='lastorder']").val();
							var $orderdir = $("input[name='orderdir']").val();
							if (($(this).attr('data-order') == $lastorder) || ($order != $lastorder)){
								if ($orderdir == 'ASC') $orderdir = 'DESC';
								else $orderdir = 'ASC';
							}
							$("input[name='orderdir']").val($orderdir);
							$("input[name='lastorder']").val($order);
							$("input[name='order']").val($(this).attr('data-order'));
							reload_page(this);
						});
						
						$('.fancybox-content .change_folder').on('click', function (event){
							if (!$('.multicheck:checked').length) {
								if (!$(event.target).parent('a').hasClass('edit') && !$(event.target).parent('a').hasClass('delete_level')){
									event.preventDefault();
									var $form = $(this).closest('form');
									if (!$form.length) $form = $('.fancybox-content form').first();
						
									if (typeof clearMultiuploadInput === 'function') clearMultiuploadInput();
						
									$form.find('.parent_guidv4').remove();
						
									if ($(this).attr('data-folder')){
										$('<input type="hidden" name="parent_guidv4" class="parent_guidv4" id="parent_guidv4" value="'+$(this).attr('data-folder')+'" />').appendTo($form);
									}
									reload_page(this);
							  }
							}
						});
							
						$(".fancybox-content .grid").click(function(event){
							event.preventDefault();
							$("input[name='c_grid']").val('1');
							reload_page(this);
						});
						
						$(".fancybox-content .list").click(function(event){
							event.preventDefault();
							$("input[name='c_grid']").val('0');
							reload_page(this);
						});
						
  					$(".fancybox-content button[type='submit']").on('click', function(event){
							event.preventDefault();
							reload_page(this);
						});
						
						$('.table-body, .table-grid').on('click', '.table-cell .grid-box.multiselect, .table-row', function (event){
							if (!$(event.target).hasClass('multicheck')) {
								event.preventDefault();
								var $checkbox = $(this).find('input[type=checkbox]');
								$checkbox.prop('checked', !$checkbox.prop('checked'));
								if ($('.multicheck:checked').length) {
									$('.multicheck_control').css('display', 'inline-block');
									$('.btn.select').css('display', 'inline-block');
								} else {
									$('.multicheck_control').hide();
									$('.btn.select').hide();
								}
							}
						});
						
						function reload_page($this){
							var $form = $($this).parents('form');
							var $data = $form.serializeArray();
							
							$data.push({name: 'csrf_token', value: document.querySelector('[data-csrf]')?.dataset.csrf });
							
							var currentUrl = $form.attr('action');
							var url = new URL(currentUrl, window.location.origin);
							url.searchParams.delete('guidv4');
							$form.attr('action', url.pathname+url.search);
							$.post($form.attr('action'), $data, function(data){
                instance.setContent(current, data);
                instance.update();
							});
						}
					}
				}
			});
    });
    	
	  
	});
	
})(jQuery, window, document);

function toggleButtonContent($button){

	var $icon = $button.find('i').first();
	var label_node = $icon[0].nextSibling;

	var current_icon = $.trim($icon.text());
	var current_label = $.trim(label_node.nodeValue);

	var new_icon = $button.attr('data-toggle-icon');
	var new_label = $button.attr('data-toggle-label');

	$icon.text(new_icon);
	label_node.nodeValue = new_label;

	$button.attr('data-toggle-icon', current_icon);
	$button.attr('data-toggle-label', current_label);
}

function mediacontrol(){
	$('.remove-all-media.images').click(function(event){
		event.preventDefault();
		var $sort = $('.table-grid.sortable.images');
		$('input[name^="images_data"]').remove();
		$('.table-grid.sortable.images .table-cell').remove();
		$sort.sortable('refresh');
  	$('.form-action.remove-all.images').addClass('hidden');
  	$sort.addClass('hidden');
	});
	
	$('.remove-media.images').click(function(event){
		event.preventDefault();
		var $sort = $('.table-grid.sortable.images');
		$('input[name^="images_data['+$(this).attr('data-id')+']"]').remove();
		$('.table-grid.sortable.images .table-cell[data-id='+$(this).attr('data-id')+']').remove();
		$sort.sortable('refresh');
    var data = $sort.sortable('toArray');
    $.each(data, function (index, id) {
    	var num = index+1;
    	$('input[name="images_data['+id+'][sortorder]"]').val(num);
    	$('.table-grid.images .table-cell[data-id='+id+'] .grid-title').html('#'+num);
    });
    if (!$('input[name^="images_data"]').length){
    	$('.form-action.remove-all.images').addClass('hidden');
    	$sort.addClass('hidden');
    }
	});
	$('.remove-all-media.files').click(function(event){
		event.preventDefault();
		var $sort = $('.table.files .table-body');
		$('input[name^="files_data"]').remove();
		$('.table.files .table-row').remove();
		$sort.sortable('refresh');
  	$('.form-action.remove-all.files').addClass('hidden');
  	$sort.addClass('hidden');
	});
	
	$('.remove-media.files').click(function(event){
		event.preventDefault();
		var $sort = $('.table.files .table-body');
		$('input[name^="files_data['+$(this).attr('data-id')+']"]').remove();
		$('.table.files .table-row[data-id='+$(this).attr('data-id')+']').remove();
		$sort.sortable('refresh');
    var data = $sort.sortable('toArray');
    $.each(data, function (index, id) {
    	var num = index+1;
    	$('input[name="files_data['+id+'][sortorder]"]').val(num);
    	$('.table.files .table-row[data-id='+id+'] .sortorder').html('#'+num);
    });
    if (!$('input[name^="files_data"]').length){
    	$('.form-action.remove-all.files').addClass('hidden');
    	$sort.addClass('hidden');
    }
	});
}
	
	
function sortdata(fixWidth){
  $(".ajax-form.sortable").sortable({
    items: '.form-sort-row',
    helper: fixWidth,
    placeholder: "form-sort-row",
    update: function (event, ui) {
      var data = $(this).sortable('toArray');
      $.each(data, function (index, id) {
      	var num = index+1;
      	$('.ajax-form.sortable .form-row#'+id+' .sortorder').html(num);
      	$('input[name="options_data['+id+'][sortorder]"]').val(num);
      });
  	}
  });
  $( ".ajax-form.sortable" ).disableSelection();
  
  function renumberImageGrid($grid){
    var data = $grid.sortable('toArray');
    $.each(data, function (index, id) {
      var num = index+1;
      $('input[name="images_data['+id+'][sortorder]"]').val(num);
      $grid.find('.table-cell[data-id="'+id+'"]').find('.grid-title').html('#'+num);
    });
  }

  $(".table-grid.sortable").sortable({
    items: '.table-cell',
    helper: fixWidth,
    placeholder: "table-cell",
    tolerance: 'pointer',
    cancel: 'a, button, input, select, textarea, label, .grid-action',
    update: function (event, ui) {
      renumberImageGrid($(this));
    },
    stop: function (event, ui) {
      renumberImageGrid($(this));
    }
  });
  $( ".table-grid.sortable" ).disableSelection();
  
  $(".table-body.sortable").sortable({
    items: '.table-row',
    helper: fixWidth,
    placeholder: "table-row",
    update: function (event, ui) {
      var data = $(this).sortable('toArray');
      $.each(data, function (index, id) {
      	var num = index+1;
      	$('input[name="files_data['+id+'][sortorder]"]').val(num);
      	$('.table.files .table-row[data-id='+id+'] .sortorder').html('#'+num);
      });
  	}
  });
  $( ".table-body.sortable" ).disableSelection();
}