var logInfoStar = false;
var logInfoInput = false;
var logInfoWidth = false;
var logInfoError = false;

/* Modifs accessibilité */
function addAlertMsg(){
	if($(".form-core form >div.alertMsg",document).length==0)
	{
		if($(".form-core form .interview-progress-parent",document).length==0)
			$(".form-core form",document).prepend("<div role='alert' class='alertMsg visuallyhidden'></div>");
		else
			$("<div role='alert' class='alertMsg visuallyhidden'></div>").insertAfter(".form-core form .interview-progress-parent");
	}

	$(".form-core form .alertMsg",document).hide();
	$(".form-core form .alertMsg",document).html("");
	var nbErrors = 0;

	$(".question-UNIQUE,.question-TEXTE,.question-MULTIPLE").each(function(){
		if($("p.error",this).length>=1)
		{
			var errorOn = false;
			//var idErrorP = $("p.error",this).attr("id");

			if($("p.error.errorFR",this).length==1)
				errorOn = $("p.error.errorFR",this).css("display") != "none";
			else
				errorOn =$("p.error",this).css("display") != "none";

			if(errorOn){
				nbErrors++;
				$(".form-core form .alertMsg",document).append("<a href='#"+ $(this).attr("id")+"'>Erreur sur la question <span style='font-style:italic'>« "+$(".question-heading-parent",this).text().trim()+" »</span></a>");
			}
		}
	});

	$(".question-GROUPE tbody").each(function(){

		$("p.error",this).each(function(){
			if($(this).css("display") != "none"){
				nbErrors++;
				var text = $(".question-heading-parent",$(this).parents(".question-GROUPE")).text().trim()+ " " +$("tr[role='radiogroup']",$(this).parents("tbody")).attr("aria-label").trim();
				$(".form-core form .alertMsg",document).append("<a href='#"+$(this).parents("tbody").attr("id")+"'>Erreur sur la question <span style='font-style:italic'>« "+ text +" »</span></a>");

			}
		});

	});

	if(nbErrors>0){
		$(".form-core form .alertMsg",document).show();
		$(".form-core form .alertMsg >a:first-child",document).focus();
	}
}

function addAriaInfos(){

	$(".question-GROUPE tbody,.question-UNIQUE,.question-TEXTE,.question-MULTIPLE").each(function(){
		if($("p.error",this).length>=1)
		{
			var errorOn =$("p.error",this).css("display") != "none";
			var idErrorP = $("p.error",this).attr("id");

			if($("p.error.errorFR",this).length==1){
				errorOn = $("p.error.errorFR",this).css("display") != "none";
				idErrorP = $("p.error.errorFR",this).attr("id");
			}

			if(errorOn){
				$("textarea,select,input",this).attr("aria-describedby", idErrorP);
				$("textarea",this).attr("aria-invalid","true");
			}
			else{
				$("textarea,select,input",this).removeAttr("aria-describedby");
				$("textarea",this).removeAttr("aria-invalid");
			}
		}

		var isMandatoryQuestion = $("span.mandatory-icon",this).length>0;
		var isQuestionGroup = $(this).attr("class").indexOf("question-GROUPE")>-1;
		if(isMandatoryQuestion)
				$("textarea,select,input[role!='presentation']",this).attr("aria-required","true");

	});

	$(".question-TEXTE").each(function(){
		$("textarea",this).attr("aria-label",$(".question-heading-parent",this).text().trim());
	});

	$(".question-UNIQUE .question-choices-parent table,.question-MULTIPLE .question-choices-parent table,.question-GROUPE .questions-table-parent table,table.element-side-container").each(function(){
		$(this).attr("role","presentation");
	});

	$(".question-GROUPE table.questions-table-container tbody tr:first-child").each(function(){
		$(this).attr("role","radiogroup");
		$(this).attr("aria-label",$(".criteria-name",this).text().trim());
	});

	$(".question-UNIQUE:not(.cursorRadio) table.question-choices-horiz tr:not(.question-choices-label),.question-UNIQUE:not(.cursorRadio) ul.question-choices").each(function(){
		$(this).attr("role","radiogroup");
		var question = $(this).parents(".question-UNIQUE");
		$(this).attr("aria-label",$(".question-heading-parent",question).text().trim());
	});
}

function checkAriaErrors(){
	addAriaInfos();
	$("input").change(function(){setTimeout(addAriaInfos,200);});
	$("button.button-questions-next").click(function(){setTimeout(addAriaInfos,200);setTimeout(addAlertMsg,400);});
	$("textarea.required").focusout(function(){ setTimeout(addAriaInfos,200);});
	$("textarea.required").mouseleave(function(){setTimeout(addAriaInfos,200);});
	$("input,textarea").on("input paste propertychange",function(){addAriaInfos();});
}

/***** Fix hover iPhone Bug *****/
function fixIPhoneHoverBug(){
	$("body").attr("tabIndex","0");
}

