var wikiEditor;
var inEdition = false;

//CHARGEMENT DE LA PAGE
function init_plugin_wiki(){
	if($('#sideMenu').length) {
		$('#sideMenu').panelResize({
			minWidth : 300
		});
	}





	wiki_category_search(function(){
		var page = $.urlParam('page');
		var category = $.urlParam('category');

		if(page && page!=''){
			wiki_page_open(category,page);
		} else if(category && category!=''){
			wiki_category_open(category);
		} else{
			wiki_page_home();
		}

		$('#wiki-categories #categories').sortable({
			cursorAt: { top:15 },
			distance: 10,
			axis: "y",
			containment: "parent",
			update: function( event, ui ) {
				var sort = [];
				//tri d'une page au sein d'une catégorie
	      		$('#wiki-categories .category:visible').each(function(i,element){
	      			sort.push($(element).attr('data-id'));
	      		});
	      		$.action({
					action : 'wiki_category_sort',
					sort : sort
				});
			}
		});
	});

	window.onbeforeunload = function(){
		if(inEdition) return "Êtes-vous sûr de vouloir quitter la page sans sauvegarder ?";
	}

	//Champ recherche
	$('.wiki_search_item input').blur(function(){
		$('.wiki_search_item span').removeClass('hidden').animate({opacity: '1'}, 150);
		$(this).animate({opacity: '0'}, 150).addClass('hidden');
	}).keyup(function(e){
		if(e.keyCode != 13) return;
		wiki_search_item($(this));
	});

	//Smooth scrolling pour sommaire
	var editor = $('.module-wiki #editor');
	$('#wiki-summary').on('click', 'a[href^="#"]',function(e) {
		e.preventDefault();

	    var href = $.attr(this, 'href');
	    editor.animate({
	        scrollTop: $(href).offset().top
	    }, 500, function () {
	        window.location.hash = href;
	    });
	});



	//Night mode
	if($('#night-mode-check').prop('checked') == true)
		$('html.module-wiki').addClass('night-mode');

	wiki_document_upload();

	//Récuperation des images en presse papier et upload
	window.addEventListener("paste", function(event){
		var clipboardData = event.clipboardData || window.clipboardData;
	    if(clipboardData.getData('Text').length) return;

		if(event.clipboardData == false || event.clipboardData.items == undefined) return;
	    var items = event.clipboardData.items;
	    if(items.length == 0) return;

	    var ajaxData = new FormData();
	    for (var i = 0; i < items.length; i++) {
	        if (items[i].type.indexOf("image") == -1) continue;
	        var file = items[i].getAsFile();
			ajaxData.append('file', file);
	    }

	     $.ajax({
			url: 'action.php?action=wiki_file_upload',
			type: 'POST',
			data: ajaxData,
			dataType: 'json',
			cache: false,
			contentType: false,
			processData: false,
			complete: function (data) {},
			success: function (response) {
				if(response.error) return $.message('error',response.error,0);
					var value = wikiEditor.value();
					for(var k in response.rows){
						var file = response.rows[k];
						value += "\n"+file.tag;
					}
					wikiEditor.value(value);
			},
			error: function (data) {
				$.message('error',data);
			}
		});
	}, false);
}

function toggle_night_mode(element){
	var wikiPage = $('html.module-wiki');
	var data = {action: 'wiki_night_mode'};

	if(element.checked){
		data.nightmode = true;
		wikiPage.addClass('night-mode');
	} else {
		wikiPage.removeClass('night-mode');
	}
	$.action(data, function(r){});
}

function wiki_search_item(input){
	if(inEdition && !confirm('Êtes vous sûr de vouloir quitter la page sans sauvegarder ?')) return;
	var input = $(input);
	// if(!input.val().length) return
	$('.search-title').length ? $('.category-recent').html('') : $('#editor').html('');
	$('.wiki-preloader').addClass('show');
	$.action({
		action : 'wiki_page_search',
		term : input.val(),
	},function(r){
		$('.wiki-preloader').removeClass('show');
		$('#editor').html(r.content);
	});
}

