$(document).ready(function(){ 
 $('form.ajax-submit').bind('submit',function(e,d,f){	_ajaxSubmitForm(this);	return false;});
// Initialiser tous les select2 visibles immédiatement (ex: ceux en dehors des tabs)
$('select.select2:visible').each(function () {
  $(this).select2();
  $(this).addClass('select2-initialized');
});

// Lorsqu'un onglet devient visible, initialise les select2 à l'intérieur
$('a[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
  const target = $(e.target).attr("href"); // Ex: "#tab-id"

  // Sélectionne tous les <select> visibles avec la classe .select2 et non encore initialisés
  $(target).find('select.select2:not(.select2-hidden-accessible)').each(function () {
    if (!$(this).hasClass('select2-initialized')) {
      $(this).select2();
      $(this).addClass('select2-initialized');
    }
  });
});



$('.taglist').each(function(){
 var input = this;

    // Initialise Tagify sur le champ input
    var tagify = new Tagify(input, {
        delimiters: ",;",      // Autorise virgule et point-virgule
        dropdown: {
            enabled: 0         // Désactive la suggestion automatique
        }
    });

   var initialValue = input.value;
    if (initialValue.trim() !== '') {
		var initialValue = JSON.parse(initialValue);
		initialValue=initialValue[0]['value'];
		
        var tagsArray = initialValue.split(',').map(function (tag) {
            return tag.trim();
        });

        tagify.removeAllTags(); // Supprime la value brute
		// console.log(tagsArray);
        tagify.addTags(tagsArray); // Ajoute proprement les tags
    }
   });
  $('.taglist').on('keydown', function (e) {
        if (e.key === 'Enter') {
            e.preventDefault();
        }
    });
	$(".profil-image").each(function(){
			console.log($(this).data('token'));
			$(this).dropzone({
					maxFiles: 2000,
					url: Lang.theme.url_quick_picture_upload.replace('{token}',$(this).data('token')),
					success: function (file, response,p,e) {
						
						
						if(response.err==0){
							
							$(this.element).find('.empty-image').hide();
							$(this.element).find('.content-filled-image').prop('src',response.file);
							$($(this.element).data('target')).val(response.file.replace(/^.*[\\\/]/, ''));
							$(this.element).find('.filled-image').show();
						}else{
console.log(response);
							_displayMessage(response.title,response.lib,'error');
						}
					}
				})});
	$('.container-profil-image .content-filled-image').bind('click',function(){
		
		$(this).closest('.container-profil-image').find('.dz-message.needsclick').trigger('click');
	});

});
function changeLang(lang,url){
	if(!url) url=window.location.pathname;

	$.ajax({
		  url: Lang.theme.url_change_lang.replace('{lang}',lang),
		  context: document.body,
		  "type": "POST",
		data: {url:url},
		dataType: 'json',
	}).done(function(e,f) {		
		if(e.url && e.url!=window.location.pathname){
			window.location=e.url;
		}else{
			window.location.reload();
		}
		
	});
}
function selfUpdate(selectors) {
    if (typeof selectors === 'string') {
        selectors = [selectors]; // Convert to an array if it's a single selector
    }

    $.ajax({
        url: window.location.href, // Send request to the current URL
        method: 'GET',
        success: function(response) {
            var newContent = $(response); // Parse the response as DOM elements
            selectors.forEach(function(selector) {
                var updatedContent = newContent.find(selector).html(); // Get the new content
                $(selector).html(updatedContent); // Update the current page
            });
        },
        error: function() {
            console.error('Error fetching the content.');
        }
    });
}
function _ajaxSubmitForm(e,callbackfct){
	
		_displayLoader($(e));
	$(e).ajaxSubmit({
					url: ($(e).attr('action')!='') ? $(e).attr('action') : window.location,
					dataType: 'json',
					 error: function(response, statusText, xhr, $form) {
						_hideLoader($(e));
						_displayMessage('An error occured','If it persists, please contact the admin','error');
					 },
					 success: function(response, statusText, xhr, $form) {
						_hideLoader($(e));
						// if(typeof(callbackfct)=='function') callbackfct(response);
						if(callbackfct) response.callback= (response.callback) ? response.callback+"var a="+callbackfct.toString()+'(response)' : "var a="+callbackfct.toString()+'(response)';
						_treatJSONReturn(response);
						
					}
				});
	return false;
}
function _hideLoader(e){
	if(e.hasClass('card')){
		var finalElement=e;
	}else{
		var finalElement=(e.closest('.card').length) ? e.closest('.card')[0] : null;
		// 
	}
	if($(finalElement).find('div.overlay').length>0){
		$(finalElement).find('div.overlay').remove();
	}
}
function _displayLoader(e){
	if(e.hasClass('card')){
		var finalElement=e;
	}else{
		var finalElement=(e.closest('.card').length) ? e.closest('.card')[0] : null;
		// 
	}
	if($(finalElement).find('div.overlay').length==0){
		$(finalElement).append('<div class="overlay"><i class="fas fa-2x fa-sync-alt fa-spin"></i></div>');
	}
}