/***** Gestion des spécificités IE *****/
function getBrowserInfos() {
	var nVer = navigator.appVersion;
	var nAgt = navigator.userAgent;
	var browserName  = navigator.appName;
	var fullVersion  = ''+parseFloat(navigator.appVersion);
	var majorVersion = parseInt(navigator.appVersion,10);
	var nameOffset,verOffset,ix;
	var IE11=false;

	if ((verOffset=nAgt.indexOf("OPR/"))!=-1) {
		browserName = "Opera";
		fullVersion = nAgt.substring(verOffset+4);
	} else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
		browserName = "Opera";
		fullVersion = nAgt.substring(verOffset+6);
		if ((verOffset=nAgt.indexOf("Version"))!=-1)
			fullVersion = nAgt.substring(verOffset+8);
	} else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
		browserName = "Microsoft Internet Explorer";
		fullVersion = nAgt.substring(verOffset+5);
	} else if ((verOffset=nAgt.indexOf("Edge"))!=-1) {
		browserName = "Edge";
		fullVersion = nAgt.substring(verOffset+5);
	} else if ((verOffset=nAgt.indexOf("Trident/"))!=-1) {
		browserName = "Microsoft Internet Explorer";
		var rv = nAgt.indexOf('rv:');
        majorVersion =  parseInt(nAgt.substring(rv + 3, nAgt.indexOf('.', rv)), 10);
		IE11 = true;
	} else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
		browserName = "Chrome";
		fullVersion = nAgt.substring(verOffset+7);
	} else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
		browserName = "Safari";
		fullVersion = nAgt.substring(verOffset+7);
		if ((verOffset=nAgt.indexOf("Version"))!=-1)
			fullVersion = nAgt.substring(verOffset+8);
	} else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
		browserName = "Firefox";
		fullVersion = nAgt.substring(verOffset+8);
	} else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) {
		browserName = nAgt.substring(nameOffset,verOffset);
		fullVersion = nAgt.substring(verOffset+1);
		if (browserName.toLowerCase()==browserName.toUpperCase()) {
			browserName = navigator.appName;
		}
	}
	// trim the fullVersion string at semicolon/space if present
	if ((ix=fullVersion.indexOf(";"))!=-1)
		fullVersion=fullVersion.substring(0,ix);
	if ((ix=fullVersion.indexOf(" "))!=-1)
		fullVersion=fullVersion.substring(0,ix);

	if(!IE11){
		majorVersion = parseInt(''+fullVersion,10);
		if (isNaN(majorVersion)) {
			fullVersion  = ''+parseFloat(navigator.appVersion);
			majorVersion = parseInt(navigator.appVersion,10);
		}
	}

	if(browserName=="Microsoft Internet Explorer")
	{
		if(majorVersion<=11)
		{
			$(".accessibiliteWarning").html("Attention, le navigateur Internet Explorer ne permet pas de répondre correctement à ce questionnaire en utilisant votre clavier. Veuillez si besoin utiliser un autre navigateur.");
			$(".accessibiliteWarning").show();

			if (majorVersion <=9)
				$("body").addClass("lteI9");
		}
	}
	else if (browserName == "Chrome")
	{
		if(majorVersion<=30)
		{
			if(majorVersion<=29)
				$(".repondantWarning").show();
			else
				$(".accessibiliteWarning").show();
			$(".browserName").text("Chrome");
			$(".browserVersion").text(", version 31 minimum,");
		}
	}
	else if (browserName == "Safari")
	{
		if(majorVersion<=11)
		{
			if(majorVersion<=8)
				$(".repondantWarning").show();
			else
				$(".accessibiliteWarning").show();
			$(".browserName").text("Safari");
			$(".browserVersion").text(", version 12 minimum,");
		}
	}
}

// Fix Edge not rendering checkboxes
function ieFix() {
	$('body.ie .question-choices-column label.img-container').each(function(){
		var disp = this.style.display;
		this.style.display = 'none';
		var trick = this.offsetHeight;
		this.style.display = disp;
		$(window).resize();
	});
}

/***** Ajout de la consigne d'une question type texte ou input en tant que placeholder *****/
jQuery.support.placeholder = (function(){
	var i = document.createElement('input');
	return 'placeholder' in i;
})()


function addPlaceHolders() {
	if ($.support.placeholder) {
		// Identifier les questions concernées
		$("textarea,input[type='text']").each(function() {
			// Récupérer l'observation
			var observation = $(this).parents("div.question-TEXTE").find(".question-instructions");
			if (observation && $(observation).text().length > 0) {
				$(this).attr("placeholder", $(observation).text());
				$(observation).hide();
			}
		});
	}
}
/******************* Curseur étoiles accessible ***********************/