//Suppression d'un tag liée à la recherche en cours
function wiki_tag_delete(element){
	var tag = $(element).closest('span.tag-item');
	// tag.remove();
	var searchInput = $('.wiki_search_item input');
	var tagKeyword = tag.text().trim();

	var keywords = searchInput.val();
	searchInput.val(keywords.replace(tagKeyword, '').trim());

	wiki_search_item(searchInput);
}

function wiki_change_url(category,page){
	var url = window.location.pathname+'?module=wiki';
	url = url.replace(/\/+/gi,'/');
	if(category) {
		url +='&category='+category;
		$('#wiki-categories .category').removeClass('category-open');
		$('#wiki-categories .category[data-category="'+category+'"]').addClass('category-open');
	}
	if(page){
		url += '&page='+page;
		$('#wiki-categories .page').removeClass('page-open');
		$('#wiki-categories .page[data-page="'+page+'"]').addClass('page-open');
	}
	url+= window.location.hash;
	window.history.replaceState(null, null, url);
}

//Enregistrement des configurations
function wiki_setting_save(){
	var data = {}
	data.action = 'wiki_setting_save';
	data.fields = $('#wiki-setting-form').toJson();
	data.logo = $('#wiki_logo')[0].files[0];

	$.action(data,function(r){
		$.message('success','Enregistré');
	});
}

//Suppression image générale application
function wiki_logo_delete(element){
	if(!confirm('Êtes-vous sûr de vouloir supprimer l\'image ?')) return;
	var imageComposer = $(element).parent().find("input[data-type='image']");

	$.action({
	    action: 'wiki_logo_delete'
	}, function(r){
	    imageComposer.wrap('<form>').closest('form').get(0).reset();
	    imageComposer.unwrap();
	    $(element).next('img').attr('src', $(imageComposer).attr('data-default-src'));
	    $(element).remove();
	    $.message('info', 'Image supprimée');
	});
}

/** COMMON **/
function wiki_modal_open(data,callback){
	var modal = $('#wiki-modal');
	if(modal.length==0){
		var modal = $('<div id="wiki-modal" class=""><i onclick="wiki_modal_close();" class="fa fa-times close-button"></i><div class="wiki-content"></div></div>');
		$('body').append(modal);
	}

	modal.find('.wiki-content').load('action.php?action='+data.action,data,function(){
		if(callback) callback();
		init_components('#wiki-modal');
		modal.addClass('wiki-modal-open');
	});
}

function wiki_search(){
	var search = $('.wiki_search_item');
	if($('input', search).is(':visible')) return;
	$('span', search).animate({opacity: '0'}, 100).addClass('hidden');
	$('input', search).val('').removeClass('hidden').animate({opacity: '1'}, 100).focus();
}

function wiki_modal_close(){
	$('#wiki-modal').removeClass('wiki-modal-open');
	$('body').removeClass('modal-open');
}

/** CATEGORY **/
function wiki_category_search(callback){
	$('#categories').fill({
		action:'wiki_category_search'
	},function(){
		if(callback!=null) callback();
	});
}

function wiki_category_edit(element,event){
	event.stopPropagation();
	var li = $(element).closest('li');

	wiki_modal_open({
		action : 'wiki_category_edit',
		id : li.attr('data-id')
	},function(){
		$('body').addClass('modal-open');
		$('#category-form #label').focus();
	});
}

function wiki_category_save(){
	var data = $('#category-form').toJson();
	$.action(data,function(r){
		$('body').removeClass('modal-open');
		wiki_category_search();
		wiki_modal_close();
		wiki_category_open(r.slug);
	});
}