function _treatJSONReturn(response){
	callback=function(t){};
	if(typeof(response.callback)=='string' && response.callback.trim()!=''){
		
			eval('var callback=function(response){'+response.callback+"}");
	}
	
	if(response.err==0){		
		if(response.lib && response.lib!=''){
			// console.log('ok');
			// console.log(callback);
			_displayMessage(response.title,response.lib,'success',callback,response);
		}else{
			callback(response);								
		}
	}else{
		var title= (response.title && response.title!='') ? response.title : 'Error';
		if(response.lib && response.lib!=''){
			
			_displayMessage(response.title,response.lib,'error',callback,response);
		}else{
			callback();
		}
	}
 
}



function _displayMessage(title,Message,type,callback,param){

			if(type=='error'){
				   Swal.fire({ title: title, text: Message, icon: "error",  confirmButtonColor: "#556ee6",  }).then((result) => {
					if(callback){
						callback(param); 
					}
					})
				// swal({"title": title,"text": Message,"type": 'error'},callback);//.then(callback);
			}else{
				
				 Swal.fire({ title: title, text: Message, icon: "success",  confirmButtonColor: "#556ee6",  }).then((result) => {
					if(callback){
						callback(param); 
					}
					})
			}
		
}
function initToolTipster(elem){
	
	elem.find('.tooltipster').each(function(){
		select=$(this).data('tooltipstertarget');
		
		$(this).tooltipster({
			content: $(select).html(),
			contentAsHTML: true,
			// theme: 'actuccitt',
		});
		$(select).remove();
	});
}
function initSwapButton(elem){
	// 
	elem.find('.button-switch').click(function(){
		if($(this).hasClass('btn-outline-secondary') && ! $(this).hasClass('btn-switch-disabled')){
			var butonSelect=$(this).closest('.field-switchbuttons').find('.btn-secondary');	
			butonSelect.removeClass('btn-secondary');	
			butonSelect.addClass('btn-outline-secondary');
			
			$(this).addClass('btn-secondary');	
			$(this).removeClass('btn-outline-secondary');
			$(this).closest('.field-switchbuttons').find('input[type="hidden"]').val($(this).data('value'));	
		}
	});
}
function initCheckboxShowHide(elem){
	
	elem.find('.hide-oncheck').click(function(){
		if(this.checked){
			$($(this).data('target')).hide();
		}else{
			$($(this).data('target')).show();
		}
	});
	elem.find('.hide-oncheck').each(function(){
		if(this.checked){
			$($(this).data('target')).hide();
		}else{
			$($(this).data('target')).show();
		}
	});
}