function cursorRadioInit() {
	$(".starCursor,.effortCursor").each(function(){
		$(this).addClass("cursorRadio");
	});

	$(".cursorRadio").each(function(){

		var isGroup = !this.classList.contains("question-UNIQUE");
		var isStarCursor = this.classList.contains("starCursor");
		var isEffortCursor = this.classList.contains("effortCursor");
		var hasNSPChoice = this.classList.contains("NSP");

		//var isSmileyCursor = this.classList.contains("smileyCursor");

		var questionGroup=$(this).parents(".question-GROUPE");
		if($("fieldset",this).length==0)
		{
			$("input[type=radio]",this).wrapAll("<fieldset></fieldset>");
			$("fieldset",this).append("<output></output>");
			var questionTitle = $(".question-heading-parent .question-heading >span:not(.mandatory-icon)" ,this).text();
			if(isGroup)
				questionTitle =  $(".question-heading-parent .question-heading ",questionGroup).text().trim()+$("td.column-criteria span.criteria-name",this).text().trim();
			$("fieldset",this).prepend("<legend class='visuallyhidden'>"+questionTitle+"</legend>");
			$(this).addClass("noSelection");
		}

		var inputs=$("input[type=radio]:not(.visuallyhidden)",this);
		var labelGroup=$("thead.header th.question-choices label.img-container span.choice-label",questionGroup);
		for(var j=0;j<inputs.length;j++){
			var el = inputs[j];

			var labelText=$(labelGroup[j]).text().trim();
			if(!isGroup)
			{
				var tableParent = $(el).parents("table.question-choices-horiz");
				var labelsTab = $("tr.question-choices-label td.question-choice-horiz span.choice-label",tableParent);
				$("span.accessibility",labelsTab).remove();
				labelText =$(labelsTab[j]).text();
			}

			var readOnlyAttr=$(el).attr("disabled")=="disabled";
			var evts='onclick="cursorRadioClick(this);" onmouseover="cursorRadioHover(this);" onmouseleave="cursorRadioLeave(this);"';
			var isAppleDevice = ((navigator.userAgent.toLowerCase().indexOf("ipad") > -1) || (navigator.userAgent.toLowerCase().indexOf("iphone") > -1) || (navigator.userAgent.toLowerCase().indexOf("ipod") > -1));
			if(isAppleDevice){
				evts='onclick="cursorRadioClick(this);"';
				$(el).parents(".cursorRadio").addClass("readOnly");
			}
			if(readOnlyAttr)
			{
				evts="";
				$(el).parents(".cursorRadio").addClass("readOnly");
			}

			if(isStarCursor)
			{
				if(!hasNSPChoice || (hasNSPChoice && j<inputs.length-1))
					$('<label class="focus-visible" for="'+$(el).attr("id")+'" index="'+j+'" total="'+inputs.length+'"'+evts+' ><span class="visuallyhidden" >'+labelText+'</span><?xml version="1.0" encoding="UTF-8"?><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50;" xml:space="preserve"><path d="M14.4,13.6l6-7.8c0.5-0.6,1-1.1,1.6-1.3c0.6-0.3,1.3-0.4,2-0.4c0.7,0,1.4,0.1,2,0.4c0.6,0.3,1.2,0.7,1.7,1.3	l6,7.8l9.1,3.1c1,0.3,1.8,0.9,2.4,1.7c0.6,0.8,0.9,1.7,0.9,2.7c0,0.5-0.1,0.9-0.2,1.4c-0.1,0.5-0.4,0.9-0.7,1.3l-5.9,8.4l0.2,8.8 c0,1.3-0.4,2.5-1.3,3.4c-0.9,0.9-2,1.4-3.3,1.4c-0.1,0-0.5,0-1.2-0.1L24.1,43l-9.6,2.7c-0.2,0.1-0.4,0.1-0.6,0.1c-0.2,0-0.4,0-0.6,0 c-1.2,0-2.3-0.5-3.3-1.4C9,43.5,8.6,42.4,8.6,41l0.2-8.9l-5.9-8.3c-0.3-0.4-0.5-0.9-0.7-1.3c-0.1-0.5-0.2-0.9-0.2-1.4 c0-1,0.3-1.9,0.8-2.7c0.6-0.8,1.3-1.4,2.3-1.8L14.4,13.6z"/></svg></label>').insertAfter($(el));
						/*$('<label class="focus-visible" for="'+$(el).attr("id")+'" index="'+j+'" total="'+inputs.length+'"'+evts+' ><span class="visuallyhidden" >'+labelText+'</span><?xml version="1.0" encoding="UTF-8"?><svg x="0px" y="0px" viewBox="0 0 50 50" style="enable-background:new 0 0 100 100;" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M36,31l2.6,16L25,39.5L11.4,47L14,31L3,19.8l15.2-2.3L25,3l6.8,14.4L47,19.8L36,31z"/></svg></label>').insertAfter($(el));*/
				else{
					$('<label class="focus-visible NSP" for="'+$(el).attr("id")+'" index="'+j+'" total="'+inputs.length+'"'+evts+' ><span class="visuallyhidden" >'+labelText+'</span><?xml version="1.0" encoding="utf-8"?><svg class="NSP" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 24 24" style="enable-background:new 0 0 24 24;" xml:space="preserve"><path d="M23,4v16c0,1.6-1.3,3-3,3H4c-1.7,0-3-1.4-3-3V4c0-1.7,1.3-3,3-3h16C21.7,1,23,2.3,23,4z"/></svg></label>').insertAfter($(el));
					//$('<label for="'+$(el).attr("id")+'" class="radiomark" index="'+j+'" total="'+inputs.length+'">Ne se Prononce pas</label>').insertAfter($(el));

				}
			}
			else if (isEffortCursor){
				if(!hasNSPChoice || (hasNSPChoice && j<inputs.length-1))
					$('<label class="focus-visible" for="'+$(el).attr("id")+'" index="'+j+'"'+evts+' ><span class="visuallyhidden" >'+labelText+'</span><?xml version="1.0" encoding="UTF-8"?><svg x="0px" y="0px" viewBox="0 0 50 50" style="enable-background:new 0 0 100 100;" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M46.9,41.3l-6.3-25.1c-0.3-1.3-1.4-2.2-2.7-2.2h-5.2c0.3-0.8,0.5-1.8,0.5-2.7C33.2,6.7,29.6,3,25,3 s-8.3,3.7-8.3,8.2c0,1,0.2,1.9,0.5,2.7h-5.1c-1.2,0-2.3,0.9-2.7,2.2L3.1,41.3c-0.7,2.9,1.3,5.7,4,5.7h35.7	C45.6,47,47.6,44.2,46.9,41.3z M25,14c-1.5,0-2.8-1.2-2.8-2.7s1.3-2.7,2.8-2.7c1.5,0,2.7,1.2,2.7,2.7S26.5,14,25,14z"/></svg></label>').insertAfter($(el));
				else
					console.log("que fait on ?");
			}

			$(el).parents("fieldset").attr("total",inputs.length);

			// Si valeur par défaut
			if($(el).attr("checked")=="checked")
			{
				$(el).parents("fieldset").attr("cursorRadioClicked",j);
				$("output",	$(el).parents(".cursorRadio")).text(labelText);
				$(el).parents(".cursorRadio").removeClass("noSelection");
			}

			$(el).on('input propertychange change',function(e){
				{
					$(this).parents(".cursorRadio").removeClass("noSelection");
					$("output",	$(this).parents(".cursorRadio")).text($("span",this.nextSibling).text());
					var currentClicked = $(this).parents("fieldset").attr("cursorRadioClicked");
					if (currentClicked != $("+ label",this).attr("index"))
						$(this).parents("fieldset").attr("cursorRadioClicked",$("+ label",this).attr("index"));

				}
			});

			$(el).addClass("visuallyhidden");
		}

	});

}

function cursorRadioClick(label){
console.log("cursor radio click");
	var attrFor=$(label).attr("for");
	var attrIndex=$(label).attr("index");
	var currentClicked=	-1;
	currentClicked = $(label).parents("fieldset").attr("cursorRadioClicked");
	if (currentClicked != attrIndex)
	{
		$(label).parents("fieldset").attr("cursorRadioClicked",$(label).attr("index"));
		$(label).parents(".cursorRadio").zremoveClass("noSelection");
	}
	else{
			$(label).parents("fieldset").attr("cursorRadioClicked","-1");
			$(label).parents(".cursorRadio").addClass("noSelection");
	}

	updateCursorText(label);
}

function cursorRadioHover(label){
	var attrFor=$(label).attr("index");
	var attrIndex = $(label).attr("index");
	var currentClicked=	-1;
	currentClicked = $(label).parents("fieldset").attr("cursorRadioHover");
	if (currentClicked != attrIndex){
		$(label).parents("fieldset").attr("cursorRadioHover",$(label).attr("index"));
	}

	var labels = $("label",$(label).parents("fieldset"));
	$(labels).removeClass("beforeHover afterHover");
	for(var j=0;j<labels.length;j++)
	{
		if(j<=attrIndex)
		$(labels[j]).addClass("beforeHover");
		else
		$(labels[j]).addClass("afterHover");
	}
	updateCursorText(label);
}

function cursorRadioLeave(label){
	var cursor = $(label).parents("fieldset");
	$(cursor).attr("cursorRadioHover","-1");

	$("label",cursor).removeClass("beforeHover afterHover");

	var selectedRadio =$(cursor).attr("cursorRadioClicked");
	if(selectedRadio>-1)
		updateCursorText($("label[index='"+selectedRadio+"']",cursor));
	else
		resetCursorText(cursor);
}

function resetCursorText(cursor){
	$("output",cursor).text("");
}

function updateCursorText(label){
	var cursor = $(label).parents("fieldset");
	if(cursor.length>0)
		$("output",cursor).text($("span",label).text());
}

/************************ Gestion des boutons radio et cases à cocher personnalisées ********************/

