jQuery(document).ready(function($){

	
	// Conseils connection
	$('.connection_carousel').owlCarousel({
	    loop:true,
	    margin:10,
	    dots:true,
	    nav:false,
	    autoplay:true,   
	    smartSpeed: 1000, 
	    autoplayTimeout:7000,
	    responsive:{
	        0:{
	            items:1
	        },
	        600:{
	            items:1
	        },
	        1000:{
	            items:1
	        }
	    }
	})
	
	// Identification
	$("#form_connection").validate({
	    errorPlacement: function($error, $element) {
	       $error.insertAfter($element.parent());
	     },
		rules: {					
			email: { 		required: true, email: true },
			pass: { 		required: true, minlength: 8 },
		},
		messages: {
			email: 			"Merci de préciser votre email ?",
			pass: {
					required: "Préciser votre mot de passe ?",
					minlength: "8 caractères minimum",
			},
		},

		submitHandler: function() {
					
			var btn_text = 	$("#form_connection button[type=submit]").text();
			addBtnLoading('form_connection',btn_text);
		
			$.ajax({
				type: 'POST',
				processData: true,
				url: ROOT_URL+'services/user/user.php',
				data: $("#form_connection").serialize(),
				success: function(message){
			
					recoverError(message);
					
					var datas 		= message.split('|');
					
					if (datas[0] == "ok")
					{
						// Matomo
						window._mtm = window._mtm || [];
						window._mtm.push({
						'event': 'connexion-compte',
						'typeMembre': ''+datas[2]+''
						});
						
						alertify.success('<b>Bienvenue '+ datas[1] +' !</b> <i class="fa fa-spinner fa-spin"></i>');
						
						if ($('#return_url').val() != '')
						{
							var my_url = $('#return_url').val();
							if (my_url != "/inscription") {
								window.location.href=""+my_url+"";
							} else
							{							
								window.location.href=datas[3];
							}
						} else
						{
							window.location.href=datas[3];
						}
						
						return false;
					}

					removeBtnLoading('form_connection',btn_text);
			
					if (datas[1] == 'is_mineur_email_parent')
					{
						$('#mineur_email_parent').show();
						alertify.error('Merci de préciser l\'email de votre parent ou d\'un titulaire de l\'autorité parentale');
						return false;
					}
			
					if (datas[1] == 'is_mineur_email_parent_mail_different')
					{
						$('#mineur_email_parent').show();
						alertify.error('Merci de préciser un autre email pour votre parent ou pour le titulaire de l\'autorité parentale');
						return false;
					}
					
					if (datas[1] == 'inconnu')
					{
						alertify.error('<b>Authentification impossible ...');
						$('#error_msg').html('<div class="col-12 text-center pb-2"><b>Authentification impossible ...</b><br />Merci de vérifier votre email et mot de passe</div>');			
						return false;
					}
					
					if (datas[1] == "compte_non_valide")
					{						
						$('#error_msg').html('<div class="col-12 text-center pb-2"><b>Compte non validé ...</b><br />Merci de cliquer sur le lien reçu lors de l\'inscription<br /><a href="Javascript:void(resend_form())" class="submit">Recevoir le lien d\'activation</a></div>');
						alertify.error('Compte non validé');
						return false;
					}						
		
					if (datas[1] == "compte_suspendu")
					{
						$('#error_msg').html('<div class="col-12 text-center pb-2"><b>Compte suspendu ...</b><br />Vous pouvez contacter le webmaster pour re activer votre compte<br />par email <a href="mailto:webmaster@jobirl.com">webmaster@jobirl.com</a></div>');
						alertify.error('Compte suspendu');
						return false;
					}	

					if (datas[1] == "compte_parent_waiting")
					{
						$('#error_msg').html('<div class="col-12 text-center pb-2"><b>Ton compte n\'est pas encore actif</b><br />car ton tuteur légal doit valider ton inscription,<br />demande lui !</b></div>');
						alertify.error('Ton compte n\'est pas actif');
						return false;
					}	

					alertify.error('Une erreur s\'est produite : '+ datas[1] +'...');
					return false;					
				}
			}).message;
			return false;
		}
	});
	
	
	$('[data-toggle="tooltip"]').tooltip();
	
	// Ouverture moteur de recherche tetiere
	$('.open_search_form').click(function()
	{
		$('#show_menu_search').slideToggle();
		document.body.scrollTop = 0; // For Safari
		document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
		$('.navbar-collapse').collapse('hide');
	});
	
	// Carousel partenaires
	$('.partenaires_carousel').owlCarousel({
	    loop:true,
	    margin:10,
	    dots:false,
	    nav:false,
	    autoplay:false,   
	    smartSpeed: 3000, 
	    autoplayTimeout:7000,
	    responsive:{
	        0:{
	            items:1
	        },
	        600:{
	            items:2
	        },
	        1000:{
	            items:6
	        }
	    }
	});

	// Carousel partenaires 
	$('.derniers_inscrits').owlCarousel({
	    loop:true,
	    margin:10,
	    dots:false,
	    nav:false,
	    autoplay:false,   
	    smartSpeed: 3000, 
	    autoplayTimeout:7000,
	    responsive:{
	        0:{
	            items:2
	        },
	        480:{
	            items:3
	        },
	        768:{
	            items:2
	        },
	        1000:{
	            items:4
	        }
	    }
	});

	// Carousel inside posts
	$('.carousel_blocks').owlCarousel({
	    loop:false,
	    margin:10,
	    dots:false,
	    nav:false,
	    autoplay:true,   
	    smartSpeed: 3000, 
	    autoplayTimeout:7000,
	    responsive:{
	        0:{
	            items:2
	        },
	        480:{
	            items:3
	        },
	        768:{
	            items:2
	        },
	        1000:{
	            items:4
	        }
	    }
	});	

	// Carousel stages inside posts
	$('.carousel_blocks_stage').owlCarousel({
	    loop:false,
	    margin:10,
	    dots:false,
	    nav:false,
	    autoplay:true,   
	    smartSpeed: 3000, 
	    autoplayTimeout:7000,
	    responsive:{
	        0:{
	            items:1
	        },
	        480:{
	            items:1
	        },
	        768:{
	            items:3
	        },
	        1000:{
	            items:3
	        }
	    }
	});

	// Carousel de temoignages
	$('.temoignages_carousel').owlCarousel({
	    loop:true,
	    margin:100,
	    dots:true,
	    nav:false,
	    autoplay:true,   
	    smartSpeed: 1000, 
	    autoplayTimeout:7000,
	    responsive:{
	        0:{
	            items:1
	        },
	        600:{
	            items:1
	        },
	        1000:{
	            items:1
	        }
	    }
	});

	
	ScrollReveal().reveal('.reveal');	

	/* Formulaires */	
    $('.select2').each(function () {
        $(this).select2({
          theme: 'bootstrap4',
          width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
          placeholder: $(this).data('placeholder'),
          allowClear: Boolean($(this).data('allow-clear')),		   
 		 language: {
 			 "noResults": function(){
 	         	return "Aucun résultat";
 			  }
 	     },
 	     escapeMarkup: function (markup) {
 	     	return markup;
 	     }
			   
        });
   });
   
   // Select form avec recherche		
    $(".select1").select2({ });


  /* $(".anchor_link").click(function (){
   	$('html, body').animate({
                      scrollTop: $("#tetiere_container").offset().top
                  }, 2000);
   });
	*/
			  
   // Top scroll
   $('.anchor_link').click(function() 
   {
   	var anchorToGo = $(this).attr('name');
	
	$('html, body').animate({ scrollTop: $('div[id|="'+anchorToGo+'"]').offset().top}, 1000);
	
	
   //	$.scrollTo( 'div[id|="'+anchorToGo+'"]',{ duration:'1000', offsetTop: '0',easing: 'swing'});
   });	


	// Selects
	/*
	 $('select').each(function() {
		goSelect2($(this).attr('id'));	
	});
	 */
	
	// Dates
	// $('.datepicker').datepicker({ dateFormat: 'dd/mm/yy', startDate: new Date('2000-01-01') });
	
	// Inputs
	$( "input" ).change(function()
	{
		var content = $(this).val();
		var id 		= $(this).attr('id');
		if (content != '')
		{			
			$(".label_"+id+"").addClass('ison');
			return;
		} else {
			$(".label_"+id+"").removeClass('ison').show();
		}
	});
	
	// Recherche principale
	$( "#form_menu_search button" ).click(function( event )
	{
		event.preventDefault();		
		submitFormSearch();
	});
	
	// Selection filtres du moteur
	$( "#filtres .filtre" ).change(function( event )
	{
		event.preventDefault();
		submitFormSearch();
	});
	
	// Recherche ecole
	$("#filtres #ajax_ecole").autocomplete({
		source: ROOT_URL+'services/societe/societe.php?qui=ecole&action=ajaxsearch',
		minLength: 2,
	 	response : function (event, ui )
		{
			
		},   
		select: function( event, ui ) {
			$('#current_ecole').remove();
			$('#ajax_ecole').removeAttr('name').prop('disabled', true);
			$("#form_menu_search").append('<input type="hidden" name="ecole" id="search_ecole" value="'+ui.item.url+'" />');
			submitFormSearch();
			/*log( ui.item ?
			"Selected: " + ui.item.value + " aka " + ui.item.Sid :
				"Nothing selected, input was " + this.value );*/
		}
	});
	
	// Recherche ecole change
	$( "#filtres #ajax_ecole" ).change(function( event )
	{
		event.preventDefault();
		$('#current_ecole').remove();
	});
	
	// Recherche entreprise
	$("#filtres #ajax_entreprise").autocomplete({
		source: ROOT_URL+'services/societe/societe.php?qui=societe&action=ajaxsearch',
		minLength: 2,
	 	response : function (event, ui )
		{
			
		},   
		select: function( event, ui )
		{
			$('#current_entreprise').remove();
			$('#ajax_entreprise').removeAttr('name').prop('disabled', true);
			$("#form_menu_search").append('<input type="hidden" name="entreprise" id="search_entreprise" value="'+ui.item.url+'" />');
			submitFormSearch();
		}
	});
	
	$( "#filtres #ajax_entreprise" ).change(function( event )
	{
		event.preventDefault();
		$('#current_entreprise').remove();
	});
	
	// Recherche formation
	$("#filtres #ajax_formation").autocomplete({
		source: ROOT_URL+'services/formation/formation.php?action=ajax_search_onisep',
		minLength: 2,
	 	response : function (event, ui )
		{
			
		},   
		select: function( event, ui ) {
			$('#current_formation').remove();
			$('#ajax_formation').removeAttr('name').prop('disabled', true);
			$("#form_menu_search").append('<input type="hidden" name="formation" id="search_formation" value="'+ui.item.slug+'" />');
			submitFormSearch();
		}
	});
	
	$( "#filtres #ajax_formation" ).change(function( event )
	{
		event.preventDefault();
		$('#current_formation').remove();
	});
	
	// Recherche entreprise stage (meteojob)
	$("#filtres #ajax_entreprise_stage").autocomplete({
		source: ROOT_URL+'services/societe/societe.php?qui=societe&action=ajaxsearch_for_stage&type='+$('#type').val(),
		minLength: 2,
	 	response : function (event, ui )
		{
			
		},   
		select: function( event, ui )
		{
			$('#current_identreprise').remove();
			$('#current_entreprise').remove();
			$('#ajax_entreprise_stage').removeAttr('name').prop('disabled', true);
			
			if (ui.item.is_lieu == 1)
			{
				$("#form_menu_search").append('<input type="hidden" name="lieu" id="ajax_entreprise_stage" value="'+ui.item.value+'" />');				
			} else
			{
				$("#form_menu_search").append('<input type="hidden" name="entreprise" id="ajax_entreprise_stage" value="'+ui.item.url+'" />');
			}
			$( "#form_menu_search option:selected" ).val(''+$('#url_type_stage').val()+'');
			
			submitFormSearch();
			
		}
	});
	
	$( "#filtres #ajax_entreprise_stage" ).change(function( event )
	{
		event.preventDefault();
		$('#current_identreprise').remove();
	});
	
	// Suppression des filtres
	$('.removeFilter').click(function( event )
	{
		event.preventDefault();		
		var monFiltre 	= $(this).data('name');
		var monId 		= $(this).data('id');
		if ((monFiltre == "entreprise") || (monFiltre == "ecole") || (monFiltre == "formation"))
		{
			$('#current_'+monFiltre+'').val('');
			$('#current_identreprise').val('');
			$('#ajax_entreprise').val('');
			$('#ajax_entreprise_stage').val('');
			$('#search_entreprise').val('');
			$('#search_formation').val('');
			$('#ajax_formation').val('');
			$('#search_ecole').val('');
			$('#ajax_ecole').val('');
			$('#'+monFiltre+'').removeAttr('name').prop('disabled', true);
		}
		
		if (monFiltre == "tag")
		{
			$('#tag_'+monId+'').remove();
		}
		
		$('#'+monFiltre+'').removeAttr('name').prop('disabled', true);
		
		// $("#form_menu_search").append('<input type="text" name="'+monFiltre+'" value="" />');
		
		$("option[value*='"+monId+"']").prop('selected', false);
		
		submitFormSearch();
	});
	
	// Filtre repplus des ecoles (stage 3eme)
	$( "#filtre_ecole_repplus" ).change(function(event)
	{
		event.preventDefault();
		$('#q').after('<input type="hidden" name="id_college" value="'+$(this).val()+'" />');		
		submitFormSearch();
	});
	
	// Progress bar inscription
	$("#progress_bar > span").each(function()
	{
		$(this)
			.data("origWidth", $(this).width())
			.width(0)
			.animate({
				width: $(this).data("origWidth")
			}, 1200);
	});
	
	// Event cp / ville
	$( ".ajax_cp, .ajax_ville" ).keypress(function(event)
	{
		if (event.key === "Enter") { event.preventDefault(); }
	});
	
	$( ".ajax_cp, .ajax_ville" ).on('blur', function(event)
	{
		
		if ($('#pays').val() != 'France') return false;
		
		if ($('#Vid').val() == '')
		{
			$error_txt = 'votre code postal';
			if ($(this).attr('id') == 'ville')
				$error_txt = 'votre ville';
			
			alertify.error('Merci de choisir '+$error_txt+' parmi la liste proposée');
			$(this).val('');
		}			
	});
	
	// Recherche cp
	$(".ajax_cp").autocomplete({
		source: ROOT_URL+'services/tools/tools.php?action=ajax_search_cp',
		minLength: 2,
	 	response : function (event, ui )
		{
			
		},   
		select: function( event, ui )
		{
			event.preventDefault();
			$('#cp').val(''+ui.item.code_postal+'');
			if ($('#form_edit_profil').length > 0 )
			{				
				$('#ville').val(''+ui.item.ville+'');
				$('#pays option[value="France"]').attr('selected', 'selected');
				$('#select2-pays-container').html('France');
				$('.label_cp, .label_ville').removeClass("error");
				$('.label_cp').after('<i class="fa fa-thumbs-up"></i>');				
			}
			$('#Vid').val(''+ui.item.id+'');
		}
	});
	
	// Recherche ville
	$(".ajax_ville").autocomplete({
		source: ROOT_URL+'services/tools/tools.php?action=ajax_search_ville',
		minLength: 2,
	 	response : function (event, ui )
		{
			
		},   
		select: function( event, ui ) {
			
			event.preventDefault();			
			
			$('#cp').val(''+ui.item.code_postal+'');
			$('#ville').val(''+ui.item.ville+'');
			
			if ($('#form_edit_profil').length > 0 )
			{
				$('#pays option[value="France"]').attr('selected', 'selected');	
				$('#select2-pays-container').html('France');
				$('.label_ville').after('<i class="fa fa-thumbs-up"></i>');
				$('.label_cp, .label_ville').removeClass("error");
			}
			$('#Vid').val(''+ui.item.id+'');
		}
	});

	// Full membre/metier navigation next/prev
	if ($('.swip_nav').length > 0 )
	{
		$('.swip_nav > div').click(function( event )
		{
			$goTo = $(".swip_nav.next > div").data('url');
			window.location.href=$goTo;
			return false;
		});

	}
	
	
 	// Ouverture modal envois de message a un membre
	/*$('.openModalRedactionMessage').click(function()
	{
		$('#modal_redaction_message #redaction_message_username').html(''+$(this).data('username')+'');
		$('#modal_redaction_message #redaction_message_userid').val(''+$(this).data('userid')+'');
	});*/
	
	// Click sur pagination
	$(".page-link").click(function()
	{
		displayLoader();
	});
	
	// Pagination select
	$('#paginationSelect').change(function( event )
	{
		$('#formPaginationSelect').submit();		
	});
	
	// Parcours date de debut
	$('.date_mois_debut').datepicker( {
		changeMonth: true,
		changeYear: true,
		showButtonPanel: true,
		monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
		monthNamesShort: ['Janv.', 'Févr.', 'Mars', 'Avril', 'Mai', 'Juin', 'Juil.', 'Août', 'Sept.', 'Oct.', 'Nov.', 'Déc.'],
		yearRange: "c-70:c+"+$('#date_more_years').val(),
		dateFormat: 'mm/yy',
		closeText:'Choisir',
		onClose: function(dateText, inst) {
			function isDonePressed() {
				return ($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1);
			}

			if (isDonePressed()) {
				var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
				var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
				$(this).datepicker('setDate', new Date(year, month, 1)).trigger('change');

				$('.date-picker').focusout() //Added to remove focus from datepicker input box on selecting date
			}
		},
		beforeShow: function(input, inst) {

			inst.dpDiv.addClass('month_year_datepicker')

			if ((datestr = $(this).val()).length > 0) {
				year = datestr.substring(datestr.length - 4, datestr.length);
				month = datestr.substring(0, 2);
				$(this).datepicker('option', 'defaultDate', new Date(year, month - 1, 1));
				$(this).datepicker('setDate', new Date(year, month - 1, 1));
				$(".ui-datepicker-calendar").hide();
			}
		}
	});
	
	// Parcours date de fin
    $('.date_mois_fin').datepicker( {
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
		monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
		monthNamesShort: ['Janv.', 'Févr.', 'Mars', 'Avril', 'Mai', 'Juin', 'Juil.', 'Août', 'Sept.', 'Oct.', 'Nov.', 'Déc.'],
		yearRange: "c-70:c+4",
		dateFormat: 'mm/yy',
		closeText:'Choisir',
		onClose: function(dateText, inst) {
			function isDonePressed() {
				return ($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1);
			}

			if (isDonePressed()) {
				var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
				var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
				$(this).datepicker('setDate', new Date(year, month, 1)).trigger('change');

				$('.date-picker').focusout() //Added to remove focus from datepicker input box on selecting date
			}
		},
		beforeShow: function(input, inst) {

			inst.dpDiv.addClass('month_year_datepicker')

			if ((datestr = $(this).val()).length > 0) {
				year = datestr.substring(datestr.length - 4, datestr.length);
				month = datestr.substring(0, 2);
				$(this).datepicker('option', 'defaultDate', new Date(year, month - 1, 1));
				$(this).datepicker('setDate', new Date(year, month - 1, 1));
				$(".ui-datepicker-calendar").hide();
			}
		}
	});
	
	// Choix annee et mois uniquement 
	$(".datepicker_month_year").datepicker({
		dateFormat: 'mm/yy',
		   altField: "#datepicker",
		   defaultDate: returnDateForPicker($(this).val()),
		   closeText: 'Ok',
		   prevText: 'Précédent',	   
		   nextText: 'Suivant',	   
		   monthNamesShort: ['Janv.', 'Févr.', 'Mars', 'Avril', 'Mai', 'Juin', 'Juil.', 'Août', 'Sept.', 'Oct.', 'Nov.', 'Déc.'],
	       selectDay: false,
	       changeDay: false,
	       changeMonth: true,
	       changeYear: true,
	       showButtonPanel: false,
		   yearRange: "-100:+0",
	       onClose: function(dateText, inst) {		   
			   var currentDate = $(this).val();
			   if (currentDate != month+'/'+year) {
		           var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
		           var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
		           $(this).val($.datepicker.formatDate('mm/yy', new Date(year, month, 1)));		   	
			   }
	       }
	});  
	
	// Choixdate dd/mm/YY
	$(".datepicker").datepicker({
		dateFormat: 'dd/mm/yy',
		   altField: "#datepicker",
		   defaultDate: returnDateForPicker($(this).val()),
		   closeText: 'Ok',
		   prevText: 'Précédent',	   
		   nextText: 'Suivant',	   
		   monthNamesShort: ['Janv.', 'Févr.', 'Mars', 'Avril', 'Mai', 'Juin', 'Juil.', 'Août', 'Sept.', 'Oct.', 'Nov.', 'Déc.'],
	       selectDay: false,
	       changeDay: true,
	       changeMonth: true,
	       changeYear: true,
	       showButtonPanel: false,
		   yearRange: "-100:+0"
	});
	
	// Fermeture side panel
	$( "body" ).delegate( ".close_side_panel", "click", function()
	{
		$('.side_panels').slideReveal("hide");
	});	
	
	// Ouverture side panel for signalement
	$( "body" ).delegate( ".open_side_panel_signaler", "click", function()
	{
		$('#form_signaler #id').val($(this).data('id'));
		$('#form_signaler #quoi').val($(this).data('name'));
		if ($('#form_signaler #from').val() == '')
		{
			$('#form_signaler #from').val($(this).data('from'));			
		}
		
		// $('#side_panel_comment').slideReveal("hide");
	});
	
	// Ouverture side panel signalement
 	$('#side_panel_signaler').slideReveal({
 		trigger: $(".open_side_panel_signaler"),
 		position: $("#panel_position").val(),
 		push: false,
	    show: function(slider, trigger){
			 resizeSidePanel();
			 $('#side_panel_signaler').show();			 
	     },
		 hidden: function(slider, trigger){
		     $('#side_panel_signaler').hide();
		 },
		 shown: function(slider, trigger){
	 		$quoi = $('#form_signaler #quoi').val();
	 		if ($quoi == "message")
	 		{
	 			$('#form_signaler h4').html('Merci de nous alerter sur le contenu inapproprié de ce message.');
	 		} else
			{
				$('#form_signaler h4').html('Signaler un contenu inapproprié<br />ou inexacte');				
			}
		 },
 	});
	
	$("#form_signaler").validate({
		rules: {
			message: { required: true},
		},
		messages: {
			message: 		"Quel signalement ?",
		},	
		submitHandler: function(form) {
			 
 			var btn_text = 	$("#form_signaler button[type=submit]").text();
 			addBtnLoading('form_signaler',btn_text);
			
			$.ajax({
			type: 'POST',
			processData: true,
			url: ROOT_URL+'services/tools/tools.php',
			data: $("#form_signaler").serialize(),
			success: function(message){
				var datas 	= message.split('|');			
				
				if (datas[0] =="ok")
				{				
					alertify.success('Votre signalement à bien été envoyé à nos équipes, merci ! <i class="fa fa-spinner fa-spin"></i>');
					removeBtnLoading('form_signaler',btn_text);
					setTimeout(function(){
						$('#side_panel_signaler').hide();
					}, 3000);
					return false;
				} else
				{
					alertify.error('Erreur: '+ datas[1]);
					removeBtnLoading('form_signaler',btn_text);
					return false;
				}
				
				return false;
			}
			}).message;		
			return false; 	
		 }
	});		
	
	// Click sur les filtres sur page secteur - Matomo
	$( "body" ).delegate( "#les_metiers .filtres", "click", function(event)
	{
		displayLoader();
		
		event.preventDefault();	
		
		var url 			= $(this).attr('href');
		var secteur_name 	= $(this).attr('title');
		var tag_name 		= $('#current_matomo_secteur').val();
		
		window._mtm = window._mtm || [];
		window._mtm.push({
			'event': 'choix-filtre-centre-interet-metier',
			'typeCompte': ''+ $('#matomo_current_user_profil').val() +'',
			'secteur_name': ''+ secteur_name +'',
			'tag_name': ''+ tag_name +'',
		});
		
		window.location.href=url;
	});
	
	// Modal favoris Non loggué
	$('#modal_warning_ajout_favoris').on('shown.bs.modal', function (event)
	{
		var button = $(event.relatedTarget)
		$quoi = button.data('quoi');
		$redir = button.data('redir');
		
		$texte = "pour participer !";	
		
		if ($quoi =='user')
		{
			$texte = "pour envoyer un message !";		
			$join = 'register='+$redir;
		}
		
		if ($quoi =='metier')
		{
			$texte = "pour ajouter des métiers en favori !";		
			$join = 'register='+$redir;
		}
		
		if ($quoi =='groupe')
		{
			$texte = "ou t\'inscrire pour rejoindre un groupe !";	
			$join = 'g='+button.data('id');
			
			$('#ajout_favoris').html('Connectez-vous ou inscrivez-vous pour rejoindre le groupe !');
			
			$('#modal_favoris_connect_link').attr('href', '/connexion?redir='+$redir);
			$('#modal_favoris_register_link').attr('href', '/inscription-jeune?'+$join);
			$('#modal_favoris_register_link').html('Inscription jeune');
			
			$('.more_from_modal_favoris').remove();
			$('#modal_favoris_connect_link').after('<div class="more_from_modal_favoris clear"><br /></div>');
			$('#modal_favoris_register_link').after('<a href="/inscription-pro?'+$join+'" class="btn btn-sm btn_blue_circle shadow mr-2 more_from_modal_favoris">Inscription pro</a>');
			
			return;
		}
				
		if ($quoi =='groupe_comment')
		{
			$texte = "ou t\'inscrire pour commenter !";	
			$join = 'g='+button.data('id');
		}
		
		if ($quoi =='entreprise')
		{
			$texte = "pour ajouter des enteprises en favori !";	
			$join = 'e='+button.data('id');	
		}
		
		if ($quoi =='ecole')
		{
			$texte = "pour ajouter des écoles en favori !";	
			$join = 'e='+button.data('id');	
		}
		
		if ($quoi =='stage')
		{
			$texte = "pour postuler à des offres de stage ou d'alternance !";	
			$join = 's='+button.data('id');	
		}
		
		$('#modal_favoris_texte').html($texte);
		$('#modal_favoris_connect_link').attr('href', '/connexion?redir='+$redir);
		$('#modal_favoris_register_link').attr('href', '/inscription-jeune?'+$join);
	});
	
	
	// Click target blank dans full_post
	/*$("#full_post a").click(function(event)
	{
		event.preventDefault();
		if ($(this).attr('target') == '_blank')
		{
			window.open($(this).attr('href'),$(this).attr('title'), 'width=800, height=600');
		} else
		{
			window.location.href=$(this).attr('href');
		}
		return false;
	});*/
	


	// Scroll top
	$(window).scroll(function(){
		var h = $('body').height();
		var y = $(window).scrollTop();
		if( y > (h*.05)){
			$(".return_top_page").fadeIn("slow");
		} else {
			$('.return_top_page').fadeOut('slow');
		}
	});
	
	// Retire contenu pour engines
	$('.hide_for_engine').remove();
	
	// Chnage placeholder main search
	$( "#form_menu_search #communautes" ).change(function(event)
	{
		$communaute = $("#form_menu_search #communautes option:selected").text();
		
		$placeholder = 'Que cherches tu ?';
		if ($communaute == 'Ecoles')
		{
			$placeholder  = 'Tape le nom d\'une école';	
		} else if ($communaute == 'Entreprises')
		{
			$placeholder  = 'Tape le nom d\'une entreprise';	
		} else if ($communaute == 'Métiers')
		{
			$placeholder  = 'Tape le nom d\'un métier';	
		} else if ($communaute == 'Membres')
		{
			$placeholder  = 'Tape le nom d\'un métier, d\'une école, d\'une formation';
		} else if ($communaute == 'Stages')
		{
			$placeholder  = 'Tape le nom d\'un métier, d\'une entreprise';
		} else if ($communaute == 'Catégorie')
		{
			$placeholder  = 'Tape le nom d\'un métier, d\'une école, d\'une formation';
		}

		$('#form_menu_search #q').attr('placeholder' , $placeholder);
	});
	
	
	// Open video home
	$( "body" ).delegate( ".openVideoHome", "click", function( event )
	{
		openVideoHome();
	});
	
	
	// Quitter  e mentorat
	$( "body" ).delegate( ".stopEmentorat", "click", function( event )
	{
		event.preventDefault();	
		alertify.set({ labels: {
		    ok     : "Ok",
		    cancel : "Annuler"
		} });	
		alertify.confirm("Merci de confirmer votre demande de quitter le programme de mentorat <br /> (opération définitive) ?", function (e) {
		if (e)
			{
				$.ajax({
					type: 'POST',
					processData: true,
					url: ROOT_URL+'services/user/user.php',
					data: 'action=stop_ementor',
					success: function(message){						
						var datas 	= message.split('|');							
						if (datas[0] =="ok") 
						{	
							alertify.success('Choix modifié !');
							window.location.href=ROOT_URL+'mon-compte';
						}
						return false;
					}
				}).message;				
				return false; 			
			}
		});
		
				
	});
	

	function submitFormSearch()
	{
		// 
		$url_search = $("#form_menu_search #communautes").val();
	
		if ($url_search == '')
		{
			alertify.error('Merci de choisir une catégorie !');
			return false;
		}
	
		displayLoader();
	
	
		$(".filtre").each(function()
		{
			if ( ($(this).attr('name') != "profil") && ($(this).val() != '') )
			{				
				$("#form_menu_search").append('<input type="text" name="'+$(this).attr('name')+'" value="'+$(this).val()+'" />');	
			}
		
		});
	
		$redirect = 0;	
		$countFiltre = $(".filtre").length;

		$q = $("input[name*='q']").val();
		if ($q == '')
		{
			if ($countFiltre == 0)
			{
				$redirect = 1;
			}
			$("input[name*='q']").val('').prop('disabled', true);
		}		
	
		// quel profil => membres
		if ($url_search == "recherche-interne/membres/tous")
		{
			if ($('#profil').length > 0)
			{
				$profil = $('#profil').val();
				if ($profil != 'tous')
				{
					$url_search = 'recherche-interne/membres/'+$profil;
				}		
			} else
			{
				$url_search = 'recherche-interne/membres/tous';
			}
		
		}
	
		// Type de stages
		if ($url_search.indexOf("stages") >= 0)
		{
	
			if ($('#url_type_stage').length > 0)
			{
				$( "#form_menu_search #communautes option:selected" ).val(''+$('#url_type_stage').val()+'');
				$url_search = $('#url_type_stage').val();
			}
		
			$search_entreprise = $('#ajax_entreprise_stage').val();
		
			// Matomo
			window._mtm = window._mtm || [];
			window._mtm.push({
				'event': 'filtreOffreStageAlternance',
				'recherche': $('#q').val(),
				'contrat': $('#filtres #type').val(),
				'domaine': ''+ $('#filtres #secteur').val() +'',
				'entreprise': ''+ $search_entreprise +'',
				'localisation': ''+ $('#filtres #loc').val() +'',
			});	
		
		}
	
		// Moteur membres JEUNE - matomo
		if ($url_search.indexOf("membres/jeune") >= 0)
		{
			$search_ecole = $('#ajax_ecole').val();
			if ($('#search_ecole').length > 0)
			{
				$search_ecole = $('#search_ecole').val();	
			}
		
			$search_formation = $('#ajax_formation').val();
			if ($('#search_formation').length > 0)
			{
				$search_formation = $('#search_formation').val();	
			}

			window._mtm = window._mtm || [];
			window._mtm.push({
				'event': 'filtreMembre',
				'recherche': $('#q').val(),
				'membre': ''+ $('#filtres #profil').val() +'',
				'ecole': ''+ $search_ecole +'',			
				'formation': ''+ $search_formation +'',
				'localisation': ''+ $('#filtres #loc').val() +''
			});		
		}
	
		// Moteur membres PRO - matomo
		if ($url_search.indexOf("membres/pro") >= 0)
		{
			$search_entreprise = $('#ajax_entreprise').val();
			if ($('#search_entreprise').length > 0)
			{
				$search_entreprise = $('#search_entreprise').val();	
			}
		
			window._mtm = window._mtm || [];
			window._mtm.push({
				'event': 'filtreMembre',
				'recherche': $('#q').val(),
				'membre': ''+ $('#filtres #profil').val() +'',
				'secteur': ''+ $('#filtres #secteur').val() +'',
				'metier': ''+ $('#filtres #metier').val() +'',
				'entreprise': ''+ $search_entreprise +'',
				'localisation': ''+ $('#filtres #loc').val() +''
			});		
		}
	
	
		// Moteur membres - matomo
		if ($url_search.indexOf("membres/tous") >= 0)
		{
			$search_entreprise = $('#ajax_entreprise').val();
			if ($('#search_entreprise').length > 0)
			{
				$search_entreprise = $('#search_entreprise').val();	
			}
		
			$search_ecole = $('#ajax_ecole').val();
			if ($('#search_ecole').length > 0)
			{
				$search_ecole = $('#search_ecole').val();	
			}
		
			$search_formation = $('#ajax_formation').val();
			if ($('#search_formation').length > 0)
			{
				$search_formation = $('#search_formation').val();	
			}

			window._mtm = window._mtm || [];
			window._mtm.push({
				'event': 'filtreMembre',
				'recherche': $('#q').val(),
				'membre': ''+ $('#filtres #profil').val() +'',
				'secteur': ''+ $('#filtres #secteur').val() +'',
				'metier': ''+ $('#filtres #metier').val() +'',
				'entreprise': ''+ $search_entreprise +'',
				'ecole': ''+ $search_ecole +'',			
				'formation': ''+ $search_formation +'',
				'localisation': ''+ $('#filtres #loc').val() +''
			});		
		}
	
		// Moteur entreprises - matomo
		if ($url_search.indexOf("entreprises") >= 0)
		{
			window._mtm = window._mtm || [];
			window._mtm.push({
				'event': 'filtreEntreprise',
				'recherche': $('#q').val(),
				'domaine': ''+ $('#filtres #secteur').val() +'',
				'localisation': ''+ $('#filtres #loc').val() +''
			});		
		}
	
		// Moteur ecoles - matomo
		if ($url_search.indexOf("ecoles") >= 0)
		{
			window._mtm = window._mtm || [];
			window._mtm.push({
				'event': 'filtreEcole',
				'recherche': $('#q').val(),
				'niveau': $('#filtres #type').val(),
				'localisation': ''+ $('#filtres #loc').val() +''
			});		
		}
	
		// Moteur metiers - matomo
		if ($url_search.indexOf("metiers") >= 0)
		{
			window._mtm = window._mtm || [];
			window._mtm.push({
				'event': 'filtreMetier',
				'recherche': $('#q').val(),
				'domaine': ''+ $('#filtres #secteur').val() +''
			});		
		}
	
		$('#form_menu_search').attr('action', '/'+$url_search);
	
		if ($redirect == 1)
		{
			window.location.href=$url_search;
			return false;
		}
	
		$("#form_menu_search").submit();
	
	}
	

	function displayLoader()
	{
		$('footer').after('<div class="loader">Loading&#8230;</div>');
	}
	
// END DOM	
});	
// END DOM	