$(document).ready(function(){
	initToolTipster($(document));
	initCheckboxShowHide($(document));
	initSwapButton($(document));
	if($.fn.fileUpload){
		$.fn.fileUpload.defaults = {
			language: {
				title: Lang.theme.multipleupload_title,
				instruction: Lang.theme.multipleupload_instruction,
				or: Lang.theme.multipleupload_or,
				browse: Lang.theme.multipleupload_browsefiles,
				noFiles: Lang.theme.multipleupload_noselectedfile,
				columns: {
					fileName: Lang.theme.multipleupload_column_filename,
					preview: Lang.theme.multipleupload_column_preview,
					size: Lang.theme.multipleupload_column_size,
					type: Lang.theme.multipleupload_column_type
				}
			},
			columns: {
				number: { visible: true },
				fileName: { visible: true },
				preview: { visible: true },
				size: { visible: true },
				type: { visible: true },
				actions: { visible: true }
			}
		};
	}
	// Guard: n'initialise TinyMCE que si la lib est disponible ET qu'il y a des éditeurs sur la page
	if (typeof tinymce !== 'undefined' && $('textarea.wysiwyg-basic').length > 0) {
		tinymce.init({
            selector: "textarea.wysiwyg-basic",
            height: 200,
			menubar:false,
			statusbar: false,
            plugins: [
                "advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker",
                "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
                "save table contextmenu directionality emoticons template paste textcolor",
            ],
            toolbar: "undo redo  | bold italic | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent",
           
        });
	}
});


if ($.fn && $.fn.dataTable) $.extend( true, $.fn.dataTable.defaults, {
	"bStateSave": true,
	"pageLength": 100,
	"responsive": false,
	
	// scrollX: true,
 // "sScrollX": "100%",
        // "bScrollCollapse": true,
	"autoWidth": false,
	"paging": true,
	 "colReorder": true,
     "language": { info: '_START_ sur  _END_ (_MAX_)' },
     "serverSide": true,
		dom: 'slBfrtip',
	"initComplete": function(settings, json) {
		
		// if($(this).hasClass('table-new-design')){
			// if(!$(this).closest('.dataTables_wrapper').hasClass('table-wrapper-new-design'))	$(this).closest('.dataTables_wrapper').addClass('table-wrapper-new-design');
		// }
	},
	
	"buttons": ["csv",{
            extend: 'colvis',
			text: Lang.theme.datatables_colvis, 
            columns: 'th:not(.noviscontrol)',
			columnText: function ( dt, idx, title ) {
				return (title=='&nbsp;') ? false : '<i class="fa fa-check"></i>&nbsp;&nbsp;' + title;
			}
        }],
	"language": {
			"emptyTable": Lang.theme.datatables_zeroRecords,
			"zeroRecords": Lang.theme.datatables_zeroRecords,
			"infoEmpty": Lang.theme.datatables_info_base,
			"lengthMenu": Lang.theme.datatables_lengthMenu,
			"search": Lang.theme.datatables_search,
			"processing": Lang.theme.datatables_processing,
			"searchPlaceholder": Lang.theme.datatables_searchPlaceholder,
			"infoFiltered": Lang.theme.datatables_info_filtered,//" - filtered from _MAX_ records"
			"info": Lang.theme.datatables_info,
			'paginate': {
               'first':    Lang.theme.datatables_paginate_first,
               'previous': Lang.theme.datatables_paginate_previous,
               'next':     Lang.theme.datatables_paginate_next,
               'last':     Lang.theme.datatables_paginate_last
            }
	  }
} );


/**
 * Append toolbar to tree
 * Used for jstree with custom toolbars
 */
var _appendToolBarToTree = function(tree, toolbar) {
	toolbar.appendTo(tree);
	if(!tree.hasClass('has-toolbar')) {
		tree.addClass('has-toolbar');
	}
	toolbar.find('.toolbar-button').each(function() {
		if($(this).attr('wwl-picto')) {
			$(this).css('background-image', "url(" + $(this).attr('wwl-picto') + ")");
		}
	});
};