/* Récupérer le texte associé au label */
function getInputText(elem,inputType,questionType){
	var fullText="";
	if(questionType=="question-GROUPE")
	{
		var thCells=$("table thead.header tr:last-child th.question-choice-horiz.column-question",$(elem).parents(".question-GROUPE"));
		var inputsRow = $("input[type="+inputType+"]",$(elem).parents("tr"));
		for(var g=0;g<inputsRow.length;g++)
		{
			if($(inputsRow[g]).attr("id")==$(elem).attr("id"))
			{
				if (g<thCells.length)
					fullText = $(thCells[g]).text();
				break;
			}
		}
	}
	else if (questionType=="question-UNIQUE")
		fullText= $("label[for='"+$(elem).attr("id")+"']",document).text().trim();

	return fullText;
}

function getInputClasses(elem,inputType){
	var className = (inputType=="radio" ? "radioContainer" : "checkboxContainer");

	// Pour la conf en ligne
	var modaliteClassName="td.question-choice-horiz";
	var modalites=$(modaliteClassName,$(elem).parents("tr:not(.question-choices-label)"));

// Si on n'a rien trouvé pour la conf en ligne on cherche poru une conf en coloone
	if(modalites.length==0)
	{
			modaliteClassName = "li.question-choices-column";
			modalites=$(modaliteClassName,$(elem).parents("ul.question-choices"));
	}

	for(var k=0;k<modalites.length;k++)
	{
			if($(elem).parents(modaliteClassName)[0]==modalites[k]){
				className+=" modalite-"+(k+1)+"-"+modalites.length;
				break;
			}
	}

	return className;
}

function moveLabels(elem,inputType,reverse=false){
	var id=$(elem).attr("for");
	var table = $(elem).parents("table.question-choice-horiz");
	if(reverse){
		if(inputType=="radio")
			$(elem).insertAfter("tr:not(.question-choices-label) label.radiomark[for='"+id+"']",table);
		else if (inputType=="checkbox")
			$(elem).insertAfter("tr:not(.question-choices-label) label.checkmark[for='"+id+"']",table);
	}
	else {
		if(inputType=="radio")
			$(elem).insertBefore("tr:not(.question-choices-label) label.radiomark[for='"+id+"']",table);
		else if (inputType=="checkbox")
			$(elem).insertBefore("tr:not(.question-choices-label) label.checkmark[for='"+id+"']",table);
	}
}

function simpleCSSButtonsInit() {
	// On ajoute la classe txtBtn automatiquement
	$(".note10").each(function(){
			$(this).addClass("txtBtn");
	});

	// Pour les tableaux de fermées uniques en bouton texte
	$(".question-GROUPE tbody.txtBtn tr input[type=radio]").not(".visuallyhidden").each(function(index) {
			$("<label for='"+$(this).attr("id")+"' class='radiomark'>"+getInputText(this,"radio","question-GROUPE")+"</label>").insertAfter($(this));
			$(this).addClass("visuallyhidden").parent().addClass(getInputClasses(this,"radio"));
	});

		// Pour les tableaux de multiples en bouton texte
	$(".question-GROUPE tbody.txtBtn tr input[type=checkbox]").not(".visuallyhidden").each(function(index) {
			$("<label for='"+$(this).attr("id")+"' class='checkmark'>"+getInputText(this,"checkbox","question-GROUPE")+"</label>").insertAfter($(this));
			$(this).addClass("visuallyhidden").parent().addClass(getInputClasses(this,"checkbox"));
	});

	// Pour les fermées uniques bouton texte
	$(".question-UNIQUE.txtBtn input[type=radio]").not(".visuallyhidden").each(function() {
		$("label[for='"+$(this).attr("id")+"'] span.accessibility",document).each(function(){	$(this).remove();	});
		$("<label for='"+$(this).attr("id")+"' class='radiomark'>"+getInputText(this,"radio","question-UNIQUE")+"</label>").insertAfter($(this));
		$(this).addClass("visuallyhidden").parent().addClass(getInputClasses(this,"radio"));
	});

	// Pour les fermées multiple bouton texte
	$(".question-MULTIPLE.txtBtn input[type=checkbox]").not(".visuallyhidden").each(function() {
		$("label[for='"+$(this).attr("id")+"'] span.accessibility",document).each(function(){	$(this).remove();	});
		$("<label for='"+$(this).attr("id")+"' class='checkmark'>"+getInputText(this,"checkbox","question-UNIQUE")+"</label>").insertAfter($(this));
		$(this).addClass("visuallyhidden").parent().addClass(getInputClasses(this,"checkbox"));
	});

	// Pour les fermées uniques "simples" et smileys
	$(".interview-element:not(.cursorRadio):not(.note10) input[type=radio]").not(".visuallyhidden").each(function() {
		$('<label for="'+$(this).attr("id")+'" class="radiomark"></label>').insertAfter($(this));
		$(this).addClass("visuallyhidden").parent().addClass(getInputClasses(this,"radio"));
	});

	// Pour les fermées multiples "simple"
	$(".interview-element input[type=checkbox]").not(".visuallyhidden").each(function() {
		$('<label for="'+$(this).attr("id")+'" class="checkmark"></label>').insertAfter($(this));
		$(this).addClass("visuallyhidden").parent().addClass(getInputClasses(this,"checkbox"));
	});

	// Déplacer les labels dans la même ligne pour les questions uniques en ligne
	$(".question-UNIQUE:not(.cursorRadio):not(.txtBtn) table.question-choices-horiz tr.question-choices-label td.question-choice-horiz label.img-container").each(function(){
			if($(this).parents(".question-UNIQUE")[0].classList.contains("bottomLabel"))
				moveLabels(this,"radio",true);
			else
				moveLabels(this,"radio");
	});
		$(".question-MULTIPLE:not(.cursorRadio):not(.txtBtn) table.question-choices-horiz tr.question-choices-label td.question-choice-horiz label.img-container").each(function(){
			if($(this).parents(".question-MULTIPLE")[0].classList.contains("bottomLabel"))
				moveLabels(this,"checkbox",true);
			else
				moveLabels(this,"checkbox");
	});

	// Pour les smileys : pour déplacer le label texte en dessous du smiley
	$(".question-UNIQUE.smileys tr:not(.question-choices-label) .radioContainer").not(".moved").each(function(){
		if($(this).parents(".question-UNIQUE")[0].classList.contains("bottomLabel"))
			$("label.img-container",this).insertAfter($("label.radiomark",this));
		else
			$("label.img-container",this).insertBefore($("label.radiomark",this));

			$(this).addClass("moved")
	});



// Pour les valeurs par défaut et le mode curseur
	$(".note10:not(.init)").each(function(){

			$(".radioContainer",this).removeClass("checked");
			$(this).addClass("modalite-null");

			var inputs=$("input",this);
			for(var i=0;i<inputs.length;i++)
			{
				// valeur par défaut ou ouverture mail
				if($(inputs[i]).attr("checked")=="checked")
					updateNote10(inputs[i],this,false);

				$(inputs[i]).click(function(){
					updateNote10(this,$(this).parents(".note10")[0],true);
				});

			}
			$(this).addClass("init");
		});
	}