function wiki_category_open(category,onlyTree,callback){

	if(inEdition && !confirm('Êtes vous sûr de vouloir quitter la page sans sauvegarder ?')) return;

	var tpl = $('#pageModel li').get(0).outerHTML;

	$.action({
		action : 'wiki_category_open',
		category : category
	},function(r){
		var line = $('#wiki-categories .category[data-category="'+category+'"]');
		$('#wiki-categories .category').removeClass('category-open').find('li').remove();
		line.addClass('category-open').removeClass('category-closed');

		$('#wiki-categories .category > ul').sortable({
			axis: "y",
			distance: 10,

			update: function( event, ui ) {
				var sort = [];
				//tri d'une page au sein d'une catégorie
	      		$('.page',this).each(function(i,element){
	      			sort.push($(element).attr('data-id'));
	      		});
	      		$.action({
					action : 'wiki_page_sort',
					sort : sort
				});
			}
		});

		$( "#wiki-categories .category" ).droppable({
		  classes: {
	        "ui-droppable-hover": "wiki-category-hover"
	      },
	      tolerance  : 'fit',
	      drop: function( event, ui ) {

	      	var category = $(this);
	      	var categorySlug= $(this).attr('data-category');
	      	var page = ui.draggable;

	      	if(isNaN(category.attr('data-id')) || isNaN(page.attr('data-id'))) return;

	      	//si on drop dans la catégorie dans laquelle la page est déja, on ne fait rien
	      	if(page.attr('data-category') == categorySlug) return;


	      	//Déplacement dans une autre catégorie
	      	$.action({
				action : 'wiki_page_move',
				category : category.attr('data-id'),
				page : page.attr('data-id'),
			},function(r){
				wiki_category_open(categorySlug,null,function(){
					$('[data-id="'+page.attr('data-id')+'"]',category).trigger('click');
				});
				var liPage = ui.draggable.remove();
			});

	      }
	    });

		if(!onlyTree) $('#editor').html(r.content);
		var ul = line.find('ul');
		ul.find('li').remove();
		var html = '';
		for(var key in r.pages){
			var page = r.pages[key];
			page.categorySlug = r.categorySlug;
			html+=Mustache.render(tpl,page);
		}
		ul.append(html);
		wiki_change_url(r.categorySlug);
		if(callback) callback();
	});
}

function wiki_category_delete(element,event){
	event.stopPropagation();
	if(!confirm('Êtes-vous sûr de vouloir supprimer cette catégorie ?')) return;
	var line = $(element).closest('li');
	$.action({
		action : 'wiki_category_delete',
		id : line.attr('data-id')
	},function(r){
		line.remove();
		$.message('info', 'Catégorie supprimée');
	});
}

function wiki_category_download(element,event){
	var line = $(element).closest('li');
	window.location = 'action.php?action=wiki_category_download&category='+line.attr('data-id');
}


/** PAGE **/
function wiki_page_summary(element){
	var togglerIcon = $(element);
	wiki_page_summary_refresh();
	if($('#wiki-summary').hasClass('show')) {
		togglerIcon.removeClass('active');
		$('#wiki-summary').removeClass('show');
	} else {
		togglerIcon.addClass('active');
		$('#wiki-summary').addClass('show');
	}
}
function wiki_page_summary_refresh(){
	var summary = $('#wiki-summary ul');
	var htmlSummary = '';
	$('#editor').find('h1,h2,h3,h4,h5').each(function(i,title){
		var tag = title.tagName.toLowerCase();
		var title = $(title);
		var slug = title.text().trim().toLowerCase().replace(/[^a-z0-9]/ig,'-').replace(/[-]{2,}/ig,'-');

		title.find('.wiki-title-link').remove();
		var link = $('<i class="fas fa-link wiki-title-link"></i>');
		title.attr('id', slug).append(link);

		link
			.addClass('pointer')
			.attr('onclick' , "wiki_copy_anchor(this);")

		if(parseInt(tag.replace('h',''))<5) htmlSummary += '<li class="summary-'+tag+'"><a href="#'+slug+'">'+title.text()+'</a></li>';
	});
	summary.html(htmlSummary);
}
function wiki_page_open(category,page,event,callback){
	if(event) event.stopPropagation();
	if(inEdition && !confirm('Êtes vous sûr de vouloir quitter la page sans sauvegarder ?')) return;
	
	$.action({
		action : 'wiki_page_open',
		category : category,
		page : page,
	},function(r){
		wiki_category_open(r.categorySlug, true, function(){

		$('#editor').html(r.content);
		wiki_page_summary_refresh();

		wiki_change_url(r.categorySlug,r.pageSlug);
		if(window.location.hash!='' && $(window.location.hash).length>0)
			$(window.location.hash).get(0).scrollIntoView();

		$('.wiki-page-content .block-code').append('<div class="pointer text-light btn-copy" title="copier le code"><i class="fas fa-paste"></i></div>');

		$('.wiki-page-content .block-code .btn-copy').click(function(){

			copy_string($(this).parent().text());
			$.message('info','Copié !');
		});

		if(callback) callback();
		});
	});
}

