var multiuploadReloadAfterUpload = false;
var multiuploadFolderPlaceholders = {};


(function () {
	var form = document.getElementById('import-form');
	if (!form) return;
	
	form.addEventListener('submit', function (event) {
		if (form.dataset.submitting === '1') {
			event.preventDefault();
			return;
		}
		if (!form.checkValidity()) return;
		event.preventDefault();
		form.dataset.submitting = '1';
		var overlay = document.getElementById('import-busy');
		if (overlay) overlay.style.display = 'flex';
		var hiddenSubmit = document.createElement('input');
		hiddenSubmit.type = 'hidden';
		hiddenSubmit.name = 'submit';
		hiddenSubmit.value = '1';
		form.appendChild(hiddenSubmit);
		window.setTimeout(function () {
			HTMLFormElement.prototype.submit.call(form);
		}, 50);
	});
})();

function clearMultiuploadInput(){
	$('.multiupload, .mediaupload.images, .mediaupload.files').each(function(){
		this.value = '';
	});
	$('input[name="filter"]').val(1);
	$('input[name="multi_update"]').val(0);
}

function multiuploadPath(file){
	var path = file.upload_path || file.webkitRelativePath || file.relativePath || file.name;
	path = path.replace(/\\/g, '/').replace(/^\/+/, '');

	if (path.substr(-1) == '/' && file.name){
		path += file.name;
	}

	return path;
}

function multiuploadKey(file){
	return multiuploadPath(file).replace(/[^0-9a-zA-Z]/g, '');
}

function multiuploadIgnoredFile(file){
	var path = multiuploadPath(file);
	var name = path.split('/').pop();
	if (!name) return true;

	return (
		name == '.DS_Store' ||
		name == 'Thumbs.db' ||
		name == 'desktop.ini' ||
		name.substring(0, 2) == '._' ||
		path.indexOf('__MACOSX/') !== -1 ||
		path.indexOf('/__MACOSX/') !== -1
	);
}

function multiuploadTextKey(value){
	return $.trim(String(value || '').toLowerCase());
}

function multiuploadCurrentFolder(){
	var $current = $('.library-breadcrumb-item.current');
	if (!$current.length) return null;
	return $.trim($current.text());
}

function multiuploadFolder(file){
	var path = multiuploadPath(file);
	var parts = path.split('/');

	if (parts.length <= 1) return null;

	parts.pop();

	if (!parts.length) return null;

	var current = multiuploadCurrentFolder();

	if (
		current &&
		parts.length &&
		multiuploadTextKey(parts[0]) == multiuploadTextKey(current)
	){
		parts.shift();
	}

	if (!parts.length) return null;

	return parts[0];
}

function multiuploadFolderDataKey(folder){
	return String(folder || '').replace(/[^0-9a-zA-Z]/g, '');
}

function multiuploadReadEntries(reader, entries, callback){
	reader.readEntries(function(results){
		if (!results.length) callback(entries);
		else multiuploadReadEntries(reader, entries.concat(Array.prototype.slice.call(results)), callback);
	}, function(){
		callback(entries);
	});
}

function multiuploadTraverseEntry(entry, path, callback){
	path = path || '';

	if (entry.isFile){
		entry.file(function(file){
			file.upload_path = path + file.name;
			callback([file]);
		}, function(){
			callback([]);
		});
	} else if (entry.isDirectory){
		multiuploadReadEntries(entry.createReader(), [], function(entries){
			var files = [];
			var waiting = entries.length;

			if (!waiting) callback([]);

			$.each(entries, function(index, child){
				multiuploadTraverseEntry(child, path + entry.name + '/', function(childFiles){
					files = files.concat(childFiles);
					waiting--;
					if (!waiting) callback(files);
				});
			});
		});
	} else {
		callback([]);
	}
}