function updateNote10(input,question,clic){

	// Input checked => unchecked
	if($(input).parents(".radioContainer")[0].classList.contains("checked")){
		$(".radioContainer",question).removeClass("checked");
		$(input).parents(".radioContainer").removeClass("checked");
		$(question).addClass("modalite-null");
	}
	else{
		$(".radioContainer",question).removeClass("checked");
		$(input).parents(".radioContainer").addClass("checked");
		$(question).removeClass("modalite-null");
	}

	$(".radioContainer",question).removeClass("fill-0 fill-1 fill-2 fill-3 fill-4 fill-5 fill-6 fill-7 fill-8 fill-9 fill-10");
	var inputs=$("input[type='radio']",question);
	var note = -1;
	for(var i=0;i<inputs.length;i++){
		if($(inputs[i]).parents(".radioContainer")[0].classList.contains("checked"))
		{
			note=i;
			break;
		}
	}


	if(note>-1){
		for(var j=0;j<inputs.length;j++){
			if (j<note)
			{
				/* Note de 0 à 10 = 11 modalités */
				if(inputs.length == 11)
					$(inputs[j]).parents(".radioContainer").addClass("fill-"+note);
				else if(inputs.length == 10)
				{

					$(inputs[j]).parents(".radioContainer").addClass("fill-"+(note+1));
				}

			}

		}
	}
}

/***** Vérification du nb de caractères minimum saisis dans une question texte, selon la classe minlength-N ou minlengthFR-N *****/
function addMinLengthAttr() {

	$(".question-TEXTE[class*='minlength-']").each(function(){
		var minLengthIndex = $(this).attr("class").indexOf("minlength-");
		var compText = $("textarea",this);
		if(compText.length==0)
			compText =  $("input[type='text']",this);
		// on utilise la méthode parseInt pour ne pas récupérer les classes situées ensuite
		var minLengthValue = parseInt($(this).attr("class").substring(minLengthIndex+10));
		if (!$(compText).attr("minlength"))
		$(compText).attr("minlength",minLengthValue);
	});

	$(".question-TEXTE[class*='minlengthFR-']").each(function(){

		var minLengthIndex = $(this).attr("class").indexOf("minlengthFR-");
		var compText = $("textarea",this);
		if(compText.length==0)
			compText =  $("input[type='text']",this);

		// on utilise la méthode parseInt pour ne pas récupérer les classes situées ensuite
		var minLengthValue = parseInt($(this).attr("class").substring(minLengthIndex+12));
		if (!$(compText).attr("minlength")) {
			$(compText).attr("minlength",minLengthValue);
		}

		var idErrorStd = $(" ~ div.error-container p.error",compText).attr("id")+"999";

		var html = "<p class='error errorFR' id='"+idErrorStd+"'>Veuillez saisir au moins "+minLengthValue+" caractère(s).</p>";
		var paragraphError = $(" ~ div.error-container p.error.errorFR",compText);

		if(paragraphError.length==0)
		$("~ div.error-container",compText).append(html);
	});
}

/***** Transformation barre de progression pourcentages en barre de progression carrés *****/
function addProgressZonePages(){
	if($("body").hasClass("progressBarPagesNumber")) {
		// si on est en mode progression par page et non par pourcentage
		$("#interview-progress").removeClass("ui-progressbar");
		$("#interview-progress").addClass("ui-progress-pages");
		var nbPages = parseInt($("#interview-progress").attr("aria-valuemax"));
		var currentPage =  parseInt($("#interview-progress").attr("aria-valuenow"));

		if(isNaN(nbPages))
		{
			setTimeout(addProgressZonePages,100);
			return;
		}

		var progressZone = $(".progressZone","#interview-progress");
		// on crÃ©e la structure
		if(progressZone.length==0){
			var structHTML = "<div class=\"progressZone\">";
			for(var i=1;i<=nbPages;i++){
				if(i<=currentPage)
				structHTML+="<span class=\"progressItem progressBeforeCurrent progressCurrent\"><span class=\"progressTxt\">"+i+"</span></span>";
				else
				structHTML+="<span class=\"progressItem progressAfterCurrent\"><span class=\"progressTxt\">"+i+"</span></span>";
			}
			structHTML += "</div>";
			$("#interview-progress").append(structHTML);
		}
	}
	else{
		$("#interview-progress",document).each(function(){
			$(this).attr("aria-valuetext",$(".interview-progress-label",this).text());
			var nbPages = $(this).attr("aria-valuemax");
			var currentPage =  $(this).attr("aria-valuenow");

			if(isNaN(parseInt(nbPages)))
			{
				setTimeout(addProgressZonePages,100);
				return;
			}

			$(".interview-progress-label",this).text("Etape : "+currentPage+" / "+nbPages);
		});
	}
}

/***** Règles ortho typo ******/
function checkOrthoTypoRules(){
	$("table span.criteria-name,span.question-heading, .comment-container p,.question-body span.choice-label,.section-heading,.question-instructions").each(function(){
		var texte=this.innerHTML;
		var texteOK = texte.replace(/   \?/g,"\u00a0?");
		texteOK = texteOK.replace(/  \?/g,"\u00a0?");
		texteOK = texteOK.replace(/ \?/g,"\u00a0?");
		texteOK = texteOK.replace(/   \!/g,"\u00a0!");
		texteOK = texteOK.replace(/  \!/g,"\u00a0!");
		texteOK = texteOK.replace(/ \!/g,"\u00a0!");
		texteOK = texteOK.replace(/   :/g,"\u00a0:");
		texteOK = texteOK.replace(/  :/g,"\u00a0:");
		texteOK = texteOK.replace(/ :/g,"\u00a0:");
		this.innerHTML = texteOK;
	});
}

/*************************************************************/

function adaptFormBox(){
	/* si on est en mode impression on sort */
	if(document.body.classList.contains("portrait") || document.body.classList.contains("landscape"))
		return;

	var margin =40;
	var headerHeight = parseInt($(".interview-name-parent").css("height"));

	// Si on est sur mobile, le formulaire est directement "collé" après le bandeau, sinon on a une marge de 20px;
	if($(".interview-name-parent").css("flex-wrap")=="wrap")
		margin = 0 ;
	headerHeight +=margin;

	$(".form-box").css("padding-top",headerHeight +"px");
}

function hideElements(){
	$(".accessibility-container").each(function(){
		$(this).addClass("visuallyHidden");

	});
}

