require( ebplatform.config.enableLoadBuilt ? ["built/dojo", "built/ebCommon", "built/iscrizione"] : [], function() { //.js.uncompressed
	require(["dojo/ready",
	 	"dojo/_base/lang",
	 	"dojo/_base/array",
		"dojo/dom",
		"dijit/Dialog",
		"dojo/dom-style",
		"dojo/dom-attr",
		"dojo/dom-prop",
		"dojo/dom-construct",
		"dojo/query",
		"dojo/request",
		"dojo/html",
		"dojo/io-query",
		"dojo/on",
		"dojo/topic",
		"dijit/registry"],
		function(ready,
			lang,
			arrayUtil,
			dom,
			Dialog,
			domStyle,
			domAttr,
			domProp,
			domConstruct,
			query,
			request,
			html2,
			ioQuery,
			on,
			topic,
			registry) {
			ready(function() {

				function init(){
					try {

						// domConstruct.place("<div class='myclass'>my html</div>", query("NODE_SELECTOR")[0], 'before');

                     	// BEGIN_GRUPPI_INCLUSIVI 
 						// END_GRUPPI_INCLUSIVI
						// BEGIN_GRUPPI_ESCLUSIVI
					    // END_GRUPPI_ESCLUSIVI	


						/* BEGIN_BLOCK: htmlFasce
						// STRUCTURE htmlFasce
						var htmlFasce = {
						  "fasce": {							    
						  }
						}
						// END STRUCTURE htmlFasce 
	 					try {	 						 
							for (const [key, value] of Object.entries(htmlFasce.fasce)) {
								console.log ("key set html:" , key, value, query(".tundra.pagIscrizione .boxDateEvento .fasceDataEvento .idFascia" + key+ " span.titoloFascia"));
							    
							    if (value != "")
							        html2.set(query(".tundra.pagIscrizione .boxDateEvento .fasceDataEvento .idFascia" + key+ " span.titoloFascia")[0], value);
							}								 
					 	} catch (err) {
							console.log("htmlFasce: ", err);
						}	
						END_BLOCK: htmlFasce */



						 
						// STRUCTURE popupDescriptions
						var popupDescriptions = {
						  "template": "%titolo%",
						  "FFFpreselect": "%FFFpreselect%",
						  "editables": "%titolo%,%bio%,%FFFpreselect%",
						  "enableDialogDetail": false,
						  "fasce": {
						     
						  }
						}
						
						// END STRUCTURE popupDescriptions

						function ifNotEmpty (v) {
						    if (v != ""){
						     	return "<br/><br/>" + v 
						    } 
							return "" ;
						}
						try {
							if (popupDescriptions.enableDialogDetail)
								for (const idFascia in popupDescriptions.fasce) {
									console.log("idFascia", idFascia);
									var ref0 = query('.idFascia' + idFascia)[0];
									var ref1 = query('.titoloFascia', ref0)[0];
	 
									if (!!ref1 && popupDescriptions[idFascia] != "") {
										// sostituisce lo span con titolo fascia mettendo il bottone	
										var html1 = "<span class='titoloFascia'>" + ref1.innerHTML + " <button type='button' id='ButIdFascia" + idFascia + "'>Details</button></span>";	
										domConstruct.place(html1, ref1, 'replace');
																						
										// apre popup quando clicco bottone
										var btn1 = query('#ButIdFascia' + idFascia)[0];
										on (btn1,'click',function(){
											//!!! **** TODO ****: Aggiungere elementi di popupDescriptions.fasce o usare il template 											 
											var myContent = "test";
													
											myDialog = new Dialog({
										        //title: "Details",
										        title: popupDescriptions.fasce[idFascia].titolo,
										        content: myContent,
										        style: "width: 800px"
										    });
										    myDialog.show();
										     

										});
									}
								}

							if (!!popupDescriptions.FFFpreselect) {
								for (const idFascia in popupDescriptions.fasce) {
									if (popupDescriptions.fasce[idFascia].FFFpreselect == "1"){
										query(".id" + idFascia + " input[type=checkbox]").forEach(function(node){node.checked=true;});		
									} 	
								}		
							}

						} catch (err) {
							console.log("popupDescriptions: ", err);
						}		
						 

						/*
                        var idPersona = query("[name=idPersona]")[0].value;
                        console.log ("idPersona:", idPersona);
                        if (idPersona == 0) 
                            query("body").addClass("publicPage");  
                        */ 
						
						/*
						if (!!dom.byId("intMaxAccompagnatori") && dom.byId("intMaxAccompagnatori").innerHTML == "0") {
							domStyle.set(dom.byId("boxAcc"), "display", "none");
							ebPlatform.iscrizione.allineaAltezzaBoxSxDx();
						}
						*/

						/* toglie email da ospite principale
						document.getElementsByClassName("ospitePrincipale")[0].innerHTML = document.getElementsByClassName("ospitePrincipale")[0].innerHTML.replaceAll (/\[.*\]/g,"").trim();
						*/

						/*  // cecca una sessione:
							query(".id201509 input[type=checkbox]").forEach(function(node){node.checked=true;});
						*/

						/* aggiungo un link */
						/*var lab=query(".tundra.pagIscrizione .boxDatiIscrizione .itemForm.idCustomfield197656 label")[0];
						if (!!lab){
							lab.innerHTML = 'PRESA VISIONE DELL\'<a href="#" class="informativaPrivacy">INFORMATIVA PRIVACY</a><span class="mandatory">*</span>';
							var link = query(".tundra.pagIscrizione .boxDatiIscrizione .itemForm.idCustomfield197656 label a.informativaPrivacy")[0];
							on(link,'click',function(){
								window.open('https://s3-eu-west-1.amazonaws.com/eventboost/assets/customcss/sacbo/Informativa01.html','informativa','width=800,height=600');
							})							
						}*/

						 /*  solo due scelte per una lista di checkbox
 						     query("input[name='valoriCustomField[383558]']").on('click', function(e){                         		
                           		var alreadyChecked = query("input[name='valoriCustomField[383558]']:checked").length;
                                console.log ("e: ", e, alreadyChecked);     
                                if (alreadyChecked >= 3) {
                                   e.checked = false;
                                   dojo.stopEvent(e); 
                                                                    
                                  myDialog = new Dialog({                                    
                                    title: "Warning",
                                    content: "You can choose a maximum of only two sessions for this date.",
                                    style: "width: 800px"
                                  });
                                  myDialog.show();
                                }
                                
                         });                        
						*/

						/* modifico frase pagina declinazione per il Lei 
	   					   scommentare e usare la jsp admin EDIT_POPUP_SESSION per fare inserire i testi 
	   					   --> andare in easy style e aggiungere la regola nascondi testi "non partecipo"
						*/
						/* 
						var target1 = query(".tundra.pagIscrizione .boxModule .boxModuleInner .custom")[0];
						if (!!target1 && target1.innerHTML.indexOf("Ci dispiace che")>-1){
							var fraseCiDispiace = "";	 
							target1.innerHTML = target1.innerHTML.replace('Ci dispiace che tu non possa partecipare e speriamo di vederti ai prossimi eventi.',
						                                        fraseCiDispiace);  
						    domStyle.set(target1, "display", "block");                                      
						    console.log ("sostituito .custom");
						}  
						var target = query(".tundra.pagIscrizione .boxModule .boxModuleInner .system")[0];
						if (!!target && target.innerHTML.indexOf("Se hai declinato")>-1){
						    var fraseSeHaiDeclinato = "";
						    var fraseConfermaPartecipazione = "";
							target.innerHTML = target.innerHTML.replace('Se hai declinato l\'invito per errore, ricarica la pagina',  fraseSeHaiDeclinato)
							 								   .replace('e conferma la tua partecipazione.', fraseConfermaPartecipazione);    
						    domStyle.set(target, "display", "block");
						    console.log ("sostituito .system");
						} 

						*/

						/* se devo leggere/agire da/su un campo lista */
						/*
						var widget = registry.byId("customFieldSelect_307042");
						var accompagnatori = "";
						*/
						/* 	663363;"SI"
							663364;"NO"
						*/
						/*
						if (!!widget){
							accompagnatori = widget.get("value");
							console.log("... da widget");

							widget.on('change',function(newVal){
								console.log("newVal:",newVal);
							});

						} else {
							var el = dom.byId("valoreLista3.idValoreLista_box_anagrafica");
							if (el.selectedIndex > 0) {
								accompagnatori = el.options[el.selectedIndex].value;
							}
							on(el,'change',function(e){
								console.log("newVal:",el.options[el.selectedIndex].value);
							});
							console.log("... da select");
						}
						*/

						/*
						// Setta valore in campo lista. Nel form degli accompagnatori setta il campo non editabile "Team Type" con il valore "Team Member" 				 
						var widget = registry.byId("customFieldSelect_376327");
						var accompagnatori = "";					 
						if (!!widget){							 
							// per desktop
							widget.set("value", 773117);
						} else {
							// per mobile 
							var el = dom.byId("valoreLista2.idValoreLista_box_anagrafica");
							el.selectedIndex = 2;							 
						}
						*/	


						/* consensi privacy: rimuoviamo default no */
						/* var c1 = document.getElementById('consensoTrattamentoDati.consensoServizioIscrizione2');
						if (!!c1){
							domProp.set(c1,'checked',false);
						}
						var c2 = document.getElementById('consensoTrattamentoDati.consensoPubblicitaIscrizione2');
						if (!!c2){
							domProp.set(c2,'checked',false);
						}	
						*/

						/* sostituisce from at nelle ore fasce */	
						/* BEGIN_BLOCK: changeFromInSessions			 		
						query(".date.time").forEach(function(dateTime) {
							console.log (".date.time n " , dateTime);
					        dateTime.innerHTML = dateTime.innerHTML.replace("from", "at").replace("dalle", "alle");		
					    });	
						END_BLOCK: changeFromInSessions */

						/* BEGIN_BLOCK: addBottoneDopoBottoneIscrizione
						var ref1 = query('.iscrizione')[0];
						var html1 = '<br/><span class="inputSubmit maggioriinfo" style="margin-top: 0px;">' + 									
									'<a href="https://www.axpo.com/it/it/axpo_green_energy_solutions_talks.html" class="submitIscrizione" style="vertical-align:middle;border: 0px none;    border-radius: 4px;    cursor: pointer;    display: inline-block;    font-size: 100%;    font-weight: 600;    height: 50px;    line-height: 38px;    padding: 5px 15px;    -webkit-appearance: none;font-family: \'Montserrat\';color:white;BACKGROUND-COLOR:#FF0000" target="_new">MAGGIORI INFO</a>' + 	
									'</span>';

						domConstruct.place(html1, ref1, 'after');
						END_BLOCK: addBottoneDopoBottoneIscrizione */


						/* BEGIN_BLOCK: messaggioSeGiaIscrittoENonDaBE
						var idPersona = document.getElementsByName("idPersona");
						//console.log("ep-25659.js idPersona.value:"+idPersona[0].value);

						var giaPresente = !!query(".giaRegistratoNoUpdate.giaRegistratoNoDelete")[0];
						console.log("giaPresente",giaPresente);
						var qs = document.location.search;
						var fromBE = false;
						if (!!qs) {
							qs = ioQuery.queryToObject(qs.substring(1, qs.length));
							if (!!qs.fromBE) {
								 console.log ("from BE:" + qs.fromBE);
								 if (qs.fromBE == "true") {
								 	fromBE = true;
								 }
							}
						}	
						//if(idPersona[0].value>0){
						if (giaPresente && fromBE == false){
							//c'e' un iscrizione
							domStyle.set("boxDxContent", "display", "none");
							var boxesPrivacyWrap = query(".boxesPrivacyWrap ")[0];
							if (!!boxesPrivacyWrap ){
								domStyle.set(boxesPrivacyWrap, "display", "none");
							}
							document.getElementById("boxDx").innerHTML = "<div id=\"boxAvvertimento\">La tua registrazione &egrave; gi&agrave; stata effettuata;<BR/>Qualora avessi bisogno di modificare la tua iscrizione, contatta la <b>Segreteria Organizzativa Amundi Digital Roadshow</b><BR/><b>Email:</b>amundidigitalroadshow@aesteam.it<BR/><b>Telefono:</b>338 4642173<BR/><i>(orario segreteria organizzativa: dal luned&igrave; al venerd&igrave; dalle 10.00 alle 16.00)</i></div>";

							var buttons = document.getElementsByClassName("boxRegistrationButtons");
							//console.log("ep-25659.js buttons.style.display:"+buttons[0].style.display);
							var i;
							for (i = 0; i < buttons.length; i++) {
								buttons[i].style.display = "none";
								//console.log("ep-25659.js buttons.style.display none");
							}
							var boxDx = document.getElementById("boxDx");
							boxDx.style.marginTop="30px";

						}else{
							//nessuna iscrizione quindi non faccio niente
						}
						END_BLOCK: messaggioSeGiaIscrittoENonDaBE */



					} catch (err) {
						console.log(err)
					}
				}

				if (lang.exists("ebPlatform.iscrizione.boxAnagraficaEndSetUp")) {
					if (!!ebPlatform.iscrizione.boxAnagraficaEndSetUp){
						init();
					}
				}
				topic.subscribe("BoxAnagrafica.EndSetUp", lang.hitch(this, function() {				
					init();
				}));

				/* Per rendere un gruppo di checkbox a scelta esclusiva */
				function rendiEsclusivoGruppo(idArr){
					arrayUtil.forEach(idArr,function(itemId){
						if (!!document.getElementById(itemId)){
							on(document.getElementById(itemId),'click',function(e){
								console.log("this",this,"e",e);
								if (e.target.checked){
									resetChecked(idArr,itemId);
								}
							});
						}
					});
				};

				function resetChecked(idArr,escludiId){
					arrayUtil.forEach(idArr,function(itemId){
						if (itemId != escludiId){
							var el = document.getElementById(itemId);
							if (!!el){
								el.checked = false;
							}
						}
					});
				}
				// usa querySelector con data-eb-idfascia
				function rendiEsclusivoGruppo2(idArr){
					arrayUtil.forEach(idArr,function(itemId){
						if (!!document.querySelector("[data-eb-idfascia='" + itemId + "']")){
							on(document.querySelector("[data-eb-idfascia='" + itemId + "']"),'click',function(e){
								console.log("this",this,"e",e);
								if (e.target.checked){
									resetChecked2(idArr,itemId);
								}
							});
						}
					});
				};
		
        		function resetChecked2(idArr,escludiId){
					arrayUtil.forEach(idArr,function(itemId){
						if (itemId != escludiId){
							var el = document.querySelector("[data-eb-idfascia='" + itemId + "']");
							if (!!el){
								el.checked = false;
							}
						}
					});
				}   

				// usa querySelector con data-eb-idfascia
				function rendiInclusivoGruppo(idArr){
					arrayUtil.forEach(idArr,function(itemId){
						if (!!document.querySelector("[data-eb-idfascia='" + itemId + "']")){
							on(document.querySelector("[data-eb-idfascia='" + itemId + "']"),'click',function(e){
								console.log("this",this,"e",e);
								if (e.target.checked){
									setChecked(idArr,itemId);
								} else {
                                  	resetChecked2(idArr,itemId);
                                }
							});
						}
					});
				};
		
        		function setChecked(idArr,escludiId){
					arrayUtil.forEach(idArr,function(itemId){
						if (itemId != escludiId){
							var el = document.querySelector("[data-eb-idfascia='" + itemId + "']");
							if (!!el){
								el.checked = true;
							}
						}
					});
				}  

				
				function numeroMassimoSessioniPossibiliIscrizione(nMaxSessioniPermesse){
					on(query("#boxDateEvento input[type=checkbox]"),'click',function(e){
								 
						var nchecked = 0;
						query("#boxDateEvento input[type=checkbox]").forEach(function(el){
							if (el.checked == true) 
								nchecked++;									 
						})
						 
						if (nchecked >= nMaxSessioniPermesse + 1) {
							e.checked = false;
							domProp.set(e, 'disabled', true);
							 
							myDialog = new Dialog({
						        //title: "Details",
						        title: "Attenzione ",
						        content: "Massimo " + nMaxSessioniPermesse + " sessioni !",
						        style: "width: 500px"
						    });
						    myDialog.show();	
						    // prevent propagating event
							dojo.stopEvent(e);	
						}								 							
					});	
				}


				/* Per controllare la lunghezza dei campi testo */
				function deleteOrFrecce(keyCode){
					return (keyCode==8 || keyCode==46 || keyCode==37 || keyCode==39);
				}

				function limitaCifre(f,num){
					domAttr.set(f,'maxlength',num);
					on(f,'keydown',function(e){
						console.log(e.keyCode);
						if ((e.keyCode<48 || e.keyCode>57) && !deleteOrFrecce(e.keyCode)){
							e.preventDefault();
						}
					});
				}

				/* Per limitare le date disponibili sui calendari */
				function limitaDate() {
					try {
						var w = registry.byId("customfield5_box_anagrafica");
						if (!!w) {						
							w.set("dropDownDefaultValue", new Date(2018, 0, 1, 0, 0, 0, 0));
							w.set("constraints", {min: "2019-02-01", max:"2019-02-28"});
						}
						
					} catch(err) {
						console.log(err);
					}
				}

				/* Per limitare le date disponibili su tutti i calendari */
				function limitaTutteLeDate() {
					try {
						query(".ebTimeZoneAwareDateTextBox").forEach(function(node){
							var widgetId = domAttr.get(node,'widgetid');
							console.log(widgetId);

							var w = registry.byId(widgetId);
							if (!!w) {						
								w.set("dropDownDefaultValue", new Date(2020, 0, 1, 0, 0, 0, 0));
								w.set("constraints", {min: "2020-01-01"});
							}
						});
					} catch(err) {
						console.log(err);
					}
				}

				/* Apre E Seleziona Tutte Le Fasce */
				function ApreESelezionaTutteLeFasce() {
					domConstruct.place("<button type='button' id='allFascia'>Subscribe to all events</button><br><br>", query("[data-ebplatform-template-elementid='registrationBoxTitleNode']")[0], 'after');
					var btnAll = query('#allFascia' )[0];
					on (btnAll,'click',function(){
					
					query(".boxDateEvento input[type=checkbox]").forEach(function(node){node.checked=true;});

					arrayUtil.forEach(
					    query(".iconText"),
					    function(selectTag){					         
							selectTag.click(); 
							
					    }
					  );		 
					});
				}

				/* bottone per resettare tutte le sessioni selezionate */	
				function uncheckAllSessions(){
                    document.querySelectorAll('.boxRegistration [type=checkbox]').forEach(function(e){ e.checked=false });
				}
				function buttonUncheckAllSessions() {
					domConstruct.place("<button type='button' id='buttonUncheckAllSessions'>Reset</button><br><br>", query("[data-ebplatform-template-elementid='registrationBoxTitleNode']")[0], 'after');
					var btnAll = query('#buttonUncheckAllSessions' )[0];
					on (btnAll,'click',function(){
					    uncheckAllSessions();				 	 
					});
				}


			});
		});
}); // outer require