function multiuploadDropFiles(dataTransfer, callback){
	var items = dataTransfer.items;

	if (items && items.length){
		var files = [];
		var waiting = items.length;

		$.each(items, function(index, item){
			var entry = item.webkitGetAsEntry ? item.webkitGetAsEntry() : null;

			if (entry){
				multiuploadTraverseEntry(entry, '', function(entryFiles){
					files = files.concat(entryFiles);
					waiting--;
					if (!waiting) callback(files);
				});
			} else {
				var file = item.getAsFile ? item.getAsFile() : null;

				if (file){
					file.upload_path = file.name;
					files.push(file);
				}

				waiting--;
				if (!waiting) callback(files);
			}
		});

		return;
	}

	callback(Array.prototype.slice.call(dataTransfer.files || []));
}

function upload(){
	
  var fixWidth = function(e, ui) {  
  	ui.children().each(function() {  
  		$(this).width($(this).width());
  	});
  	return ui;
  };
	
	if ($('.multiupload').length){
		$(document.documentElement).off('dragover.multiupload').on('dragover.multiupload', function(event){
			event.preventDefault();
			$('.dragging-container').show();
		});
		
		$('.dragging-container').off('dragleave.multiupload').on('dragleave.multiupload', function(event){
			$('.dragging-container').hide();
		});
				
		$(document.documentElement).off('drop.multiupload').on('drop.multiupload', function(event){
			event.preventDefault();
			$('.dragging-container').hide();
		
			multiuploadDropFiles(event.originalEvent.dataTransfer, function(files){
				files = $.grep(files, function(file){
					return !multiuploadIgnoredFile(file);
				});
		
				if (!files.length) return;
		
				files.sort(function(a, b){
					return multiuploadPath(a).localeCompare(multiuploadPath(b));
				});
		
				$('input[name="filter"]').val(0);
				$('input[name="multi_update"]').val(1);
		
				$('.multiupload').fileupload('add', {files: files});
			});
		});
	}
	
	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,
      dropZone: null,
			pasteZone: null,
      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');
      	}
      	data.files = $.grep(data.files, function(file){
					return !multiuploadIgnoredFile(file);
				});
				
				if (!data.files.length) return;
				
				
				$.each(data.files, function (index, file) {
					var folder = multiuploadFolder(file);
				
					if (folder){
						var key = multiuploadFolderDataKey(folder);

						if (!multiuploadFolderPlaceholders[key]){
							multiuploadFolderPlaceholders[key] = true;
						
							var $templateClone = $template.clone();
							$templateClone.attr('data-filename', key);
							$templateClone.attr('data-folder-upload', '1');
						
							if ($c_grid == 1){
								$templateClone.find('.caption').html(folder);
							} else {
								$templateClone.find('.table-cell.file .skeleton + .skeleton').replaceWith(folder);
							}
						
							$container.append($templateClone);
						}
					
						multiuploadReloadAfterUpload = true;
					} else {
						var $templateClone = $template.clone();
						$templateClone.attr('data-filename', multiuploadKey(file));
						$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);
			
					if (multiuploadFolder(file)){
						return true;
					}
			
					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='+multiuploadKey(file)+']');
	      		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='+multiuploadKey(file)+']');
	      		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) {
				var reload = multiuploadReloadAfterUpload;
				clearMultiuploadInput();
				context_menu();
				multi_check();

				multiuploadFolderPlaceholders = {};
			
				if (reload){
					multiuploadReloadAfterUpload = false;
					$("button[type='submit']").val('reload');
					$("button[type='submit']").click();
				}
      }
  })
  .prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled')
	.on('fileuploadsubmit', function (e, data) {
		var formData = $('form').serializeArray();
	
		formData.push({name: 'filter', value: '0'});
		formData.push({name: 'multi_update', value: '1'});
	
		if (data.files && data.files.length) {
			$.each(data.files, function(index, file){
				formData.push({
					name: 'upload_path['+index+']',
					value: multiuploadPath(file)
				});
			});
		}
	
		data.formData = formData;
	});
  
	
	$('.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', multiuploadKey(file));
      		$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='+multiuploadKey(file)+']').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='+multiuploadKey(file)+']');
	    			$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) {
				clearMultiuploadInput();
      	context_menu();     
        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', multiuploadKey(file));
      		$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='+multiuploadKey(file)+']').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='+multiuploadKey(file)+']');
	    			$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) {
				clearMultiuploadInput();
      	context_menu();     
        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;
	    }
    });
    
	});
}