function customThankYouPage(){
	$(".form-core .feedback.interview-end:not(.initialized)").each(function(){
		$(this).parents("body").addClass("thankYouPage");
		$(this).parents(".form-core").prepend("<div class='interview-name-parent noTitle'><span id='EnTeteImage' class='interview-image'></span></div>");
		$(this).parents("body").append("<h1 class='visuallyhidden'>Merci d'avoir répondu à ce questionnaire</h1>");
		$(this).addClass("initialized");
	});
}

/***** Ajuster la hauteur du bloc de texte automatiquement *****/
function getScrollHeight(elm){
	var savedValue = elm.value
	elm.value = ''
	elm._baseScrollHeight = elm.scrollHeight
	elm.value = savedValue
}

function onExpandableTextareaInput(e){
	// make sure the input event originated from a textarea and it's desired to be auto-expandable
	var elm=e.target;
	if(!elm.classList.contains('autoExpand') || !elm.nodeName == 'TEXTAREA' ) return

	var minRows = elm.getAttribute('data-min-rows')|0, rows;
	!elm._baseScrollHeight && getScrollHeight(elm);

	elm.rows = minRows
	rows = Math.ceil((elm.scrollHeight - elm._baseScrollHeight) / 16)
	elm.rows = minRows + rows
}

function autoExpand(){
	$(".question-TEXTE:not(.init):not(.disableAutoExpand)").each(function(){

		var nbRows = -1;
		if($("textarea",this).length==1)
		nbRows = parseInt($("textarea",this).attr("rows"));

		if(nbRows>1)
		{
			$("textarea",this).addClass("autoExpand");
			var min=$("textarea",this).attr("rows");
			$("textarea",this).attr("data-min-rows",min);
			$(this).addClass("init");
		}
	});

	// global delegated event listener
	document.addEventListener('input', onExpandableTextareaInput);
}

/* Pour déplacer l'étoile de question obligatoire directement dans l'intitulé de question */
function moveAsteriskTableQuestion(){
		$(".questions-table-container tbody tr td.column-criteria:not(.init)").each(function(){
			var mandatorySpan = $("+td.mandatory span",this);

			if(mandatorySpan.length>0)
				$(mandatorySpan[0]).insertAfter($("div.criteria-name-container span.criteria-name",this));

			$("+td.mandatory",this).remove();
			$(this).addClass("init");
		});
}

/* Pour aligner le logo au centre si pas de titre */
function alignLogo(){
	// le titre est masqué
	$(".interview-name-parent > h1.interview-name.accessibility").each(function(){
			$(this).parents(".interview-name-parent").addClass("noTitle");
	});
}

function insertImgLogo(){
	console.log("insertImgLogo");
	$(".interview-name-parent:not(.initialized) > span.interview-image").each(function(){
		var propertyName = "--logo-url-src";
		var imgShortName="",imgAlt="";
		if (document.body.currentStyle)
			imgShortName = document.body.currentStyle["--logo-url-src"];
		else if (window.getComputedStyle)
			imgShortName = document.defaultView.getComputedStyle(document.body,null).getPropertyValue("--logo-url-src");

		/*	if(imgShortName.indexOf("IMG-")== -1)
				imgShortName ="IMG-"+imgShortName;
				const regex=/\"|\'/g;
			imgShortName = imgShortName.replaceAll("\"","");
			imgShortName = imgShortName.replaceAll("\'","");*/

			console.log("url :"+imgShortName)

			if (document.body.currentStyle)
				imgAlt = document.body.currentStyle["--logo-alt-txt"];
			else if (window.getComputedStyle)
				imgAlt = document.defaultView.getComputedStyle(document.body,null).getPropertyValue("--logo-alt-txt");

			$("<img class='logo' alt ="+imgAlt+" src="+imgShortName+"/>").insertAfter(this);

			$(this).parents(".interview-name-parent").addClass("initialized");
			$(this).remove();
	});
}


async function loadImage(url, elem) {
  return new Promise((resolve, reject) => {
    elem.onload = () => resolve(elem);
    elem.onerror = reject;
    elem.src = url;
  });
}

/**********************************************************************/

function addJSAttribute(){
	$("body:not(.elq_js_loaded)").addClass("elq_js_loaded");
}

function initOrRefreshCustomElments(init){
	/* si on est en mode impression on sort */
	if(document.body.classList.contains("portrait") || document.body.classList.contains("landscape"))
	{
		console.log("print, on sort !!!");
		return;
	}

	if(init){
		// Fix hover iPhone Bug
		fixIPhoneHoverBug();
		// Gestion des spécificités IE9
		getBrowserInfos();
		// Pour transformer la barre de progression pourcentages en barre de progression carrés
		addProgressZonePages();
		// Pb manque ajax ajaxComplete
		let observer = new MutationObserver((mutations) => {
		  mutations.forEach((mutation) => {
			let oldValue = mutation.oldValue;
			let newValue = mutation.target.textContent;
			if (oldValue !== newValue) {
					$(".starCursor").addClass("cursorRadio");
					cursorRadioInit();
					simpleCSSButtonsInit();
				}
		  });
		});

		observer.observe(document.body, {
		  characterDataOldValue: true,
		  subtree: true,
		  childList: true,
		  characterData: true
		});
	}

	// Fix Edge not rendering checkboxes
	ieFix();
	// Ajout des addPlaceHolders
	addPlaceHolders();

	// Remplacement des étoiles produit par des svg
	cursorRadioInit();
	// Boutons radio et coches
	simpleCSSButtonsInit();

	autoExpand();

	addMinLengthAttr();
	checkOrthoTypoRules();

	checkAriaErrors();

	addJSAttribute();

	adaptFormBox();
	hideElements();
	customThankYouPage();
	moveAsteriskTableQuestion();
	alignLogo();
	insertImgLogo();

	setTimeout(function() {
		ieFix();
		addPlaceHolders();

		cursorRadioInit();
		simpleCSSButtonsInit();

		autoExpand();

		addMinLengthAttr();
		checkOrthoTypoRules();
		checkAriaErrors();
		addJSAttribute();

		adaptFormBox();
		hideElements();
		customThankYouPage();
		moveAsteriskTableQuestion();
		alignLogo();
		//setUnderlineColor();
		setDefaultButtonBgColor();

	}, 250);

}

function rgb2hex(r, g, b) {
	var n = (r<<16) + (g<<8) + b;
	return '#' + (r<16? '0':'') + n.toString(16);
}