// renvois du lien d'activation
function resend_form() 
{
	var lemail = $("#form_connection #email").val();
	
	if (lemail == "") {
		alert('Pas d email ....');
		return false;
	}

	$.ajax({
		type: 'POST',
		processData: true,
		url: ROOT_URL+'services/user/user.php',
		data: "action=resend_activation&email="+lemail,
		success: function(message){
			
			var datas 		= message.split('|');
			
			if (datas[0] == "nok")
			{
				alert('Erreur '+datas[1]);
				return false;
			}
			
			if (datas[0] == "ok")
			{
				
				if (datas[1] == 'compte_deja_valide')
				{
					$('#error_msg').html('<div class="alert alert-success"><b>Ce compte est déja validé ...</b></div>');
					return false;
				}
				
				if (datas[1] == 'no_user')
				{
					$('#error_msg').html('<div class="alert alert-danger"><b>Pas de compte avec cet email</b><br/>Merci de vérifier votre adresse email.</div>');
					return false;
				}
				$('#error_msg').html('<div class="alert alert-success"><b>Merci ...</b><br />Nouveau lien d\'activation envoyé sur '+lemail+'</div>');
				return false;
			}

			
			return false;
		}
	}).message;		
	return false; 				

}	

// Fonction de lancement de la pop signalement des post
function launch_signaler_posts(id)
{
	$('#open_posts_panel_signaler').attr('data-id', id);
	$('#open_posts_panel_signaler').click();
}

