function upload(){
	
  var fixWidth = function(e, ui) {  
  	ui.children().each(function() {  
  		$(this).width($(this).width());
  	});
  	return ui;
  };
	
	if ($('.multiupload').length){
		document.documentElement.addEventListener('dragover', (event) => {
		  event.preventDefault();
		  $('.dragging-container').show();
		});
		
		$('.dragging-container').on('dragleave', (event) => {
		  $('.dragging-container').hide();
		});
		
		document.documentElement.addEventListener('drop', (event) => {
		  event.preventDefault();
		  $('.dragging-container').hide();
		  $('.multiupload').prop('files', event.dataTransfer.files);
		  
			$('input[name="filter"]').val(0);
			$('input[name="multi_update"]').val(1);
		});
	}
	
	if ($('.mediaupload.images').length){
		$('.upload-box.images').on('dragover', function(event) {
		  event.preventDefault();
		  $(this).addClass('active');
		});
		
		$('.upload-box.images').on('dragleave', function(event) {
		  $(this).removeClass('active');
		});
		
		$('.upload-box.images').on('drop', function(event) {
		  event.preventDefault();
		  $(this).removeClass('active');
		  $('.mediaupload.images').prop('files', event.originalEvent.dataTransfer.files);
		});
	}
	
	if ($('.mediaupload.files').length){
		$('.upload-box.files').on('dragover', function(event) {
		  event.preventDefault();
		  $(this).addClass('active');
		});
		
		$('.upload-box.files').on('dragleave', function(event) {
		  $(this).removeClass('active');
		});
		
		$('.upload-box.files').on('drop', function(event) {
		  event.preventDefault();
		  $(this).removeClass('active');
		  $('.mediaupload.files').prop('files', event.originalEvent.dataTransfer.files);
		});
	}
	
	$('.image-upload').change(function(){
		if (this.files && this.files[0]) {
			var $id = $(this).attr('id');
			var reader = new FileReader();
			reader.onload = function (e) {
				$('label[data-id="'+$id+'"]').css('background-image', 'url('+e.target.result+')');
			}
			reader.readAsDataURL(this.files[0]);
		}
	});
	
	$('.multiupload-trigger').on('click', function(event){
		event.preventDefault();
		$('.multiupload').trigger('click');
	});		
	
	$('.multiupload').change(function(){
		if (this.files && this.files[0]) {
			$('input[name="filter"]').val(0);
			$('input[name="multi_update"]').val(1);
		} else {
			$('input[name="filter"]').val(1);
			$('input[name="multi_update"]').val(0);
		}
	});
	
  $('.multiupload').fileupload({
      url: $('form').attr('action').replace('index.php', 'ajax_form.php'),
      sequentialUploads: true,
      add: function (e, data) {
      	var $c_grid = $('form input[name="c_grid"]').val();
				var $template = $('#skeleton-box').contents();
      	var $container = null;
      	if ($c_grid == 1){
      		$container = $('.table-grid');
      	} else {
      		$container = $('.table-body');
      	}
      	$.each(data.files, function (index, file) {
    			var $templateClone = $template.clone();
	      	$templateClone.attr('data-filename', file.name.replace(/[^0-9a-zA-Z]/g, ""));
      		$container.append($templateClone);
		    });
		    data.submit();
      },
      done: function (e, data) {
      	var $c_grid = $('form input[name="c_grid"]').val();
      	$.each(data.files, function (index, file) {
      		var $result = $.parseJSON(data.result);
      		var $upload = $result.upload;
      		var checkbox = '<input id="c_check_'+$result.id+'" class="multicheck c_check_'+$result.id+'" value="1" type="checkbox" name="c_check['+$result.id+']">';
      		var $template = null;
      		if ($c_grid == 1){
	      		$template = $('.table-grid').find('[data-filename='+file.name.replace(/[^0-9a-zA-Z]/g, "")+']');
	      		if ($result.class == 'error') {
	      			$template.remove();
	      		} else {
	      			$template.find('.grid-title').html($upload.date+' - '+$upload.label+' - '+$upload.filesize);
	      			$template.find('.grid-content img').attr('src', $upload.dir+$upload.file);
	      			$template.find('.grid-content .skeleton').replaceWith($template.find('.grid-content img'));
		      		$template.removeAttr('data-filename');
		      		$template.attr('data-id', $result.id);
			      	$template.find('.multiselect').prepend(checkbox);
		      		$template.find('.caption').html($upload.file);
		      	}
      		} else {
	      		$template = $('.table-body').find('[data-filename='+file.name.replace(/[^0-9a-zA-Z]/g, "")+']');
	      		if ($result.class == 'error') {
	      			$template.remove();
	      		} else {
	      			$template.find('.table-cell.date').html($upload.date);
	      			if ($template.attr('data-module') == 'images'){
	      				$template.find('.table-cell.file .skeleton + .skeleton').replaceWith($upload.file);
	      				$template.find('.table-cell.file img').attr('src', $upload.dir+$upload.file);
	      				$template.find('.table-cell.file .skeleton').replaceWith($template.find('.table-cell.file img'));
	      			} else {
	      				$template.find('.table-cell.icon .skeleton').replaceWith($upload.file);
	      				$template.find('.table-cell.category').html($upload.category);
	      			}
	      			$template.find('.table-cell.filesize').html($upload.filesize);
	      			if ($upload.language) $template.find('.table-cell.language').html($upload.language);
	      			else $template.find('.table-cell.language').html('');
	      			$template.find('.toolbar .edit.hidden').attr('data-id', $result.id).removeClass('hidden');
	      			$template.find('.toolbar .delete.hidden').attr('data-id', $result.id).removeClass('hidden');
	      			
		      		$template.removeAttr('data-filename');
		      		$template.attr('data-id', $result.id);
			      	$template.find('.multiselect').html(checkbox);
			      }
      		}
      		
      	});
      },
      stop: function (e) {
				$('input[name="filter"]').val(1);
				$('input[name="multi_update"]').val(0);
				context_menu();
				filter();
				multi_check();
      }
  }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
  
	
	$('.mediaupload-trigger.images').on('click', function(event){
		event.preventDefault();
		$('.mediaupload.images').trigger('click');
	});	
	
  $('.mediaupload.images').fileupload({
	    url: 'ajax_form.php?module=images&backend_module=library',
      sequentialUploads: true,
      add: function (e, data) {
				var $template = $('#skeleton-box.images').contents();
      	var $container = $('.table-grid');
      	
	    	$('.form-action.remove-all').removeClass('hidden');
	    	$('.table-grid.sortable.images').removeClass('hidden');
      	$.each(data.files, function (index, file) {
    			var $templateClone = $template.clone();
	      	$templateClone.attr('data-filename', file.name.replace(/[^0-9a-zA-Z]/g, ""));
      		$container.append($templateClone);
		    });
		    data.submit();
      },
      done: function (e, data) {      	
      	$.each(data.files, function (index, file) {
      		var $result = $.parseJSON(data.result);
      		var $upload = $result.upload;
      		
      		if ($result.class == 'error') {
      			$('.table-grid.images').find('[data-filename='+file.name.replace(/[^0-9a-zA-Z]/g, "")+']').remove();
      		} else {
	      		var $insert = true;
	      		var $check = $result.id.replace('c_check_', '');
	      		if ($('.images-data').length){
		      		$('.images-data').each(function(){
		      			if ($(this).val() == $check) $insert = false;
		      		});
		      	}
		      	
		      	var $num = 1;
		      	if ($('.images-data').length) $num = $num + $('.images-data').length;
	      		
	      		if ($insert === true){
							$('<input type="hidden" name="images_data['+$check+'][id_media]" class="images-data" value="'+$check+'" />').insertBefore($('.mediaupload.images').parents('.form-row'));
							$('<input type="hidden" name="images_data['+$check+'][sortorder]" value="'+$num+'" />').insertBefore($('.mediaupload.images').parents('.form-row'));
							$('<input type="hidden" name="images_data['+$check+'][c_enlarge]" value="1" />').insertBefore($('.mediaupload.images').parents('.form-row'));
							
							
							$('.images-library').each(function() {
		            $('<input type="hidden" name="images_data_ph['+$check+']['+$(this).attr('name').split('[').pop().split(']')[0]+']" value="'+$(this).val()+'" />').insertBefore($('.mediaupload.images').parents('.form-row'));
			        });
	      		}
	      		
	      		var $template = $('.table-grid.images').find('[data-filename='+file.name.replace(/[^0-9a-zA-Z]/g, "")+']');
	    			$template.find('.grid-title').html('#'+$result.id);
	    			$template.find('.grid-content img').attr('src', $upload.dir+$upload.file);
	    			$template.find('.grid-content .skeleton').replaceWith($template.find('.grid-content img'));
	      		$template.attr('data-id', $result.id);
	      		$template.attr('id', $result.id);
	      		$template.find('.edit-media').attr('data-id', $result.id);
	      		$template.find('.remove-media').attr('data-id', $result.id);
	      		$template.find('.caption').html($upload.file);
	      		$template.removeAttr('data-filename');
	      	}
      	});
      },
      stop: function (e) {
      	context_menu();     
				upload();
        sortdata(fixWidth);
        mediacontrol();
      }
  })
  .prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled')
  .on('fileuploadsubmit', function (e, data) {
		data.formData = { "multi_update": "1" };
  	if ($('input[name=images_parent_guidv4]').length) {
      data.formData.parent_guidv4 = $('input[name=images_parent_guidv4]').val();
    } else if ($('input[name=parent_guidv4]').length) {
      data.formData.parent_guidv4 = $('input[name=parent_guidv4]').val();
    }
    
    if ($('input[name=session_module]').length) {
      data.formData.session_module = $('input[name=session_module]').val();
    }
    
    if ($('input[name=csrf_token]').length) {
      data.formData.csrf_token = $('input[name=csrf_token]').val();
    }
    
    $('.images-library').each(function () {
	    var $field = $(this);
	    var fieldName = $field.attr('name');
	    var fieldValue = $field.is(':checkbox, :radio') ? ($field.is(':checked') ? $field.val() : null) : $field.val();
	
	    if (fieldValue !== null) {
	    	data.formData[fieldName] = fieldValue;
	    }
    });
    
	});
	
	$('.mediaupload-trigger.files').on('click', function(event){
		event.preventDefault();
		$('.mediaupload.files').trigger('click');
	});	
	
  $('.mediaupload.files').fileupload({
	    url: 'ajax_form.php?module=files&backend_module=library',
      sequentialUploads: true,
      add: function (e, data) {
				var $template = $('#skeleton-box.files').contents();
      	var $container = $('.table-body');
      	
	    	$('.form-action.remove-all').removeClass('hidden');
	    	$('.table.files').removeClass('hidden');
      	$.each(data.files, function (index, file) {
    			var $templateClone = $template.clone();
	      	$templateClone.attr('data-filename', file.name.replace(/[^0-9a-zA-Z]/g, ""));
      		$container.append($templateClone);
		    });
		    data.submit();
      },
      done: function (e, data) {      	
      	$.each(data.files, function (index, file) {
      		var $result = $.parseJSON(data.result);
      		var $upload = $result.upload;
      		
      		if ($result.class == 'error') {
      			$('.table.files').find('[data-filename='+file.name.replace(/[^0-9a-zA-Z]/g, "")+']').remove();
      		} else {
	      		var $insert = true;
	      		var $check = $result.id.replace('c_check_', '');
	      		if ($('.files-data').length){
		      		$('.files-data').each(function(){
		      			if ($(this).val() == $check) $insert = false;
		      		});
		      	}
		      	
		      	var $num = 1;
		      	if ($('.files-data').length) $num = $num + $('.files-data').length;
	      		
	      		if ($insert === true){
							$('<input type="hidden" name="files_data['+$check+'][id_media]" class="files-data" value="'+$check+'" />').insertBefore($('.mediaupload.files').parents('.form-row'));
							$('<input type="hidden" name="files_data['+$check+'][sortorder]" value="'+$num+'" />').insertBefore($('.mediaupload.files').parents('.form-row'));
	      		}
	      		
	      		var $template = $('.table.files').find('[data-filename='+file.name.replace(/[^0-9a-zA-Z]/g, "")+']');
	    			$template.find('.sortorder').html('#'+$num);
	      		$template.attr('data-id', $result.id);
	      		$template.attr('id', $result.id);
    				$template.find('.table-cell.icon .skeleton').replaceWith($upload.file);
    				$template.find('.table-cell.category').html($upload.category);
	      		$template.find('.edit-media').attr('data-id', $result.id);
	      		$template.find('.remove-media').attr('data-id', $result.id);
	      		$template.removeAttr('data-filename');
	      	}
      	});
      },
      stop: function (e) {
      	context_menu();     
				upload();
        sortdata(fixWidth);
        mediacontrol();
      }
  })
  .prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled')
  .on('fileuploadsubmit', function (e, data) {
		data.formData = { "multi_update": "1" };
  	if ($('input[name=files_parent_guidv4]').length) {
      data.formData.parent_guidv4 = $('input[name=files_parent_guidv4]').val();
    } else if ($('input[name=parent_guidv4]').length) {
      data.formData.parent_guidv4 = $('input[name=parent_guidv4]').val();
    }
    
    if ($('input[name=session_module]').length) {
      data.formData.session_module = $('input[name=session_module]').val();
    }
    
    if ($('input[name=csrf_token]').length) {
      data.formData.csrf_token = $('input[name=csrf_token]').val();
    }
    
    $('.files-library').each(function () {
	    var $field = $(this);
	    var fieldName = $field.attr('name');
	    var fieldValue = $field.is(':checkbox, :radio') ? ($field.is(':checked') ? $field.val() : null) : $field.val();
	
	    if (fieldValue !== null) {
	    	data.formData[fieldName] = fieldValue;
	    }
    });
    
	});
}