function wiki_copy_anchor(anchor){
	var title = $(anchor).parent();
	var id = title.attr('id');
	var url = window.location.href.replace(/#.*/ig,'')+'#'+id;

	var temp = $('<input>');
	$('body').append(temp);
	temp.val(url).select();
	document.execCommand('copy');
	temp.remove();
	$.message('info','Adresse copiée dans le presse papier');
}

function wiki_page_home(){
	$.action({
		action : 'wiki_page_home',
	},function(r){
		$('#wiki-categories .category').removeClass('category-open').find('li').remove();
		wiki_change_url();
		$('#editor').html(r.content);
	});
}

function wiki_page_edit(callback){
	$('.wiki-page-content #content-text').removeClass('hidden');
	$('.wiki-page-content #content-html').addClass('hidden');

	var pageLabel = $('#page-label');
	pageLabel.attr('contenteditable','true').addClass('show');
	pageLabel.keydown(function(e){
		if(e.keyCode == 13) return false;
	});

	$('.page-option-menu').removeClass('shown');
	$('.page-editor-menu').addClass('hidden');

	$('.page-save-menu').removeClass('hidden');
	$('.page-option-save').addClass('show');

	inEdition = true;
	$('#editor').addClass('edition');
	wikiEditor = new SimpleMDE({
		element: $("#content-text")[0],
		spellChecker : false,
		promptURLs: true,
		autofocus : true,
		toolbar : [
		'bold',"italic",{
			'name' : 'underline',
			action: function customFunction(editor){
				var selected = editor.codemirror.getSelection();
				var newValue = '';
				if(selected.match(/^__.*__$/gi)){
					newValue = selected.replace(/^__(.*)__$/gi,"$1");
				}else{
					newValue = "__"+selected+"__";
				}
				editor.codemirror.replaceSelection(newValue);

			},
			className: "fas fa-underline",
		},"heading-1","heading-2","heading-3","|", "unordered-list", "ordered-list","code","link","image","quote","table","clean-block","horizontal-rule","|","preview","side-by-side","fullscreen"

		],

		//showIcons: ["code", "table","heading-2","heading-3","clean-block","horizontal-rule"]
	});
	if(callback) callback();
}

function wiki_page_add(element, event){
	event.stopPropagation();
	var category = !element ? $('.category-open').attr('data-id') : $(element).closest('li.category').attr('data-id');

	$.action({
		action : 'wiki_page_save',
		category : category,
		content : 'Mon contenu ici...',
	},function(r){
		wiki_page_open(r.category.slug,r.page.slug,event,function(){
			wiki_page_edit(function(){
				$('.html.module-wiki #editor.edition .CodeMirror').click();
			});
		});
	});
}

//Ajout ou modification d'élément page
function wiki_page_save(){
	var pageId = $('.wiki-breadcrumb').attr('data-page');

	$.action({
		action : 'wiki_page_save',
		id : pageId,
		label : $('#page-label').text(),
		content : wikiEditor.value(),
	},function(r){
		var editor = $('#editor');
		var currentPage = $('#categories li.category-open li[data-id="'+pageId+'"].page-open');

		$('.page-option-save, #page-label').removeClass('show');
		$('.page-option-menu').addClass('shown');
		editor.html(r.content).removeClass('hidden');

		$('#page-label').removeAttr('contenteditable','true');
		editor.removeClass('edition');

		currentPage.html(currentPage.children().get(0).outerHTML+' '+r.page.label).attr('data-page', r.page.slug);
		wiki_change_url(r.category.slug, r.page.slug);
		wiki_page_summary_refresh();
		inEdition = false;
	});
}

//Suppression d'élement page
function wiki_page_delete(element){
	if(!confirm('Êtes vous sûr de vouloir supprimer cette page ?')) return;

	$.action({
		action : 'wiki_page_delete',
		id : $('.wiki-breadcrumb').attr('data-page')
	},function(r){
		$.message('info', 'Page supprimée');
		wiki_category_open(r.category.slug);
	});
}

function wiki_page_download(){
	window.location = 'action.php?action=wiki_page_download&page='+$('.wiki-breadcrumb').attr('data-page');
}


function wiki_document_upload(){
	var form = $('#upload-button form');
	var input = form.find('input[type="file"]');
	var zone = $('.container-fluid');
	var droppedFiles = null;
	var noBlink = null;
	input.addClass('hidden');
	$('#upload-button > div').click(function(e){
		input.trigger('click');
		e.preventDefault();
		e.stopPropagation();
	});
	input.on('change', function (e) {
		if(!$('#editor').hasClass('edition')) return;
		if(input.attr('data-label') == 1){
			//Ajout de fichiers avec libellés
			$("#file-modal").remove();
			if(!$('#file-modal').length) {
				var modal = '<div class="modal fade file-modal" id="file-modal" tabindex="-1" role="dialog" aria-labelledby="file-modal-label" aria-hidden="true"><div class="modal-dialog modal-lg" role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="file-modal-label">Libellé par fichier</h5><button type="button" class="close" data-dismiss="modal" aria-label="Fermer"><span aria-hidden="true">&times;</span></button></div><div class="modal-body"><section id="file-form" class="file-form">';
				var tmpData = new FormData(form.get(0));

				//Obligé de passer par l'event pour IE
				if(!e.target.files) return;
				$(e.target.files).each(function(index, value) {
					modal += '<div class="form-group"><label class="form-control-label">'+value.name+'</label><input required onkeyup="if($(this).hasClass(\'label-required\')){$(this).removeClass(\'label-required\'); $(this).attr(\'placeholder\', \'Libellé\')}" type="text" value="" placeholder="Libellé" class="form-control" id="'+slugify(value.name)+'" name="'+slugify(value.name)+'"/></div>';
				});
				modal += '</section></div><div class="modal-footer"><div class="btn btn-light" data-dismiss="modal">Fermer</div><div class="btn btn-success" onclick="if(check_label_filled()){$(\'#upload-button form\').trigger(\'submit\'); $(\'#file-modal\').remove(); $(\'div.modal-backdrop\').remove(); $(\'body\').removeAttr(\'style\').removeClass(\'modal-open\'); $(\'#mainMenu, #mainMenu > button\').removeAttr(\'style\');}"><i class="fas fa-check"></i> Enregistrer</div></div></div></div></div>';
				$('div.document-container').after(modal);
				$('#file-modal:hidden').modal('show');
			}
			$("#file-modal").on("hidden.bs.modal", function () {
				input.val('');
			});
		} else {
			filesNb = $(this)[0].files.length;
			//Sans libellés
			form.trigger('submit');
		}
	});

	zone.on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
		e.preventDefault();
		e.stopPropagation();
	})
	.on('dragover dragenter', function (e) {
		if(!$('#editor').hasClass('edition')) return;
		clearTimeout(noBlink);
		$('#drag-overlay').css('display', 'block');
		zone.addClass('drag-over');
		e.preventDefault();
		e.stopPropagation();
	})
	.on('dragleave dragend drop', function (e) {
		if(!$('#editor').hasClass('edition')) return;
		noBlink = setTimeout(function(){
			$('#drag-overlay').css('display', 'none');
			zone.removeClass('drag-over');
		},500);

		e.preventDefault();
		e.stopPropagation();
	})
	.on('drop', function (e) {
		if(!$('#editor').hasClass('edition')) return;
		if(!e.originalEvent.dataTransfer) return;
		droppedFiles = e.originalEvent.dataTransfer.files;
		filesNb = droppedFiles.length;
		for (var i=0, f; f=droppedFiles[i]; ++i) {
			var ext = f.name.split('.').pop();
			if(!f.type && ext=='' ){
				$.message('error', 'Impossible d\'envoyer un dossier / un élément sans extension.');
				return;
			}
			if(!f.type && ext=='' && f.size%4096 == 0) {
				$.message('error', 'Impossible d\'envoyer un dossier.');
				return;
			}
		}
		if(input.attr('data-label') == 1){
			//Ajout de fichiers avec libellés
			$("#file-modal").remove();
			if(!$('#file-modal').length) {
				var modal = '<div class="modal fade file-modal" id="file-modal" tabindex="-1" role="dialog" aria-labelledby="file-modal-label" aria-hidden="true"><div class="modal-dialog modal-lg" role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="file-modal-label">Libellé par fichier</h5><button type="button" class="close" data-dismiss="modal" aria-label="Fermer"><span aria-hidden="true">&times;</span></button></div><div class="modal-body"><section id="file-form" class="file-form">';

				$(droppedFiles).each(function(index, value) {
					modal += '<div class="form-group"><label class="form-control-label">'+value.name+'</label><input required onkeyup="if($(this).hasClass(\'label-required\')){$(this).removeClass(\'label-required\'); $(this).attr(\'placeholder\', \'Libellé\')}" type="text" value="" placeholder="Libellé" class="form-control" id="'+slugify(value.name)+'" name="'+slugify(value.name)+'"/></div>';
				});
				modal += '</section></div><div class="modal-footer"><div class="btn btn-light" data-dismiss="modal">Fermer</div><div class="btn btn-success" onclick="if(check_label_filled()){$(\'#upload-button form\').trigger(\'submit\'); $(\'#file-modal\').remove(); $(\'div.modal-backdrop\').remove(); $(\'body\').removeAttr(\'style\').removeClass(\'modal-open\'); $(\'#mainMenu, #mainMenu > button\').removeAttr(\'style\');}"><i class="fas fa-check"></i> Enregistrer</div></div></div></div></div>';
				$('div.document-container').after(modal);
				$('#file-modal:hidden').modal('show');
			}
			$("#file-modal").on("hidden.bs.modal", function () {
				input.val('');
			});
		} else {
			//Sans libellés
			form.trigger('submit');
		}
	});

	form.on('submit', function (e) {
		e.preventDefault();
		if(!$('#editor').hasClass('edition')) return;
		var ajaxData = new FormData();

		if (droppedFiles) {
			$.each(droppedFiles, function (i, file) {
				ajaxData.append(input.attr('name'), file);
			});
		} else {
			ajaxData = new FormData(form.get(0));
		}
		ajaxData.append('path', $('#file-elements').attr('data-current-path'));
		droppedFiles = null;

		//Gestion libellés de fichiers
		if(input.attr('data-label') == 1){
			var labels = $('#file-modal input');
			var labelData = {};
			labels.each(function(i, label){
				var label = $(label);
				labelData[label.attr('id')] = label.val();
			});
			var labelArr = JSON.stringify(labelData);
			ajaxData.append('labels', labelArr);
		}

		$.ajax({
			url: form.attr('action'),
			type: form.attr('method'),
			data: ajaxData,
			dataType: 'json',
			cache: false,
			contentType: false,
			processData: false,
			complete: function (data) {},
			success: function (response) {

				if(response.error) return $.message('error',response.error,0);
				var resultMsg = filesNb==1 ? '1 document envoyé' : filesNb+' documents envoyés';

					var value = wikiEditor.value();
					for(var k in response.rows){
						var file = response.rows[k];
						value += "\n"+file.tag;
					}

					wikiEditor.value(value);

				$.message('info',resultMsg);
			},
			error: function (data) {
				$.message('error',data);
			}
		});
	});
}