function returnDateForPicker(queryDate,small) 
{
	queryDate = '01-'+queryDate;
	queryDate = queryDate.replace("/", "-"); 

	var datas 		= queryDate.split('-');

	var madate = datas[2]+'-'+datas[1]+'-'+datas[0];

    dateParts = madate.match(/(\d+)/g)
    realDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);  	
	//console.log(realDate);
	return realDate;
}	

function loadCurrentConversationWithUser()
{
	return;
}



jQuery( window ).resize(function($){
	resizeSidePanel();
});	

/* Redimensionne side panel */
function resizeSidePanel()
{
	var largeur = jQuery( window ).width();
	if (largeur < 700)
	{
		$('.side_panels').css('width', '100%');
	} else {
		$('.side_panels').css('width', '50%');
	}
}


// ADd bouton loading
function addBtnLoading($div,$texte)
{
	$("#"+$div+" button[type=submit]").html('<span class="loading">'+$texte+' <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span></span>');
}

// Remove bouton loading
function removeBtnLoading($div,$texte)
{
	$("#"+$div+" button[type=submit]").html($texte);
}

// Validation du mot de passe
function validatePass(pass)
{ 
    var str = pass; 
	
	$('.pass_mention').remove();
	
    if (str.match( /[0-9]/g) && 
            str.match( /[A-Z]/g) && 
            str.match(/[a-z]/g) &&          
            str.length >= 8) 
	{
		$('.label_pass').removeClass('is_on_error');
		return 'ok|<p class="pass_mention small" style="color:green">Mot de passe fort</p>';
		
	} else
	{
		
		var msgPerso = '';
	
		if (!str.match( /[0-9]/g))
		{
			msgPerso += 'Un chiffre minimum<br>';
		}
		if (!str.match( /[A-Z]/g))
		{
			msgPerso += 'Il manque une majuscule<br>\r\n';
		}
		if (!str.match( /[a-z]/g))
		{
			msgPerso += 'Une minuscule minimum<br>\r\n';
		}
		if (str.length < 9)
		{
			msgPerso += 'Trop court, 8 caractères minimum<br>';
		}
		
		/*
		  str.match( /[^a-zA-Z\d]/g) &&
		if (!str.match( /[^a-zA-Z\d]/g))
		{
			msgPerso += '<br>Un caractères spécial';
		}*/
		
		return 'nok|<p class="pass_mention small" style="color:red">'+ msgPerso +'</p>';
	}   
}