function hex2rgb(hex){
  //  return "rgba("+Integer.valueOf(hexCode.substring(0, 2), 16)+","+Integer.valueOf(hexCode.substring(2, 4), 16)+","+Integer.valueOf(hexCode.substring(4, 6), 16)+"0.1)";
	// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function(m, r, g, b) {
    return r + r + g + g + b + b;
  });

  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? "rgba("+ parseInt(result[1], 16)+","+parseInt(result[2], 16)+","+parseInt(result[3], 16)+",0.1)" : "#ffffff";
}

function setUnderlineColor(){
    var prop = "";
	var propertyName = "--strong-underline-color";
    if (document.body.currentStyle)
		prop = document.body.currentStyle[propertyName];
    else if (window.getComputedStyle)
		prop = document.defaultView.getComputedStyle(document.body,null).getPropertyValue(propertyName);

	if (prop.substring(0,3)=="rgb")
	{
		var rgbArr = prop.substring(4, prop.length-1).replace(/ /g, '').split(',');
		prop = rgb2hex(rgbArr[0],rgbArr[1],rgbArr[2]);
	}

	/* Pour mettre une transparence de 30% */
	document.body.style.setProperty('--strong-underline-color-start',prop+'4D');
	/* Pour mettre une transparence de 60 % */
	document.body.style.setProperty('--strong-underline-color-end',prop+'99');

}

function setDefaultButtonBgColor(){
	var prop = "",propBG="";
var propertyName = "--button-bg-hover-color";
	if (document.body.currentStyle)
		prop = document.body.currentStyle[propertyName];
	else if (window.getComputedStyle)
		prop = document.defaultView.getComputedStyle(document.body,null).getPropertyValue(propertyName);

if(prop =="")
{
	console.log("on n'a pas trouvé la couleur de fnd au survol dans le style");
	propertyName = "--button-bg-color";
		if (document.body.currentStyle)
			propBG = document.body.currentStyle[propertyName];
		else if (window.getComputedStyle)
			propBG = document.defaultView.getComputedStyle(document.body,null).getPropertyValue(propertyName);
console.log("prop "+propBG);
	//if ((propBG.substring(0,1)=="#") && (propBG.length==7))
	{
		//var rgbArr = prop.substring(4, prop.length-1).replace(/ /g, '').split(',');
		var rgbaColor = hex2rgb(propBG);
		console.log("hex color "+propBG+" rgba color "+rgbaColor);
		/* Pour mettre une transparence de 30% */
		document.body.style.setProperty('--button-bg-hover-color',rgbaColor);
	}
}


}

$(document).ready(function(){
	initOrRefreshCustomElments(true);
});

var isAjaxCompleteRun = false;

$(document).bind("ajaxComplete", function() {
	initOrRefreshCustomElments(false);
	isAjaxCompleteRun = true;
});

$(window).resize(function() {
	setTimeout(adaptFormBox,100);
});

window.addEventListener("orientationchange", function() {
	setTimeout(adaptFormBox,100);
});