/* BEGIN_BLOCK: allowedDomains 
function ebPlatformCustomCheckAndSubmit(){
	console.log("ebPlatformCustomCheckAndSubmit");


	// controlla che domini della email ospite ed accompagnatore siano in un certo set:
	// METTERE "," iniziale e "," finale
	var email0AllowedDomains = ",@gmail.com,@hotmail.com,@eventboost.com,";
	var emailAccompagnatoreAllowedDomains = ",@gmail.com,@hotmail.com,@eventboost.com,";
	var idCampoEmailAccompagnatore= "customfield1_box_anagrafica"

	var returnValue = 'ok';
	// classe managingFiglio
	if (ebManagingFiglio == false){
	    var email0 = document.getElementById("customfield0_box_anagrafica").value;
		var domain0 = email0.substring(email0.indexOf("@"), email0.length);
	    if (email0AllowedDomains.toLowerCase().indexOf(domain0.toLowerCase()) < 0) {
	        console.log ("Dominio email ospite non permesso.");
	        returnValue = 'Dominio email ospite non permesso.';
	    }
	} else {
	    // accompagnatore cambiare id a seconda del caso
	    var emailAcc = document.getElementById(idCampoEmailAccompagnatore).value;
		var domainAccompagnatore = emailAcc.substring(emailAcc.indexOf("@"), emailAcc.length);
	    if (emailAccompagnatoreAllowedDomains.toLowerCase().indexOf(domainAccompagnatore.toLowerCase()) < 0) {
	        console.log ("Dominio email accompagnatore non permesso."); 
	        returnValue = 'Dominio email accompagnatore non permesso.';
	    }
	}   
	return returnValue;

	return 'ko'
}
END_BLOCK: allowedDomains */