// Erreur js
function recoverError($errors)
{
	var datas 		= $errors.split('|');
	if (datas[0] != 'nok')
	{
		return true;
	}
	if (datas[1] == 'logout')
	{
		window.location.href=ROOT_URL+"deconnection";
		return false;
	}
	if ((datas[1] == 'invalid_token') || (datas[1] == 'token'))
	{
		setTimeout(function(){
			window.location.reload();
		}, 1500);		
		return false;
	}
}

// Launch select2
function goSelect2(div)
{
	$('select').select2({
		theme: 'bootstrap4',
	});	
}

// Chargement des secteurs d une entreprise
function loadSecteursEntreprise(id)
{
	$.ajax({
		type: 'POST',
		processData: true,
		url: ROOT_URL+'services/secteur/secteur.php',
		data: 'action=getAllSecteursFromIdSociete&id='+id,
		success: function(message)
		{
			if (message != "nop")
			{
				$('#liste_secteurs_societe #idsecteur_societe').html(message);
				//$('#liste_secteurs_societe').show();		
			}
		}
	}).message;	
}

// Chargement des secteurs d un métier
function loadSecteursMetier(id,format="")
{
	$.ajax({
		type: 'POST',
		processData: true,
		url: ROOT_URL+'services/secteur/secteur.php',
		data: 'action=getAllSecteursFromIdMetier&id='+id+'&format='+format,
		success: function(message)
		{
			var datas 	= message.split('|');
			if (datas[0] =="nok")
			{
				alertify.error('Une erreur s\'est produite : '+ datas[1] +'...');
				return false;
			}
			
			if (format != '')
			{
				if (format == 'json')
				{
					$nbr = JSON.parse(datas[1]).length;
			
					$return = $selected = '';
			
					if (id == "__ADD__")
					{
						$return += '<option value="" selected>Renseigner le secteur d\'activité de votre métier *</option>';	
					}
			
					$.each(JSON.parse(datas[1]), function(i, item)
					{
						if (id != "__ADD__")
						{
							if (i == 0) { $selected = 'selected'; }
						}
				
						$return += '<option value="'+item.id+'" '+$selected+'>'+item.titre+'</option>';
					});
				}
			} else
			{
				$return = '';
				if (id == "__ADD__")
				{
					$return += '<option value="" selected>Renseigner le secteur d\'activité de votre métier *</option>';	
				}
				
				$return += datas[1];
			}
			
			$('#idsecteur_metier').html(''+$return+'');
			
		}
		
	}).message;	
}

