/* /js/jquery/jquery.plugin.complete.js */
/*
	JQuery Complete v1.9
	Copyright (c) 2014-2022 Seg
	Licensed under the MIT license

	This plugin needs jquery library (tested at least with 1.10.1).
	jQuery: http://code.jquery.com/jquery-1.10.1.min.js

	Option:
	call:       Three otpions:
	            1. it can be an url string like "/call.php?q=%s" where '%s' is the token automaticaly replaced by the keyword.
	            2. it can be a javascript array like "obj", where the variable obj is initialized like:
	               var obj=[]; obj['key']=''; obj['list']=[{label:'a'},...]
	            3. it can be a callback function like function(keyword,response) {return <The result>}, where:
	               - keyword: the current keyword
	               - response: function name to call to send result: response(result) {}
	               -> The result can be true if you call the response function like above
	                  The result can be an Array like the 2nd possibilitie
	                  The result can be a string which is the final called URL by the plugin. Like: return '/call.php?q='+encodeURIComponent(keyword)
	onselect:   callback function(data,this) {}. Hook to a function when an item is selected:
	            - data: data of the selected item
	            - this: this of the input
	onchange:   callback function(keyword,listData) {}. Hook to a function when key is pressed:
	            - keyword: the current keyword
	            - listData: array of current items list
	            - this: this of the input
	oninit:     callback function(keyword,listData) {}. Hook to a function each time the list change
	            - keyword: the current keyword
	            - listData: array of current items list
	            - this: this of the input
	onvalidate: callBack function(keyword,curIdx,listData,event,this) {return curIdx or -1}. To do something when Enter key is pressed,
	            and to set which item you want to select anyway:
	            - keyword: the current keyword
	            - curIdx: index of the current selected item (-1 if nothing)
	            - listData: array of current items list
	            - event: object Event
	            - this: this of the input
	            Also, this option can be:
	            - 'auto' if you want auto select the first item when none is selected
	            - 'auto_submit': like auto, but with submit
	            - 'close': just close the list. No submit.
	            - 'close_submit': close the list and submit
	ondraw:     callback function(el,item,this) {...; return trueOrfalse}
	            - "el": is the element to draw.
	            - 'item": is the data of the element
	            - this: this of the input
	            Return true if the element must be in the list, or false if not.
	            With this option, you can add a class to the element, or decide to draw or not draw the element in the final list.
	cachedurat: set max duration of the inner cache (default: 1 min). 0=no cache.
	setshow:    set the slide speed to open the list box (défault: 50 ms). The value can be a function like function(box) {box.show();}
	sethide:    set the slide speed to close the list box (default: 50 ms). The value can be a function like function(box) {box.hide();}
	lag:        set delay before the server call when changing text zone (default: 50 ms).
	charmin:    minimum number of characters before to send the request (default: 1)
	classover:  add a class name on a focused item.
	classlist:  add a class name on the global 'ul' created by the list. If this option is set, you must set all CSS needed to display
	            the list.
	height:     the height of the list when classlist option is not set. (default: 200px)
	width:      the width of the list when classlist option is not set. (default: like the input zone (or object zone if object option is used))
	            Note: if the classlist is defined, you must set 'width:default', if you want a list width like the
	            input width. Otherwise, you will set the width into the css file.
	object:     the object on which the list is to hang. (default: the input)

	Server side [PHP]: (using option call:'/getlist.php?q=%s')
	getlist.php code:
	$keywords=iconv("UTF-8","CP1252//TRANSLIT",$_GET['q']);
	header('Content-Type: application/json');
	exit(json_encode(array(
		'key'=>$keywords,
		'list'=>array(
			array('label'=>utf8_encode('a: '.$keywords)),
			array('label'=>utf8_encode('b: '.$keywords))
		)
	)));
*/
(function($)
{
	$.complete=function(obj,option)
	{
		var opt=option || {};
		var zone=$(obj);

		var resultList=new Array,cur=-1,listOver=false;
		var cache=new Array,cacheDuration=60,lag=50,setHide=50,setShow=50,charMin=1;
		var timeout=null,xhr=null,isDefaultWidth=false;
		var objBase=typeof opt.object!='undefined'?$(opt.object):zone;
		var list,color,bgColor;

		var response=function(result)
		{
			if(!result['list'].length) zone.hideList();

			initList(result['list']);
			if(cacheDuration>0) setCache(result['key'],result);
			if(getCount()>0) zone.showList();
		};

		var select=function(idx)
		{
			var isClose=true;

			if(typeof(resultList[idx])!='undefined')
			{
				cur=idx;
				if(typeof opt.onselect=='function') isClose=opt.onselect(resultList[idx],zone);
				else zone.val(resultList[idx].label);
				zone.setItem(idx,false);
				if(isClose || typeof isClose=='undefined') zone.hideList();
			}

			return isClose;
		};

		var initList=function(data)
		{
			var html='';

			resultList=data;
			list.empty();
			for(idx in resultList)
			{
				var item=resultList[idx];
				var li=$('<li name="'+idx+'">'+item.label+'</li>');
				var isAppend=typeof opt.ondraw=='function'?opt.ondraw(li,item,zone):true;
				if(isAppend) list.append(li);
			}

			list.children('li').hover(function()
			{
				removeStyleOver();
				addStyleOver(this);
			},function()
			{
				removeStyleOver();
			}).click(function()
			{
				select($(this).attr('name'));
			});

			if(typeof opt.oninit=='function') opt.oninit(zone.val(),resultList,zone);
		};

		var addStyleOver=function(item)
		{
			if(typeof opt.classover!='undefined') $(item).addClass(opt.classover);
			else $(item).css({'color':bgColor,'background-color':color});
			$(item).attr('over',true);
		};

		var removeStyleOver=function()
		{
			var item=list.find('li[over=true]');
			if(typeof opt.classover!='undefined') $(item).removeClass(opt.classover);
			else $(item).removeAttr('style')
			$(item).removeAttr('over');
		};

		var getCount=function()
		{
			return list.children('li').length;
		};

		var calcItemIdx=function(idx)
		{
			idx=parseInt(idx);
			if(idx<0) idx=0;
			else
			{
				var count=getCount();
				if(idx>=count) idx=count-1;
			}
			return idx;
		};

		var getCurItem=function()
		{
			var idx=-1;
			var itemOver=list.find('li[over=true]:first');
			if(itemOver.length) idx=parseInt(itemOver.attr('name'));
			return idx;
		};

		var setPos=function()
		{
			var marginTop=parseInt(objBase.css('margin-top')),marginLeft=parseInt(objBase.css('margin-left'));
			if(isNaN(marginTop)) marginTop=0;
			if(isNaN(marginLeft)) marginLeft=0;
			var top=objBase.position().top+objBase.outerHeight()+marginTop;
			var left=objBase.position().left+marginLeft;
			list.css({'left':left+'px','top':top+'px'});
			if(isDefaultWidth) list.css('width',objBase.outerWidth()+'px');
		};

		var setCache=function(key,data)
		{
			cache[key]={timeout:getTimeSec()+cacheDuration,data:data};
		};

		var getCache=function(key)
		{
			if(typeof(cache[key])!='undefined')
			{
				if(cache[key].timeout>=getTimeSec()) return cache[key].data;
				else delete cache[key];
			}
			return null;
		};

		var getTimeSec=function()
		{
			return new Date().getTime()/1000;
		};

		var call=function(keyword)
		{
			if(typeof opt.onchange=='function') opt.onchange(zone.val(),resultList,zone);

			clearTimeout(timeout);
			if(xhr) {xhr.abort(); xhr=null;}
			if(keyword.length>=charMin)
			{
				var tmp=getCache(keyword);
				if(!tmp) timeout=setTimeout(function(){
					var link=opt.call;
					if(typeof opt.call=='function')
					{
						link=opt.call(keyword,response);
						if(typeof link!='string') response(link);
					}
					else if(typeof opt.call!='string') response(opt.call);
					else link=link.replace(/%s/i,encodeURIComponent(keyword));
					if(typeof link=='string') xhr=$.ajax({url:link,dataType:'json',success:response});
				},keyword.length>=charMin+1?lag:0);
				else response(tmp);
			} else zone.clean();
		};

		zone.keydown(function(key)
		{
			var vis=list.is(':visible');
			var idx=getCurItem(),stop=true,curkey=key.which;

			switch(curkey)
			{
				case 38: //key up
					if(vis) zone.setItem(calcItemIdx(idx-1),true);
					break;

				case 40: //key down
					if(vis) zone.setItem(calcItemIdx(idx+1),true);
					break;

				case 9:
				case 13:
					if(curkey==9) stop=false;
					if(typeof(opt.onvalidate)!='undefined')
					{
						if(opt.onvalidate=='auto') {if(idx<0) idx=0;}
						else if(opt.onvalidate=='auto_submit') {zone.hideList(); stop=false; if(idx<0) idx=0;}
						else if(opt.onvalidate=='close') zone.hideList();
						else if(opt.onvalidate=='close_submit') {zone.hideList(); stop=false;}
						else idx=opt.onvalidate(zone.val(),idx,resultList,key,zone);
					}
					select(idx);
					break;

				default:
					stop=false;
					break;
			}

			if(stop)
			{
				key.preventDefault();
				key.stopImmediatePropagation();
			}
		});

		zone.keyup(function(key)
		{
			var idx=getCurItem();

			switch(key.which)
			{
				case 38: //key up
				case 40: //key down
					zone.showList();
					break;

				case 13: //Enter
					break;

				case 27: //Esc
					zone.hideList();
					break;

				default:
					call(zone.val());
					break;
			}
		});

		zone.click(function()
		{
			if(list.is(':visible')) zone.hideList();
			else
			{
				//call(zone.val());
				zone.showList();
			}
		});

		zone.blur(function(event)
		{
			if(!listOver) zone.hideList();
		});

		//PUBLIC API
		zone.clean=function()
		{
			zone.unselect();
			zone.hideList();
			initList(new Array);
		};

		zone.hideList=function()
		{
			if(list.is(':visible'))
			{
				if(typeof setHide=='function') setHide(list); else list.slideUp(setHide);
			}
		};

		zone.showList=function()
		{
			if(!list.is(':visible') && getCount()>0)
			{
				setPos();
				listOver=false;
				if(typeof setShow=='function') setShow(list); else list.slideDown(setShow);
				if(cur>=0) zone.setItem(cur,false);
			}
		};

		zone.unselect=function() {
			cur=-1;
		};

		zone.setItem=function(idx,isSetPos)
		{
			removeStyleOver();
			if(idx>=0)
			{
				var item=list.find('li[name='+idx+']');
				addStyleOver(item);

				if(isSetPos)
				{
					var itemL=item.offset().top;
					var limitL=list.offset().top;
					var limitH=list.offset().top+list.height()-item.height();
					if(itemL<limitL) list.scrollTop(itemL-limitL+list.scrollTop());
					else if(itemL>limitH) list.scrollTop(itemL-limitH+list.scrollTop());
				}
			}
		};

		//Object init
		if(typeof opt.cachedurat!='undefined') cacheDuration=opt.cachedurat;
		if(typeof opt.lag!='undefined') lag=opt.lag;
		if(typeof opt.sethide!='undefined') setHide=opt.sethide;
		if(typeof opt.setshow!='undefined') setShow=opt.setshow;
		if(typeof opt.charmin!='undefined') charMin=opt.charmin;

		color=zone.css('color');
		bgColor=zone.css('background-color');
		list=$(document.createElement('ul'));
		list.css({
			'position':'absolute',
			'overflow':'auto',
			'cursor':'pointer',
			'display':'none'
		}).hover(function()
		{
			listOver=true;
		},function()
		{
			listOver=false;
		});

		$(window).resize(function(){
			setPos();
		});

		if(typeof opt.classlist!='undefined')
		{
			if(typeof opt.width!='undefined' && opt.width=='default') isDefaultWidth=true;
			list.addClass(opt.classlist);
		}
		else
		{
			if(typeof opt.width=='undefined') isDefaultWidth=true;
			list.css({
				'list-style-type':'none',
				'padding':0,
				'margin':0,
				'text-align':'left',
				'font-weight':'normal',
				'border':'1px solid '+objBase.css('border-color'),
				'color':objBase.css('color'),
				'background-color':bgColor,
				'width':(!isDefaultWidth?opt.width:objBase.outerWidth()+'px'),
				'max-height':(typeof opt.height!='undefined'?opt.height:'200px'),
				'z-index':1000
			});
		}

		zone.attr('autocomplete','off').after(list);
		initList(new Array);

		zone.data('complete',zone);

		return zone;
	}

	$.fn.complete=function(option)
	{
		var opt=option || {};

		if(this.length==0) throw 'Exception jquery complete: target not exists';

		var obj=$(this);
		this.each(function(){
			obj=new $.complete(this,opt);
		});

		return obj;
	}
})(jQuery);

