var navigationMenuEdited = false;

//CHARGEMENT DE LA PAGE SETTING
function init_setting_global_navigation(){
	window.onbeforeunload = function(e){
	  if(!navigationMenuEdited) return e = null;
	  return "Certaines modifications sur le menu n'ont pas été sauvgardées.\nÊtes-vous sûr de vouloir quitter la page ?";
	};
	navigation_menu_setting_search();
}


function navigation_menu_setting_search(){
	navigation_tree_search();

	$( ".navigation-tree-list" ).sortable({
		handle: ".navigation-item-header",
		cancel: ".not-editable",
		helper: "clone",
    	opacity: 0.8,
		distance : 15,
		grid: [ 50, 1 ],
      	update : function(){
      		navigationMenuEdited = true;
      	},
      	start: function(e,ui) {
      		draggedItem = $(ui.item[0]);
      		if(draggedItem.hasClass('navigation-line-child')) return;

      		children = [];
      		var borderReached = false;
      		$.each(draggedItem.nextAll('li.navigation-line'), function(i, childLine){
      			var line = $(childLine);

      			if(borderReached || !line.hasClass('navigation-line-child')) {
      				borderReached = true;
      				return;
      			}
      			children.push(line);
				line.addClass('hidden');
      		});
      	},
		sort: function(event,ui){
			var leftLimit = ui.item.hasClass('navigation-line-child') ? -20 : 15;
			if(ui.position.left < leftLimit){
				ui.helper.css('left',leftLimit+'px');
			}
			if(ui.position.left > 65){
				left = 65;
				ui.helper.css('left',left+'px');
			}
			if(ui.item.index()==1){
				ui.helper.css('left',leftLimit+'px');
			}
		},
		stop: function(event,ui){
			if(ui.position.left>15){
				if(!ui.item.hasClass('navigation-line-child')) navigationMenuEdited = true;
				ui.item.addClass('navigation-line-child');
			}else{
				if(ui.item.hasClass('navigation-line-child')) navigationMenuEdited = true;
				ui.item.removeClass('navigation-line-child');
			}

			if(!children.length) return;
			$.each(children.reverse(), function(i, row){
				$(row).insertAfter(draggedItem).removeClass('hidden');
			});
		},
		// placeholder: "navigation-item-placeholder",
		placeholder: {
			element: function(clone, ui) {
				var placeholderRow =  $('<li class="navigation-item-placeholder"></li>');

				/** Lié à la feature de drag&drop de plusieurs lignes à la fois **/
				if(!clone.hasClass('navigation-line-child')){
					var rowNb = 1;
					var borderReached = false;

		      		$.each(clone.nextAll('li.navigation-line'), function(i, childLine){
		      			var line = $(childLine);

		      			if(borderReached || !line.hasClass('navigation-line-child')) {
		      				borderReached = true;
		      				return;
		      			}
		      			rowNb += 1
		      		});

					placeholderRow.css({
						height: 'calc(44px * '+rowNb+')',
					});
				}
                return placeholderRow;
            },
            update: function() {
                return;
            }
		}
    });
    $(".navigation-tree > ul").disableSelection();
}



/** Éditeur d'arborescence **/
//Enregistrement des configurations
function navigation_setting_save(){
	if(isProcessing) return;
	var items = [];
	var lastParentIndex = 0;

	$('.navigation-line:not(.hidden)').each(function(i,element){
		var line = $(element);
		var item = {
			id: line.attr('data-id'),
			label: line.find('.item-label').val(),
			visibility: line.find('input.item-visibility').val(),
			url: line.find('.item-url').val(),
			icon: line.find('.item-icon').val(),
			target: line.find('[name="item-target"]:checked').val(),
		};

		if(line.hasClass('navigation-line-child')){
			items[lastParentIndex].childs.push(item);
		}else{
			lastParentIndex = items.length;
			item.childs = [];
			items.push(item);
		}
	});

	isProcessing = true;
	$.action({
		action: 'navigation_setting_save',
		fields:  $('#navigation-setting-form').toJson(),
		items: items,
		firm: $('#navigation-firm').val(),
		menu: $('#navigation-menu').val()
	},function(){
		isProcessing = false;
		navigationMenuEdited = false;
		$.message('success','Enregistré');

		navigation_tree_search();

		$('#navbarCollapse').load(document.URL+' #navbarCollapse > *');
	},function(){
		isProcessing = false;
	});
}


function navigation_tree_search(callback){
	var menu = $('#navigation-menu').val();
	if(!menu || menu=='' || isProcessing) return;

	isProcessing = true;
	$.action({
		action: 'navigation_tree_search',
		firm: $('#navigation-firm').val(),
		menu: menu
	},function(r){
		$('.navigation-tree > ul > li:visible').remove();
		for(var key in r.rows){
			var line =  r.rows[key];
			navigation_tree_add(line);
			if(line.childs){
				for(var key2 in line.childs){
					navigation_tree_add(line.childs[key2]);
				}
			}
		}
		isProcessing = false;
	},function(r){
		isProcessing = false;
	});
}

function navigation_tree_new(element){
	var data = {
		label: 'Sans titre',
		icon: 'far fa-bookmark',
		url: '',
		shortcut: $('#navigation-menu>option:selected').attr('data-slug') == 'shortcut-menu',
		target: {slug:'redirect'}
	};

	if(element){
		data = $.extend(data, $(element).closest('.list-group-item').data());
		$.message('info','Lien "'+data.label+'" ajouté au menu');
	}

	var line = navigation_tree_add(data);
	navigation_tree_toggle(line.find('.navigation-item-toggle'));
}

function navigation_tree_add(data){
	var tpl = $('.navigation-line:hidden').get(0).outerHTML;
	if(data.visibility==null) data.visibility = $('.item-visibility',tpl).attr('data-default');
	tpl = tpl.replace('data-type="user-tpl"','data-type="user"');
	var line = $(Mustache.render(tpl,data));

	line.removeClass('hidden');
	$('.navigation-tree > ul').append(line);

	line.find('[name="item-target"][value="'+data.target.slug+'"]').prop('checked',true);

	line.off('keyup','.item-label').on('keyup','.item-label', function(){
		navigationMenuEdited = true;
		line.find('.navigation-item-label').text($(this).val());
	});
	line.off('keyup','.item-url').on('keyup','.item-url', function(){
		navigationMenuEdited = true;
		line.find('.navigation-item-url').text($(this).val());
	});
	line.off('click','[name="item-target"]').on('click','[name="item-target"]', function(){
		navigationMenuEdited = true;
		line.find('.navigation-item-type span').text($(this).parent().text());
	});
	line.off('change','.item-icon').on('change','.item-icon', function(){
		navigationMenuEdited = true;
		line.find('.navigation-item-icon i').attr('class',$(this).val());
	});
	return line;
}

function navigation_tree_toggle(element){
	var toggler = $(element).find('i');
	var line = toggler.closest('.navigation-line');
	toggler.toggleClass('fa-angle-right fa-angle-down');
	$('.navigation-item-form',line).toggleClass('hidden');
	init_components(line);
}

function navigation_tree_remove(element){
	if(!confirm('Êtes-vous sûr de vouloir supprimer cet élement de menu ?')) return;
	navigationMenuEdited = true;
	$(element).closest('.navigation-line').remove()
}