/************** Partie polyfill ************************/
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
  typeof define === 'function' && define.amd ? define(factory) :
  (factory());
}(this, (function () { 'use strict';

  /**
   * Applies the :focus-visible polyfill at the given scope.
   * A scope in this case is either the top-level Document or a Shadow Root.
   *
   * @param {(Document|ShadowRoot)} scope
   * @see https://github.com/WICG/focus-visible
   */
  function applyFocusVisiblePolyfill(scope) {
    var hadKeyboardEvent = true;
    var hadFocusVisibleRecently = false;
    var hadFocusVisibleRecentlyTimeout = null;

    var inputTypesAllowlist = {
      text: true,
      search: true,
      url: true,
      tel: true,
      email: true,
      password: true,
      number: true,
      date: true,
      month: true,
      week: true,
      time: true,
      datetime: true,
      'datetime-local': true
    };

    /**
     * Helper function for legacy browsers and iframes which sometimes focus
     * elements like document, body, and non-interactive SVG.
     * @param {Element} el
     */
    function isValidFocusTarget(el) {
      if (
        el &&
        el !== document &&
        el.nodeName !== 'HTML' &&
        el.nodeName !== 'BODY' &&
        'classList' in el &&
        'contains' in el.classList
      ) {
        return true;
      }
      return false;
    }

    /**
     * Computes whether the given element should automatically trigger the
     * `focus-visible` class being added, i.e. whether it should always match
     * `:focus-visible` when focused.
     * @param {Element} el
     * @return {boolean}
     */
    function focusTriggersKeyboardModality(el) {
      var type = el.type;
      var tagName = el.tagName;

      if (tagName === 'INPUT' && inputTypesAllowlist[type] && !el.readOnly) {
        return true;
      }

      if (tagName === 'TEXTAREA' && !el.readOnly) {
        return true;
      }

      if (el.isContentEditable) {
        return true;
      }

      return false;
    }

    /**
     * Add the `focus-visible` class to the given element if it was not added by
     * the author.
     * @param {Element} el
     */
    function addFocusVisibleClass(el) {
      if (el.classList.contains('focus-visible')) {
        return;
      }
      el.classList.add('focus-visible');
      el.setAttribute('data-focus-visible-added', '');
    }

    /**
     * Remove the `focus-visible` class from the given element if it was not
     * originally added by the author.
     * @param {Element} el
     */
    function removeFocusVisibleClass(el) {
      if (!el.hasAttribute('data-focus-visible-added')) {
        return;
      }
      el.classList.remove('focus-visible');
      el.removeAttribute('data-focus-visible-added');
    }

    /**
     * If the most recent user interaction was via the keyboard;
     * and the key press did not include a meta, alt/option, or control key;
     * then the modality is keyboard. Otherwise, the modality is not keyboard.
     * Apply `focus-visible` to any current active element and keep track
     * of our keyboard modality state with `hadKeyboardEvent`.
     * @param {KeyboardEvent} e
     */
    function onKeyDown(e) {
      if (e.metaKey || e.altKey || e.ctrlKey) {
        return;
      }

      if (isValidFocusTarget(scope.activeElement)) {
        addFocusVisibleClass(scope.activeElement);
      }

      hadKeyboardEvent = true;
    }

    /**
     * If at any point a user clicks with a pointing device, ensure that we change
     * the modality away from keyboard.
     * This avoids the situation where a user presses a key on an already focused
     * element, and then clicks on a different element, focusing it with a
     * pointing device, while we still think we're in keyboard modality.
     * @param {Event} e
     */
    function onPointerDown(e) {
      hadKeyboardEvent = false;
    }

    /**
     * On `focus`, add the `focus-visible` class to the target if:
     * - the target received focus as a result of keyboard navigation, or
     * - the event target is an element that will likely require interaction
     *   via the keyboard (e.g. a text box)
     * @param {Event} e
     */
    function onFocus(e) {
      // Prevent IE from focusing the document or HTML element.
      if (!isValidFocusTarget(e.target)) {
        return;
      }

      if (hadKeyboardEvent || focusTriggersKeyboardModality(e.target)) {
        addFocusVisibleClass(e.target);
      }
    }

    /**
     * On `blur`, remove the `focus-visible` class from the target.
     * @param {Event} e
     */
    function onBlur(e) {
      if (!isValidFocusTarget(e.target)) {
        return;
      }

      if (
        e.target.classList.contains('focus-visible') ||
        e.target.hasAttribute('data-focus-visible-added')
      ) {
        // To detect a tab/window switch, we look for a blur event followed
        // rapidly by a visibility change.
        // If we don't see a visibility change within 100ms, it's probably a
        // regular focus change.
        hadFocusVisibleRecently = true;
        window.clearTimeout(hadFocusVisibleRecentlyTimeout);
        hadFocusVisibleRecentlyTimeout = window.setTimeout(function() {
          hadFocusVisibleRecently = false;
        }, 100);
        removeFocusVisibleClass(e.target);
      }
    }

    /**
     * If the user changes tabs, keep track of whether or not the previously
     * focused element had .focus-visible.
     * @param {Event} e
     */
    function onVisibilityChange(e) {
      if (document.visibilityState === 'hidden') {
        // If the tab becomes active again, the browser will handle calling focus
        // on the element (Safari actually calls it twice).
        // If this tab change caused a blur on an element with focus-visible,
        // re-apply the class when the user switches back to the tab.
        if (hadFocusVisibleRecently) {
          hadKeyboardEvent = true;
        }
        addInitialPointerMoveListeners();
      }
    }

    /**
     * Add a group of listeners to detect usage of any pointing devices.
     * These listeners will be added when the polyfill first loads, and anytime
     * the window is blurred, so that they are active when the window regains
     * focus.
     */
    function addInitialPointerMoveListeners() {
      document.addEventListener('mousemove', onInitialPointerMove);
      document.addEventListener('mousedown', onInitialPointerMove);
      document.addEventListener('mouseup', onInitialPointerMove);
      document.addEventListener('pointermove', onInitialPointerMove);
      document.addEventListener('pointerdown', onInitialPointerMove);
      document.addEventListener('pointerup', onInitialPointerMove);
      document.addEventListener('touchmove', onInitialPointerMove);
      document.addEventListener('touchstart', onInitialPointerMove);
      document.addEventListener('touchend', onInitialPointerMove);
    }

    function removeInitialPointerMoveListeners() {
      document.removeEventListener('mousemove', onInitialPointerMove);
      document.removeEventListener('mousedown', onInitialPointerMove);
      document.removeEventListener('mouseup', onInitialPointerMove);
      document.removeEventListener('pointermove', onInitialPointerMove);
      document.removeEventListener('pointerdown', onInitialPointerMove);
      document.removeEventListener('pointerup', onInitialPointerMove);
      document.removeEventListener('touchmove', onInitialPointerMove);
      document.removeEventListener('touchstart', onInitialPointerMove);
      document.removeEventListener('touchend', onInitialPointerMove);
    }

    /**
     * When the polfyill first loads, assume the user is in keyboard modality.
     * If any event is received from a pointing device (e.g. mouse, pointer,
     * touch), turn off keyboard modality.
     * This accounts for situations where focus enters the page from the URL bar.
     * @param {Event} e
     */
    function onInitialPointerMove(e) {
      // Work around a Safari quirk that fires a mousemove on <html> whenever the
      // window blurs, even if you're tabbing out of the page. ¯\_(ツ)_/¯
      if (e.target.nodeName && e.target.nodeName.toLowerCase() === 'html') {
        return;
      }

      hadKeyboardEvent = false;
      removeInitialPointerMoveListeners();
    }

    // For some kinds of state, we are interested in changes at the global scope
    // only. For example, global pointer input, global key presses and global
    // visibility change should affect the state at every scope:
    document.addEventListener('keydown', onKeyDown, true);
    document.addEventListener('mousedown', onPointerDown, true);
    document.addEventListener('pointerdown', onPointerDown, true);
    document.addEventListener('touchstart', onPointerDown, true);
    document.addEventListener('visibilitychange', onVisibilityChange, true);

    addInitialPointerMoveListeners();

    // For focus and blur, we specifically care about state changes in the local
    // scope. This is because focus / blur events that originate from within a
    // shadow root are not re-dispatched from the host element if it was already
    // the active element in its own scope:
    scope.addEventListener('focus', onFocus, true);
    scope.addEventListener('blur', onBlur, true);

    // We detect that a node is a ShadowRoot by ensuring that it is a
    // DocumentFragment and also has a host property. This check covers native
    // implementation and polyfill implementation transparently. If we only cared
    // about the native implementation, we could just check if the scope was
    // an instance of a ShadowRoot.
    if (scope.nodeType === Node.DOCUMENT_FRAGMENT_NODE && scope.host) {
      // Since a ShadowRoot is a special kind of DocumentFragment, it does not
      // have a root element to add a class to. So, we add this attribute to the
      // host element instead:
      scope.host.setAttribute('data-js-focus-visible', '');
    } else if (scope.nodeType === Node.DOCUMENT_NODE) {
      document.documentElement.classList.add('js-focus-visible');
      document.documentElement.setAttribute('data-js-focus-visible', '');
    }
  }

  // It is important to wrap all references to global window and document in
  // these checks to support server-side rendering use cases
  // @see https://github.com/WICG/focus-visible/issues/199
  if (typeof window !== 'undefined' && typeof document !== 'undefined') {
    // Make the polyfill helper globally available. This can be used as a signal
    // to interested libraries that wish to coordinate with the polyfill for e.g.,
    // applying the polyfill to a shadow root:
    window.applyFocusVisiblePolyfill = applyFocusVisiblePolyfill;

    // Notify interested libraries of the polyfill's presence, in case the
    // polyfill was loaded lazily:
    var event;

    try {
      event = new CustomEvent('focus-visible-polyfill-ready');
    } catch (error) {
      // IE11 does not support using CustomEvent as a constructor directly:
      event = document.createEvent('CustomEvent');
      event.initCustomEvent('focus-visible-polyfill-ready', false, false, {});
    }

    window.dispatchEvent(event);
  }

  if (typeof document !== 'undefined') {
    // Apply the polyfill to the global document, so that no JavaScript
    // coordination is required to use the polyfill in the top-level document:
    applyFocusVisiblePolyfill(document);
  }

})));