// Chargement du secteur principal
function loadSecteursMetierIdOnly(id)
{
	$.ajax({
		type: 'POST',
		processData: true,
		url: ROOT_URL+'services/secteur/secteur.php',
		data: 'action=getMainSecteurIdFromMetier&id='+id,
		success: function(message)
		{
			$('#idsecteur_metier').remove();
			$('#idmetier').after('<input type="hidden" id="idsecteur_metier" name="idsecteur_metier" value="'+message+'" />');
		}
	}).message;	
}


// Chargement de tous les secteurs
function loadAllSecteurs()
{
	$.ajax({
		type: 'POST',
		processData: true,
		url: ROOT_URL+'services/secteur/secteur.php',
		data: 'action=getAllSecteursForSelect',
		success: function(message){

			if (message !="nop") {
				$('#liste_secteurs_societe #idsecteur_societe').html(message);
				$('#liste_secteurs_societe').show();		
			}
		}
	}).message;	
}

function openVideoHome() { $("#myVideo").css("width","100%"); }

function closeVideoHome() { $("#myVideo").css('width','0%'); }

function saveNotificationPlayerId(playerID,playerRegisterStatus="")
{
	/*if (stopCallingForPlayerID_js == 'stop')
	{
		return false;
	}*/
	
	$.ajax({
		type: 'POST',
		processData: true,
		url: ROOT_URL+'services/user/user.php',
		data: 'action=save_notification_player_id&playerID='+playerID+'&playerRegisterStatus='+playerRegisterStatus,
		success: function(message)
		{
		}
	}).message;	
}

function isBreakpoint() {
    return $('.navbar-toggler').is(':visible');
}