/* /js/index.js */
function initCompletion(lang) {
	$("#metiers_acceptables_1, #metiers_acceptables_2, #metiers_acceptables_3, #metiers_exerces_1, #metiers_exerces_2, #metiers_exerces_3").complete({
		call:"/completion-isco?v=1&langue="+lang+"&q=%s",
		onvalidate:"close",
		onselect:function(result,zone) {
			var id=zone.prop('id');
			var iscoId=id.replace(/^(.*)_(\d+)/,"$1_isco$2");
			var label=lang=="ukr"?result.value.labeluk:result.value.labelfr;

			$(`#${id}`).val(label);
			$(`#${iscoId}`).val(result.value.isco);
			$(`#${id}_trad_fra`).val(result.value.labelfr);
			$(`#${id}_trad_ukr`).val(result.value.labeluk);
		},
		onchange:function(k,l,zone) {
			var id=zone.prop('id');
			var iscoId=id.replace(/^(.*)_(\d+)/,"$1_isco$2");
			$(`#${iscoId}`).val("");
		},
		charmin:3,
		classover:"over",
		classlist:"isco-completion",
		width: 'default',
		lag: 300
	});
}

$(document).ready(function() {
	$("[data-showif]").each(function(data) {
		var showif=$(this).data("showif");
		var who=showif.replace(/^(.*?)=.*$/,"[name=$1]");
		var what=showif.replace(/^.*?=(.*)$/,"$1");
		var obj=this;
		var checked=$(who).prop('type')=="radio"?":checked":"";
		var cur=`${who}${checked}`;
		if($(cur).length)
			if($(cur).val().match(new RegExp(what)))
				$(obj).show();
			else
				$(obj).hide();
		$(who).on("keyup click change",function(e) {
			if($(this).val().match(new RegExp(what)))
				$(obj).slideDown();
			else
				$(obj).slideUp();
		});
	});

	// empêche la soumission du formulaire quand l'utilisateur tappe sur Entrée
	$(window).keydown(function(event){
		if(event.keyCode == 13) {
		  event.preventDefault();
		  return false;
		}
	});

	// Permet de contourner le fonctionnement de jquery qui ne prend pas en compte les changements des champs hidden
	$("#bouton-modification").on("click", function() {
		$("#state").val("update");
		$("#form-informations").submit();
	});

	// Génère un cadre de selection des radio "checked" au moment du clic
	$("input[type=radio]").on("click",function() {
		if($(this).prop('checked')) {
			$(this).parents("div").addClass("checked");
			$(this).parents("div").parent().find("input[type=radio]").not(":checked").each(function() {
				$(this).parents("div").removeClass("checked");
			});
		} else {
			$(this).parent("div").removeClass("checked");
		}
	});

	// Génère un cadre de selection des radio "checked" au moment de l'actualisation de la page
	$("input[type=radio]:checked").each(function() {
		$(this).parents("div").addClass("checked");
	});

	// Gestion des couleurs des erreurs. Réplique la couleur sur les intitulés des champs
	//$(".error").parent().find(".label").each(function() {
	//	$(this).addClass("error");
	//});
	$(".error").parents(".question").each(function() {
		$(this).addClass("error");
	});


	// Modifie la langue dans l'action du formulaire et valide le formulaire en mode "update"
	$("#langue").on("change",function() {
		var form=$("#form-informations");
		var val=$(this).val();

		if(val=="fra") val="";

		form.attr("action","/"+val);
		form.find("#state").val("update");
		form.submit();
	});

	$("#close-success-icon").on("click", function () {
		trueHide(".success");
	});

	$("#btn_ajout_metier_exerce_1").on("click", function (e) {
		e.preventDefault();
		showMetierExerce2();
	});

	$("#btn_ajout_metier_exerce_2").on("click", function (e) {
		e.preventDefault();
		showMetierExerce3();
	});

	$("#btn_ajout_metiers_acceptables_1").on("click", function (e) {
		e.preventDefault();
		showMetierAcceptable2();
	});

	$("#btn_ajout_metiers_acceptables_2").on("click", function (e) {
		e.preventDefault();
		showMetierAcceptable3();
	});


	$(function () {
		$('[data-toggle="tooltip"]').tooltip();

		if($(".error").length) {
			// l'élement en erreur est focus
			$(".error:eq(1)").focus();
			// on scroll jusqu'au bloc de question contenant l'erreur
			$(".error:eq(1)").parents("div").get(0).scrollIntoView({ behavior: 'smooth'});
		}

		if($("#metiers_acceptables_2").val() != '') {
			showMetierAcceptable2();
		}

		if($("#metiers_acceptables_3").val() != '') {
			showMetierAcceptable2SansBouton();
			showMetierAcceptable3();
		}

		if($("#metiers_exerces_2").val() != '') {
			showMetierExerce2();
		}

		if($("#metiers_exerces_3").val() != '') {
			showMetierExerce2SansBouton();
			showMetierExerce3();
		}
	});

	function showMetierAcceptable2(){
		trueShow("#metiers_acceptables_2_div");
		trueShow("#btn_ajout_metiers_acceptables_2");
		$("#btn_ajout_metiers_acceptables_1").hide();
	}
	function showMetierAcceptable2SansBouton(){
		trueShow("#metiers_acceptables_2_div");
		$("#btn_ajout_metiers_acceptables_1").hide();
	}
	function showMetierAcceptable3(){
		trueShow("#metiers_acceptables_3_div");
		$("#btn_ajout_metiers_acceptables_2").hide();
	}
	function showMetierExerce2(){
		trueShow("#metier_exerce_2_div");
		trueShow("#btn_ajout_metier_exerce_2");
		$("#btn_ajout_metier_exerce_1").hide();
	}
	function showMetierExerce2SansBouton(){
		trueShow("#metier_exerce_2_div");
		$("#btn_ajout_metier_exerce_1").hide();
	}
	function showMetierExerce3(){
		trueShow("#metier_exerce_3_div");
		$("#btn_ajout_metier_exerce_2").hide();
	}

	// Fonctions qui permettent de surcharger les classes bootstrap (d-block, d-none) et ainsi de réellement cacher/monter ce qui doit l'être
	function trueHide(element) {
		$(element).slideUp();
	}

	function trueShow(element) {
		$(element).removeClass('d-none');
		$(element).slideDown();
	}
});

