/**
 * 
 */


var resetResult;
var lsid;
var lsentid;
//var getDimDiv;
const formaClass='frm'
var selectedVista;
 
$(document).ready(function() {
	lsid='';
	removeGraph=false;
						
	const cantobadgeclass = 'badge badge-outline-info badge-pill'

	const sparqlGenerator = sparqljs.Generator;
	const myEngine = new Comunica.QueryEngine();
	const sparqlEndpoint = "https://hdnlab1.isti.cnr.it/fuseki/commediaontosintgra/query";
	
	var shownSentenceList = new Set()

	//var currentMinimap = ''
	
	var listarisultati = [];
	var listaPeriodiRisultato = [];
	var resultSentences = new Set()
	var minimapScrolling = false;
	var displayId = 'displaycanto'
	var cantiche=["Inferno", "Purgatorio","Paradiso"]
	var loadedCanti=new Set();
	const openSTag="{"
	const closeSTag="}"
	
	var cantoDisplayed = "#InfernoCanto_1";
	var queryExecuted = false;
	var contextLength = 4; 
	var currentContextLength = 4; 

	
	resetResult=function(){
		//console.log('clean result')
		cleanSearchResult()
		esprlogica = []
	}
	
	hideMinimap();
	createAllDivCanti()
	const start = performance.now();
	showCanto(formeprima, '1','1')
	$("#InfernoCanto_1").attr('style', 'display: d-flex;')
	loadedCanti.add("InfernoCanto_1")
	//$("#InfernoCanto_1").removeClass('hidecanto')

	//$("#InfernoCanto_1").css("display", "block");
	drawMinimap("#InfernoCanto_1")
	const end = performance.now();
	console.log(`Load cantiche time: ${end - start} ms`);
	
$("#valoreVista").on('change', function() {
	selectedVista = $(this).val();
	switch (selectedVista){
		case "forme":
					$("#vistaFrasi").css("display", "none");
					$("#vistaDialoghi").css("display", "none");
					$("#vistaMetafore").css("display", "none");
					resetFrasi()
					$(cantoDisplayed).attr('style', 'display: d-flex;')
					break;
		case "frasi":
					loadFrasi();
					$("#vistaDialoghi").css("display", "none");
					$("#vistaMetafore").css("display", "none");
					//$(cantoDisplayed).css("display", "none");
					//$("#vistaFrasi").attr('style', 'display: d-flex;');
					break;					
		case "metafore":
					//loadMetafore();
					//$("#vistaDialoghi").css("display", "none");
					//$("#vistaFrasi").css("display", "none");
					//resetFrasi()
					//$(cantoDisplayed).css("display", "none");
					//$("#vistaMetafore").attr('style', 'display: d-flex;');
					break;			
		case "dialoghi":
					//loadDialoghi();
					//$("#vistaMetafore").css("display", "none");
					//$("#vistaFrasi").css("display", "none");
					//resetFrasi()
					//$(cantoDisplayed).css("display", "none");
					//$("#vistaDialoghi").attr('style', 'display: d-flex;');
					break;
	}
});

function loadFrasi() {
	//var spanFrase = $('<span />')
	
	/*for (pos=0;pos<20;pos++){
		spanFrase.attr('id', pos)
		spanFrase.append("La mia più bella frase numero "+" "+pos+"<br>");		
		$("#vistaFrasi").append(spanFrase);
	}*/
	
	$(cantoDisplayed).find(' .sentencetag').each(function() {
		$(this).attr('style', 'display: d-flex;');
	})
	$(cantoDisplayed).find(' .'+formaClass).each(function() {
		stp=$(this).attr('class').split(" ")[1]

		$(this).css('color', colorssp(mapsynttypestopalette[stp]));
	})
	let minim=$(" .minimap__content")
	minim.contents().find(" .sentencetag").each(function(){
		$(this).attr('style', 'display: d-flex;');
	})
	minim.contents().find(' .'+formaClass).each(function() {
		stp=$(this).attr('class').split(" ")[1]

		$(this).css('color', colorssp(mapsynttypestopalette[stp]));
	})
	//drawMinimap(cantoDisplayed)
}

function resetFrasi(){
	
	$(cantoDisplayed).find(' .sentencetag').each(function() {
		$(this).css('display', 'none');
	})
	$(cantoDisplayed).find(' .'+formaClass).each(function() {
		//console.log(colorssp(mapsynttypestopalette[stp]))
		$(this).css('color', '');
	})
	let minim=$(" .minimap__content")
	minim.contents().find(" .sentencetag").each(function(){
		$(this).css('display', 'none');
	})
	minim.contents().find(' .'+formaClass).each(function() {
		$(this).css('color', '');
	})
	//drawMinimap(cantoDisplayed)
}


//$(" .Ma, .Co, .Su, .Pa").each(function(idx, element) {

$(" ."+formaClass).each(function(idx, element) {
        // We cycle through the elements using each() so that we can choose the element specifically that we wish to clean up afterward
		var ele = $(element);
			ele.tooltip({
				content: (function() {return formatTTContent(ele.attr('title'), ele.attr('class').split(' ')[1]);}),
  				classes:{"ui-tooltip":'Nik_dropdown-content'},
  				close: function (event, ui) {$(".ui-helper-hidden-accessible").remove();},
       			create: function(ev, ui) {$(this).data("ui-tooltip").liveRegion.remove();},
  				hide: false,
  				show: false
			
		});
	});



$( " ."+formaClass ).dblclick(function() {
	
		sentenceId=$(this).attr('class').split(' ')[0].replace('$','')
		console.log('dblclick '+lisid)
		if (shownSentenceList.has(sentenceId)){
			resetSentenceStructure(sentenceId)
			shownSentenceList.delete(sentenceId)
			lsid=''
			
		}
		else{
			//showSentenceStructure (sentenceId)
			shownSentenceList.add(sentenceId)
			
		}
});


$(" ."+formaClass).hover(function(idx, element) {
        
        sentenceId=$(this).attr('class').split(' ')[0].split('_')
		var tmplisid=sentenceId[0]+'_'+sentenceId[1]+'_'+sentenceId[3]
		lsentid=$(this).attr('class').split(' ')[0]
		lisid=tmplisid
	});



	
	
	jQuery(document).delegate('#sentence', 'click', function(e) {
		e.preventDefault();
		sentenceId=$(this).attr('class').split(' ')[0].replace('$','')
		console.log(sentenceId)
		if (shownSentenceList.has(sentenceId)){
			lisid=''
			resetSentenceStructure(sentenceId)
			shownSentenceList.delete(sentenceId)
		}
		else{
			//showSentenceStructure (sentenceId)
			shownSentenceList.add(sentenceId)
		}
		
	});
	
	
	
	$("#" + displayId).scroll(function() {
		if (minimapScrolling) {
			minimapScrolling = false
		}
		else {
			trackScrollCanto()
		}
	});

	jQuery(document).delegate(' .espandiFrase', 'click', function() {
		var cid  = $(this).attr('id');
		var parcid=cid.split('_');
		var cantoToShow = "#"+parcid[0]+"_"+parcid[2]
		var fraseToExpand = "#"+"Frase"+parcid[4]
		var cantoDiv = [];
		var fraseDiv = [];
		var primoVerso;
		var ultimoVerso;
		var idVerso;
		var verso;
		var fraseCorrente = $(fraseToExpand)
		var fraseElements = [];
		var divComandi = $("#comandiFrase"+parcid[4]).clone();
		
		if ( !(loadedCanti.has(cantoToShow))){
			caricaCanto(cantoToShow,parcid)
		}
		
		$(cantoToShow +" > p").each((index, elem) => {
  			cantoDiv.push(elem.id);
		});
		
		$(fraseToExpand +" > p").each((index, elem) => {
  			fraseDiv.push(elem.id);
		});
		
		$(fraseToExpand +" > p").each((index, elem) => {
  			fraseElements.push(elem);
		});
		
		idVerso = fraseDiv[0].split('_');
		primoVerso = idVerso[2];
		idVerso = fraseDiv[fraseDiv.length-1].split('_');
		ultimoVerso = parseInt(idVerso[2]);
		
		$("#comandiFrase"+parcid[4]).remove();

		if (fraseDiv.length < currentContextLength){
			if(primoVerso == 1){ //  caso inizio canto
				var divAggiunti = $("<div />")
				divAggiunti.attr('id',"FraseAggiunti"+parcid[4])
				for (i=0;i<4;i++){
					var verso  = $("#"+cantoDiv[3+i]).clone();
					divAggiunti.append(verso);
				}	
				fraseCorrente.append(divAggiunti);			
				fraseCorrente.append(divComandi);
			}else{ //  caso fine canto
				for (i=primoVerso-5;i<primoVerso-1;i--){
					var verso  = $("#"+cantoDiv[i]).clone();
					divAggiunti.append(verso);
				}					
			} 			
		}else{ 
			for (element of fraseDiv){
				$("#"+element).remove();
			}
			var divAggiunti = $("<div />")
				divAggiunti.attr('id',"FraseAggiunti"+parcid[4])
			for (i=primoVerso-5;i<primoVerso-1;i++){
					var verso  = $("#"+cantoDiv[i]).clone();
					divAggiunti.append(verso);
			}
			fraseCorrente.append(divAggiunti);

			for (element of fraseElements){
				fraseCorrente.append(element);
			}
			var divAggiunti = $("<div />")
				divAggiunti.attr('id',"FraseAggiunti"+parcid[4])	
			for (i=ultimoVerso;i<ultimoVerso+4;i++){
					var verso  = $("#"+cantoDiv[i]).clone();
					divAggiunti.append(verso);
			}	
			fraseCorrente.append(divAggiunti);	
			fraseCorrente.append(divComandi);
		}
		
		//aggiungo listeners
		addFormaListeners()
		
	});

	jQuery(document).delegate(' .riduciFrase', 'click', function() {
		var cid  = $(this).attr('id');
		var parcid=cid.split('_');
		var fraseToReduce = "#"+"FraseAggiunti"+parcid[4]
		$(fraseToReduce).remove();
		$(fraseToReduce).remove();
	
	});		
	
	function caricaCanto(canto, parcid){
			if(parcid[0].includes('Inferno'))
				showCanto(formeprima, '1',parcid[2])
			if(parcid[0].includes('Purgatorio'))
				showCanto(formeseconda, '2',parcid[2])
			if(parcid[0].includes('Paradiso'))
				showCanto(formeterza, '3',parcid[2])
			loadedCanti.add(canto)
	}

	jQuery(document).delegate(' .vaiALCanto', 'click', function() {
		var cid  = $(this).attr('id');
		var parcid=cid.split('_');
		var fraseToReduce = "#"+"FraseAggiunti"+parcid[4]

		cantoDisplayed = parcid[0]+"_"+parcid[2]
		
		if ( !(loadedCanti.has(cantoDisplayed))){
			caricaCanto(cantoDisplayed,parcid)
		}
		cantoDisplayed = "#"+cantoDisplayed
		$(fraseToReduce).remove();
		$(cantoDisplayed).attr('style', 'display: d-flex;');
		$("#vistaFrasi").css("display", "none");	
	});
/*
 * Costruzione e visualizzazione del risultato in frasi.
*/
	jQuery(document).delegate(' .lista-risultati', 'click', function(e) {
		   
			var canto, numeroCantica;
			var divVerso;
			
			currentContextLength = contextLength;
			
			$(cantoDisplayed).css("display", "none");
			
			if (!queryExecuted){
				$("#vistaFrasi").attr('style', 'display: d-flex;');
				$(cantoDisplayed).css("display", "none");
				return
			}
			
			queryExecuted = false;
			
			listarisultati.sort(function(a, b){return a - b});
			
			var elencoRisutati = $("#vistaFrasi");
			elencoRisutati.empty();
					
			var numeroRisultato = 0;
				
			for (risultato of listarisultati){
				numeroRisultato++;
				versiContesto= getFormaContext(parseInt(risultato), contextLength);
				var setVersicontesto = new Set()
				divVerso =''
				numeroCantica=0
				canto=0
				var elencoVersi = $('<div class="itemelenco" />')
				var titoloCanto = $('<h5 class="titolo-canto" />')
				
				elencoVersi.attr('id', "Frase"+numeroRisultato);

				for (forma of versiContesto){
					if (setVersicontesto.size == 0){
						numeroCantica=forma.cantica
						canto=forma.canto
						titoloCanto.append("<cite class='elencoris'>"+ getCantica(numeroCantica)+", Canto "+canto+"</cite>");
						elencoVersi.append(titoloCanto)
					}
					if (!setVersicontesto.has(forma.verso)){
						divVerso = createDivVersoGeneric(forma.cantica, forma.verso, forma.canto)
						elencoVersi.append(divVerso)
						setVersicontesto.add(forma.verso)
					}
					createSpanFormeNew(forma.testo, forma.catg, 'e'+forma.posizione, forma.periodo, forma.funzperiodo, divVerso)
				}
				
				
				var mhr=$('<hr width="100" align="center"/>')
				var comandi = $('<div />')
				comandi.attr('id',"comandiFrase"+numeroRisultato)
				var spanBadgeContext = $('<span />');				
				var contextIcon = '<ion-icon name="return-up-back-outline"></ion-icon>';
				spanBadgeContext.attr('class', 'badge badge-primary badge-pill mx-2 vaiALCanto');
				var spanBadgeExpand = $('<span />');				
				var expandIcon = '<ion-icon name="arrow-down-outline"></ion-icon>';
				spanBadgeExpand.attr('class', 'badge badge-primary badge-pill mx-2 espandiFrase');
				var spanBadgeReduce = $('<span />');				
				var reduceIcon = '<ion-icon name="arrow-up-outline"></ion-icon>';
				spanBadgeReduce.attr('class', 'badge badge-primary badge-pill mx-2 riduciFrase');
				
				spanBadgeContext.attr('id', getCantica(numeroCantica)+"Canto_e_"+canto+"_"+risultato+"_"+numeroRisultato);
				spanBadgeContext.append(contextIcon)
				
				spanBadgeExpand.attr('id', getCantica(numeroCantica)+"Canto_ex_"+canto+"_"+risultato+"_"+numeroRisultato);
				spanBadgeExpand.append(expandIcon)
				
				spanBadgeReduce.attr('id', getCantica(numeroCantica)+"Canto_er_"+canto+"_"+risultato+"_"+numeroRisultato);
				spanBadgeReduce.append(reduceIcon)

				spanBadgeContext.appendTo(comandi);
				spanBadgeExpand.appendTo(comandi);
				spanBadgeReduce.appendTo(comandi);
				comandi.appendTo(elencoVersi);
				elencoVersi.appendTo(elencoRisutati);
				elencoRisutati.append(mhr)
				
			}
					
			//evidenzio resultati
			
			for (ris of listarisultati) {
				idris = '#e' + ris
				$(idris).addClass("font-weight-bold mark ")
			}
						
			//aggiungo listeners
			addFormaListeners()
			
			//visualizzo
			$("#vistaFrasi").attr('style', 'display: d-flex;');
			manageMM("#vistaFrasi")
			
			//drawMinimap("#vistaFrasi")
	});
	
	
	jQuery(document).delegate('.navig-canto', 'click', function(e) {
		resetFrasi()
		
		//nasconde vista risultati
		$("#vistaFrasi").css("display", "none");
		
		//rimuove il grafo sintattico se c'è'
		var periodograph=document.getElementById("periodograph");
		
		if (periodograph!=null){
			let showngr=document.getElementById("periodograph").getAttribute('name').split("_")
			var tmpsent=showngr[0]+"_"+showngr[1]+"_s_"+showngr[2];
			if (shownSentenceList.has(tmpsent)){
				lisid=''
				resetSentenceStructure(tmpsent)
				shownSentenceList.delete(tmpsent)
			}
			$("#periodograph").empty()
		}
		
		
		
		$('.canto').each(function() {
			$(this).css("display", "none");
		});
		
		
		const cid=$(this).attr('name').replace(" ", "_");
		
		cantoDisplayed = "#"+cid;
		
		if ( !(loadedCanti.has(cid)))
		{
			
			var parcid=cid.split('_')
			if(parcid[0].includes('Inferno'))
				showCanto(formeprima, '1',parcid[1])
			if(parcid[0].includes('Purgatorio'))
				showCanto(formeseconda, '2',parcid[1])
			if(parcid[0].includes('Paradiso'))
				showCanto(formeterza, '3',parcid[1])
			loadedCanti.add(cid)
		}
		//$("#" + $(this).attr('name').replace(" ", "_")).css("display", "block");
		$("#" + $(this).attr('name').replace(" ", "_")).attr('style', 'display: d-flex;')
		
		//drawMinimap("#" + $(this).attr('name').replace(" ", "_"))
		manageMM("#" + $(this).attr('name').replace(" ", "_"))
		if (selectedVista=='frasi'){
			loadFrasi();
		}
		addFormaListeners();
		
	});

	
	//Query

	jQuery(document).delegate('#searchcomm, #searchcomm2', 'click', function(e) {
		e.preventDefault();
		manageQuery()
	});
	

	//Reset

	jQuery(document).delegate('#cleanresult', 'click', function(e) {
		console.log('clean')
		cleanSearchResult()
		esprlogica = []
		$('#queryText').val("")

	});
	
	//Utility functions
	
	function addFormaListeners(){
		
		$(" ." + formaClass).each(function(idx, element) {
			var ele = $(element);
			ele.tooltip({
				content: (function() { return formatTTContent(ele.attr('title'), ele.attr('class').split(' ')[1]); }),
				classes: { "ui-tooltip": 'Nik_dropdown-content' },
				close: function(event, ui) { $(".ui-helper-hidden-accessible").remove(); },
				create: function(ev, ui) { $(this).data("ui-tooltip").liveRegion.remove(); },
				hide: false,
				show: false

			});
			ele.hover(function(idx, element) {

				sentenceId = $(this).attr('class').split(' ')[0].split('_')
				var tmplisid = sentenceId[0] + '_' + sentenceId[1] + '_' + sentenceId[3]
				lsentid = $(this).attr('class').split(' ')[0]
				lisid = tmplisid

			});

		});

	}
	
	function getCantica(numeroCantica){
	
		switch (numeroCantica){
				case 1:	return("Inferno");
				case 2:	return("Purgatorio");
				case 3:	return("Paradiso");
		}	
	}
	
	function formatTTContent(categ, syntType){
		var details=[];
		
		details = getHoverContent(categ);
		
		var myitems;
		var catgramm;
		var subcatgramm = '';
		var popoverText = '';
		if (selectedVista=='frasi'){
			return '<div class="ttContent"><b>'+maptypes[syntType]+'</b></div>';
		}

		for (detail of details){
			myitems= detail.split(',');	
			
			catgramm='<div  class="ttContent">';
			subcatgramm='<p> <b>'+myitems[0]+'</b><i>'+myitems.slice(1,-1)+'</i></p></div>';			
			popoverText = popoverText + catgramm + subcatgramm;
		}
		
		return (popoverText);
	}

	function getHoverContent(categ){
		
		//console.log('Categoria '+categ)
		var mycat=[];
		if(categ.includes('^')){
			categs=categ.split('^')			
			for (cat of categs){
				mycat.push(proprietaForma(cat))
			}
			console.log(mycat.join('-'))
		}else{
			mycat.push(proprietaForma(categ));
		}
		return(mycat);
	}
	
	function proprietaForma(categ){
		if (categ[0]=='v'){
			return parserVerbi.parse(categ).split(',').filter(prop => prop.length > 0).join()
		}
		if(categ[0]=='s'){
			return parserSostantivi.parse(categ).split(',').filter(prop => prop.length > 0).join()
		}
		if(categ[0]=='e'){
			return parserPreposizioni.parse(categ).split(',').filter(prop => prop.length > 0).join()
		}
		if(categ[0]=='b'){
			return parserAvverbi.parse(categ).split(',').filter(prop => prop.length > 0).join()
		}
		if(categ[0]=='p'){
			return parserPronomi.parse(categ).split(',').filter(prop => prop.length > 0).join()
		}
		if(categ[0]=='a'){
			return parserAggettivi.parse(categ).split(',').filter(prop => prop.length > 0).join()
		}
		if(categ[0]=='r'){
			return parserArticolo.parse(categ).split(',').filter(prop => prop.length > 0).join()
		}
		if (categ[0] == 'f') {
			return parserCitazione.parse(categ).split(',').filter(prop => prop.length > 0).join();
		}
		if (categ[0] == 'n') {
			return parserOnomastica.parse(categ).split(',').filter(prop => prop.length > 0).join();
		}
		if (categ[0] == 'c') {
			return parserCongiunzione.parse(categ).split(',').filter(prop => prop.length > 0).join();
		}
		return categoriegrammaticali[categ[0]]
	}
	
	function cleanSearchResult() {
		
		$("#headingZero").css("display", "none");
		$("#vistaFrasi").empty()
		$("#vistaFrasi").css("display", "none");
		for (msid of listaPeriodiRisultato){
			$(msid).each(function(){
				$(this).removeClass("font-weight-bold mark ")
			});
		}
		
		let minim=$(" .minimap__content")
		for (forma of listarisultati) {
			idforma = '#' + forma
			$(idforma).removeClass("font-weight-bold mark ")
			minim.contents().find(idforma).removeClass("font-weight-bold mark ")
		}
		
		
		$(".badge").remove();
		//$("#headingZero").css("display", "none");
	
		listarisultati = []
		listaPeriodiRisultato=[]
		resultSentences=new Set()
		$(cantoDisplayed).attr('style', 'display: d-flex;');
		//drawMinimap(cantoDisplayed)
	}
	
	function manageMM(name){
		currentMinimap = name;
		let testhtml = $(currentMinimap)[0].outerHTML;
		let minim=$(" .minimap__content")
		let bm=minim.contents().find(' .blog-main')
		bm.empty()
		bm.append(testhtml)
		getDimensionsDiv();
	
	}
	
	var unitaRicerca='forma'
	
	function manageQuery(){
		cleanSearchResult()
		esprlogica = []
		jsonQuery=getJsonQuery()
		
		unitaRicerca=jsonQuery['unitaRicerca']
		console.log("got json query, unita ricerca: "+unitaRicerca)
		if(jsonQuery['QueryAvanzata']==0 && jsonQuery['Clausola0']['queryText']==''){
			alert('Digitare una stringa da cercare')
			return
		}
		
		jsonQuery = buildSQ(jsonQuery)
		
		myquery = new sparqlGenerator().stringify(jsonQuery)
		console.log(myquery)
		executeQuerySearch(myquery)
	}
	
	
	
	//manage sentence and clauses
	
	function showSentenceStructure(sentence) {

		sid = '.' + sentence.toString()
		//console.log(sid)
		$(sid).addClass('text-info font-italic')
		/*
		$(sid).each(function(){
			//console.log($(this).attr('class'))
			if ($(this).attr('class').includes(' Ma ')){
				$(this).addClass("text-primary font-weight-normal")
			}
			if ($(this).attr('class').includes(' Su ')){
				$(this).addClass("text-info font-weight-normal")
			}
			if ($(this).attr('class').includes(' Co ')){
				$(this).addClass("text-warning font-weight-normal")
			}
			if ($(this).attr('class').includes(' Pc ')){
				$(this).addClass("text-success font-weight-normal")
			}
			if ($(this).attr('class').includes(' Pa ')){
				$(this).addClass("text-secondary font-weight-normal")
			}
		})
		*/

	}
	
	
	
	function resetSentenceStructure(sentence) {
		/*
		$(" ." + sentence).removeClass('text-info font-weight-normal')
		$(" ." + sentence).removeClass('text-primary font-weight-normal')
		$(" ." + sentence).removeClass('text-secondary font-weight-normal')
		$(" ." + sentence).removeClass('text-warning font-weight-normal')
		$(" ." + sentence).removeClass('text-success font-weight-normal')
		*/
		$(" ." + sentence).removeClass('text-info font-italic')
	}


	//Cantica management functions
	
	function showCanto(formecantica, idcantica, canto) {
		var setVersiCanto = new Set()
		
		var cantica=cantiche[parseInt(idcantica)-1];
		var elverso, formaItem, currSentenceId;
		formecantica.map(function(item) {
			formaItem = item.split("_");
			var sentenceid=idcantica+"_"+formaItem[1]+"_s_"+formaItem[5]
			if (formaItem[1]==canto){
				if (! setVersiCanto.has(cantica + "_" + formaItem[3] + "_" + 'Canto_' + formaItem[1])){
					if(currSentenceId!=null && currSentenceId != sentenceid){
						createSpanPeriodiTag(closeSTag, 'c', formaItem[2]-1, currSentenceId, elverso)
						currSentenceId=null
					}
					elverso=createDivVersoNew(cantica, formaItem[3], 'Canto_' + formaItem[1])
					setVersiCanto.add(cantica+ "_" + formaItem[3] + "_" + 'Canto_' + formaItem[1])
				}
				if(currSentenceId==null || currSentenceId != sentenceid){
					if (currSentenceId!=null){
						createSpanPeriodiTag(closeSTag, 'c', formaItem[2]-1, currSentenceId, elverso)
					}
					currSentenceId=sentenceid;
					createSpanPeriodiTag(openSTag, 'o', formaItem[2], sentenceid, elverso)
				}
				createSpanFormeNew(formaItem[0], formaItem[4], formaItem[2], sentenceid,formaItem[6],elverso)
			
			}
			
		})
		
		if (listaPeriodiRisultato.length){
			for (msid of listaPeriodiRisultato){
				$(msid).each(function(){
					$(this).addClass("font-weight-bold mark ")
				});
			}
		}			
		
		if (listarisultati.length){
			//evidenzia risultati
			for (ris of listarisultati) {
				idris = '#' + ris
				$(idris).addClass("font-weight-bold mark ")
	
			}
		}
		
	}

	function createSpanPeriodiTag(separator, catgramm, pos, sentenceid, elementoverso) {
		var spanoccorrenza = $('<span />')
		spanoccorrenza.attr('id', 'sep_'+pos)
		spanoccorrenza.attr('title', catgramm)
		spanoccorrenza.attr('class', sentenceid+' sentencetag')
		spanoccorrenza.append(separator+" ")
		if (separator==closeSTag){
			varsupel=$('<sup />')
			varsupel.append(sentenceid.split('_')[3]+' ')
			varsupel.appendTo(spanoccorrenza)
		}
		spanoccorrenza.css("display", "none")
		spanoccorrenza.appendTo(elementoverso)

	}
	
	function createSpanFormeNew(forma, catgramm, pos, sentenceid, clausefunct, elementoverso) {
		var spanoccorrenza = $('<span />')
		spanoccorrenza.attr('id', pos)
		//spanoccorrenza.attr('data-cg', catgramm)
		spanoccorrenza.attr('title', catgramm)
		spanoccorrenza.attr('class', sentenceid+" "+clausefunct+' '+formaClass)
		spanoccorrenza.append(forma+" ")
		
		spanoccorrenza.appendTo(elementoverso)

	}
	function createDivVersoNew(cantica, num, canto) {
		
			var elementoverso = createDivVersoGeneric(cantica, num, canto)
			
			elementoverso.appendTo('#' + cantica + canto)
			return elementoverso

	}
	
	function createDivVersoGeneric(cantica, num, canto) {
		
			var elementoverso = $('<p />')
			var spannum=$('<span />')
			spannum.append(num + ". ")
			spannum.attr('class', 'numverso text-muted')
			elementoverso.append(spannum)
			//elementoverso.append(num + ". ")
			//elementoverso.attr("style", "line-height: 0.5em")

			elementoverso.attr('class', 'f6 mb-2 text-dark text-nowrap font-weight-lighter '+cantica+' '+canto)

			elementoverso.attr('id', cantica + "_" + canto + "_" + num)
			
			return elementoverso
	}
	
	
	function createAllDivCanti() {
		var cantiche=["Inferno", "Purgatorio","Paradiso"]
		var divFrasi = $('<div />')
		var divDialoghi = $('<div />')
		var divMetafore = $('<div />')
		
		//var titoloFrasi = $('<h4 class="titolo-canto pb-2" />')
		var titoloDialoghi = $('<h4 class="titolo-canto pb-2" />')
		var titoloMetafore = $('<h4 class="titolo-canto pb-2" />')

		//titoloFrasi.append("Frasi:");
		titoloDialoghi.append("Dialoghi:");
		titoloMetafore.append("Metafore:");

		divFrasi.attr('id', "vistaFrasi")
		divDialoghi.attr('id', "vistaDialoghi")
		divMetafore.attr('id', "vistaMetafore")
		
		divFrasi.appendTo('#displaycanto')
		divDialoghi.appendTo('#displaycanto')
		divMetafore.appendTo('#displaycanto')
		
		divFrasi.css("display", "none")
		divDialoghi.css("display", "none")
		divMetafore.css("display", "none")

		//titoloFrasi.appendTo(divFrasi)
		titoloDialoghi.appendTo(divDialoghi)
		titoloMetafore.appendTo(divMetafore)

		
		for (cantica of cantiche){
			for (var i=1; i<35; i++){
				if(i==34 && cantica!=="Inferno"){
					continue
				}
			canto= "Canto "+i
			var divcanto = $('<div />')
			var titolocanto = $('<h4 class="titolo-canto pb-2" />')
			titolocanto.append(cantica + ", " + canto)
			divcanto.attr('class', 'canto')
			divcanto.css("display", "none")

			divcanto.attr('id', (cantica + canto).replace(" ", "_"))
			titolocanto.appendTo(divcanto)
			divcanto.appendTo('#displaycanto')
			}
		}
	}

	//execute query
	
	async function executeQuerySearch(query) {
		seachbBindingsStream = await myEngine.queryBindings(query, { sources: [{ type: 'sparql', value: sparqlEndpoint },], });
		//console.log(query)
		alert(query)
		try {
			var result = new Set()
			var resultClauses = new Set()
			
			var resultsInCantica = []
			var resultsInCanto = []
			seachbBindingsStream.on('data', (binding) => {
				//cantica
				if (binding.has('Cantica'))
					cantica = binding.get('Cantica').value;
				else
					cantica='Nessuna'
				
				
				//canto
				if (binding.has('Canto'))
					canto = binding.get('Canto').value;
				else
					canto='Canto 0'
				
				//numero del verso
				if (binding.has('NumeroVerso'))
					numverso = binding.get('NumeroVerso').value;
				else
					numverso=0
				//posizione del frammento
				if (binding.has('pos'))
					pos = binding.get('pos').value;
				else{
					pos = 0;
				}
				
				//regione della clausola
				var clfrom=binding.get('clfr').value;
				var clto=binding.get('clto').value;
				var cltype=binding.get('clatype').value
				//id del periodo
				var sentenceid=binding.get('sentence').value.replace('http://dantenetwork.it/data/commedia/','')
				
				if (pos>0 && !result.has(pos)){
					
					result.add(pos)
					resultsInCantica.push(cantica);
					resultsInCanto.push(cantica + canto)
				}
				resultClauses.add(sentenceid + "-" +clfrom+'-'+clto+"-"+cltype+'-'+cantica+'-'+canto)
				resultSentences.add(sentenceid)
	
			});
			seachbBindingsStream.on('end', () => {
				var resSent=new Set()
				let minim=$(" .minimap__content")
				console.log('start rendering...')
				listarisultati = Array.from(result)
				var listaclausole=Array.from(resultClauses)

				cantiche = ["Inferno", "Purgatorio", "Paradiso"]
				
				if (!listarisultati.length || unitaRicerca=='frase'){
					
					resultsInCantica=[]
					resultsInCanto=[]
					listaPeriodiRisultato=[]
					if (listaclausole.length){
						for (var frase of listaclausole){
							var fraseItems=frase.split('-');
							for (var p=parseInt(fraseItems[1]); p<parseInt(fraseItems[2])+1;p++){
								
								listarisultati.push(p)	
							}
							if (!resSent.has(fraseItems[0]+'-'+fraseItems[3])){
								resSent.add(fraseItems[0]+'-'+fraseItems[3])
								resultsInCantica.push(fraseItems[4]);
								resultsInCanto.push(fraseItems[4] + fraseItems[5])
							}
							
						}
					}
				}
				if (unitaRicerca=='periodo' && listaclausole.length){
					resultsInCantica=[]
					resultsInCanto=[]
					listaPeriodiRisultato=[]
					for (var frase of listaclausole){
						var fraseItems=frase.split('-');
						var mysid = '.' + fraseItems[0].toString()
						console.log(mysid)
						//$(mysid).addClass('font-italic')
						//$(mysid).addClass("font-weight-bold mark ")
						listaPeriodiRisultato.push(mysid)
						$(mysid).each(function(){
							//console.log('add id '+$(this).attr('id'));
							listarisultati.push($(this).attr('id'))
						});
						if (!resSent.has(fraseItems[0])){
							resSent.add(fraseItems[0])
							resultsInCantica.push(fraseItems[4]);
							resultsInCanto.push(fraseItems[4] + fraseItems[5])
						}
						
					}
					
					
				}
				
				if (listarisultati.length){
					//evidenzia risultati
					
					for (ris of listarisultati) {
						idris = '#' + ris
						$(idris).addClass("font-weight-bold mark ")
						minim.contents().find(idris).addClass("font-weight-bold mark ")
						
					}
					
					
				}
				
				
				//aggiunge badge con totale risultati accanto alle cantiche
				i = 0
				var totResultN=0;
				var listIcon = '<ion-icon name="list-outline"></ion-icon>';

				for (cantica of cantiche) {
					i += 1
					let count = resultsInCantica.reduce((n, x) => n + (x === cantica), 0);
					if (count>0){
						totResultN+=count
						var spanbadgecantica = $('<span />');
						spanbadgecantica.attr('class', 'badge badge-warning badge-pill mx-2');
						spanbadgecantica.append(count)
						spanbadgecantica.appendTo($('#cantica' + i + '-badge'))
						//$('#cantica' + i).after(spanbadgecantica)
					}
				}
				//aggiunge badge con totale risultati nel bottone lista risultati
				if (totResultN>0){
					$("#headingZero").attr('style', 'display: d-flex;')
					var spanbadgelista = $('<span />');
					spanbadgelista.attr('class', 'badge badge-primary badge-pill mx-2 lista-risultati');
					spanbadgelista.append(totResultN+listIcon)
					spanbadgelista.appendTo($('#cantica0-badge'))
				}
				//aggiunge badge con totale risultati accanto ai canti
				
				console.log('results end...')
				
				//console.log(sid)
				var $nctags= $(' .navig-canto')
		
		
				for (cantica of cantiche) {
					for (k of Array(35).keys()) {
						if (k == 0)
							continue
						let count = resultsInCanto.reduce((n, x) => n + (x === cantica + 'Canto ' + k), 0);
						if (count>0){
							var spanbadge = $('<span />');
							spanbadge.attr('class', cantobadgeclass);
							spanbadge.append(count)
							//spanbadge.appendTo($('[name="' + cantica + 'Canto ' + k + '"]'))
							spanbadge.appendTo($nctags.filter('[name="' + cantica + 'Canto ' + k + '"]'))
							//spanbadge.insertAfter($('[name="'+cantica+'Canto '+k+'"]'))
						}
					}
				}
				console.log('badge end')

				/*
				//aggiorna minimap
				
				if (currentMinimap != '') {
					showMinimap()
				}
				*/
			});
			queryExecuted = true;
			$(cantoDisplayed).attr('style', 'display: d-flex;');
			$("#vistaFrasi").css("display", "none");
		}
		catch (err) {
			console.log(err.message);
		};

	};

/*
*	REGOLE DI PARSING PER VISUALIZZAZIONE CATEGORIE GRAMMATICALI 
*/

const categoriegrammaticali={"v":"Verbo", "s":"Sostantivo", "a":"Aggettivo", "p":"Pronome", "r":"Articolo", "b":"Avverbio","e":"Preposizione", 
								"c":"Congiunzione", "i":"Interiezione", "n":"Onomastica", "f":"Citazione", "l":"Locuzione", 
								"r-e":"Articolo, Preposizione", "b-v":"Avverbio, Verbo", "p-v":"Pronome, Verbo", 
								"b-p-v":"Avverbio, Pronome, Verbo", "b-p":"Avverbio, Pronome", 
								"e-p":"Preposizione, Pronome", "a-s":"Aggettivo, Sostantivo",
								"e-r":"Preposizione, Articolo", "v-b":"Verbo, Avverbio", "v-p":"Verbo, Pronome", 
								"v-p-b":"Verbo, Pronome, Avverbio", "p-b":"Pronome, Avverbio", 
								"p-e":"Pronome, Preposizione", "s-a":"Sostantivo, Aggettivo",}


var categoriegrammaticaliGrammar=`Expression = head:(Filtro){return 'Verbo,'+head.join()}
Filtro= fhead:("v")? tail:( transitivita? diatesi? impersonalita?
    						coniugazione? modotempo?
                            persona? funzione? declinazione?
                            genere? numero? grado?){return tail}
    

diatesi= [a|p] {if (text()=='a') return ' Attivo'; else return ' Passivo';}
    
transitivita=[i|t]? {if (text()=='t') return ' Transitivo'; else if (text()=='i') return ' Intransitivo';}

impersonalita=([*|+])? {if (text()=='*') return ' Impersonale'; else if (text()=='+')return ' Riflessivo';}

coniugazione=[1|2|3|4|5]? {switch(parseInt(text())){
							case(1): return ' Prima coniugazione';
                            case(2): return ' Seconda coniugazione';
                            case(3): return ' Terza coniugazione';
                            case(4): return ' Ausiliare essere'
                            case(5): return ' Ausiliare avere'}}
modotempo=modo:"ip" {return(' Presente indicativo')}/
			   "ib" {return(" Passato Prossimo Indicativo")}/
			   "ii" {return(" Imperfetto Indicativo")}/
              "ir" {return(" Passato Remoto Indicativo")}/
              "is" {return( " Trapassato Prossimo Indicativo")}/
              "it" {return( " Trapassato Remoto Indicativo")}/
              "if" {return(" Futuro Semplice Indicativo")}/
              "ia" {return(" Futuro Anteriore Indicativo")}/
              "cp" {return( " Presente Congiuntivo")}/
              "ci" {return( " Imperfetto Congiuntivo")}/
              "cr" {return( " Passato Congiuntivo")}/
              "ct" {return( " Trapassato Congiuntivo")}/
              "dp" {return( " Presente Condizionale")}/
              "dr" {return( " Passato Condizionale")}/
              "mp" {return( " Presente Imperativo")}/
              "fp" {return( " Presente Infinito")}/
              "fr" {return( " Passato Infinito")}/
              "pp" {return( " Presente Participio")}/
              "pr" {return( " Passato Participio")}/
              "gp" {return( " Presente Gerundio")}/
              "gr" {return( " Passato Gerundio")}/
              "pf" {return( " Participio Futuro")} 
persona="s1" {return(' Prima persona singolare')}/
		"s2" {return(' Seconda persona singolare')}/
        "s3" {return(' Terza persona singolare')}/
        "p1" {return(' Prima persona plurale')}/
        "p2" {return(' Seconda persona plurale')}/
        "p3" {return(' Terza persona plurale')}


funzione="a" {return(' Verbo Funzione Aggettivo')}/
		"sm" {return(' Verbo Funzione Sostantivo maschile')}/
        "sf" {return(' Verbo Funzione Sostantivo femminile')}/
        "b" {return(' Verbo Funzione Avverbio')}/
        "l" {return(' Verbo Funzione Locuzione')}


declinazione=[1|2|3|4|5] {switch(parseInt(text())){
							case(1): return ' Prima declinazione';
                            case(2): return ' Seconda declinazione';
                            case(3): return ' Terza declinazione';
                            case(4): return ' nd'
                            case(5): return ' nd'}}
                     
genere=[f|m] {if (text()=='f') return ' Femminile'; else if (text()=='m') return ' Maschile';}

numero=[s|p] {if (text()=='s') return ' Singolare'; else if (text()=='p') return ' Plurale';}

grado="c+" {return(' Grado c+ singolare')}/
		"c-" {return(' Grado c-')}/
        "c=" {return(' Grado c=')}

Integer "integer"
  = _ [0-9]+ { return parseInt(text(), 10); }

_ "whitespace"= " "*

`

var categoriaGrammaticaleSostantivo = `
Expression = head:(Filtro){return 'Sostantivo,'+head.join()}
Filtro= fhead:("s")? tail:( genereforma? declinazionesostantivo? generelemma?
    						numersingolareplurale? locuzione?){return tail}
    

declinazionesostantivo= [1|2|3]? {switch(parseInt(text())){
							case(1): return ' Prima declinazione';
                            case(2): return ' Seconda declinazione';
                            case(3): return ' Terza declinazione'}}
    
genereforma=[m|f]? {if (text()=='m') return ' forma maschile'; else if (text()=='f') return ' forma femminile';}

generelemma=[m|f]? {if (text()=='m') return ' lemma maschile'; else if (text()=='f') return ' lemma femminile';}

numersingolareplurale=[s|p]? {if (text()=='s') return ' numero singolare'; else if (text()=='p') return ' numero plurale';}

locuzione="Iv" {return('In Locuzione verbo');}

Integer "integer"
  = _ [0-9]+ { return parseInt(text(), 10); }

_ "whitespace"= " "*

`

var categoriaGrammaticalePreposizione = `
Expression = head:(Filtro){return 'Preposizione,'+head.join()}
Filtro= fhead:("e")? tail:( tipo1? tipo2? sintassi? complemento1? complemento2?){return tail}
    

tipo1=[p|i] {if (text()=='i') return ' Impropria'; else if (text()=='p') return ' Impropria';}
tipo2=modo:"a" {return(' Articolata')}/
			   "lx" {return(" In locuzione separata")}/
			   "l" {return(" In locuzione")} /
               "s" {return(" Semplice")}
               
sintassi=[sodbfcnutmezlpa] {if (text()=='s') return ' Soggettiva'; 
							if (text()=='o') return ' Oggettiva';
                            if (text()=='d') return ' Dichiarativa';
                            if (text()=='b') return ' Completiva obliqua';
                            if (text()=='f') return ' Finale';
                            if (text()=='c') return ' Causale';
                            if (text()=='n') return ' Concessiva';
                            if (text()=='u') return ' Consecutiva';
                            if (text()=='t') return ' Temporale';
                            if (text()=='m') return ' Modale';
                            if (text()=='e') return ' Eccettuativa';
                            if (text()=='z') return ' Esclusiva';
                            if (text()=='l') return ' Limitativa';
                            if (text()=='p') return ' Comparativa';
                            if (text()=='a') return ' Avversativa';}
                            
complemento1="ktd" {return(" Di tempo determinato")} /
               "ktc" {return(" Di tempo continuato")} /
               "kt" {return(' Di tempo')}/
			   "kdl" {return(" Di moto da luogo")} /
			   "kd" {return(" Di termine")}/
			   "kv" {return(" Di vantaggio")} /
               "ksl" {return(" Di stato in luogo")} /
               "ks" {return(" Di svantaggio")} /
               "kg" {return(" Di specificazione")} /
               "kml" {return(" Di moto a luogo")} /
               "km" {return(" Di modo")} /
               "kw" {return(" Di mezzo")} /
               "kc" {return(" Di compagnia")} /
               "ku" {return(" Di unione")} /
               "ka" {return(" Di allontanamento/separazione")} /
               "kz" {return(" Di materia")} /
               "kl" {return(" Di luogo")} /
               "ko" {return(" Di sostanza")} /
               "kpl" {return(" Di moto per luogo")} /
               "kps" {return(" Predicativa del soggetto")} /
               "kpo" {return(" Predicativa dell'oggetto")}
               
           
complemento2= 
    "kp" {return(" Di Limitazione")} /
    "kq" {return("  Di Qualità")} /
    "kr" {return("  Di Causa")} /
    "ki" {return("  Di Agente")} /
    "ke" {return("  Di Causa Efficiente")} /
    "kf" {return("  Di Fine Scopo")} /
    "ky" {return("  Di Paragone")} /
    "kx" {return("  Di Argomento")} /
    "kb" {return("  Distributivo")} /
    "kj" {return("  Di Sostituzione")} /
    "kn" {return("  Di Estensione")} /
    "k1b" {return("  Indiretta Benefattiva")} /
    "k1p" {return("  Indiretta Possessore")} /
    "k1o" {return(" Indiretta Oggetto")} /
    "k1d" {return(" Indiretta Dativo")} /
    "k1e" {return(" Indiretta Esperiente")} /
    "k2" {return(" Simmetrica")} /
    "k3" {return(" Di Pena")} /
    "k4" {return("  Di Effetto")} /
    "k5" {return("  Concessiv")} /
    "k6" {return(" Di Origine Provenienza")} /
    "k7" {return(" Di Abbondanza/Privazione")} /
    "k8" {return(" Partitiva")} /
    "k9" {return(" Di Denominazione")} /
    "k10" {return(" Di Colpa")} /
    "k11" {return(" Di Quantità")} /
    "k12" {return(" Di Peso")} /
    "k13" {return(" Di Esclusione")} /
    "k14" {return(" Di Rapporto")}

`
var avverbio = ` Expression = head:(Filtro){return 'Avverbio,'+head.join()}
Filtro= fhead:("b")? tail:( fake?  tipo?){return tail}
     
fake= ""

tipo="c+" {return(' Avverbio al Comparativo di Maggioranza')}/
        "c-" {return(' Avverbio al Comparativo di Minoranza')}/
        "sa" {return(' Avverbio al Superlativo Assoluto')}/
        "sr" {return(' Avverbio al Superlativo Relativo')}/
        "lz" {return(' Avverbio in Locuzione Separato')}/
        "l" {return(' Avverbio in Locuzione')}/
        "y" {return(' Avverbio Proclitico')}/
        "x" {return(' Avverbio Enclitico')}/
        "c" {return(' Avverbio al Comparativo di Uguaglianza')}


Integer "integer"
  = _ [0-9]+ { return parseInt(text(), 10); }

_ "whitespace"= " "*

`

var pronome = `

Expression = head:(Filtro){return 'Pronome,'+head.join()}
Filtro= fhead:("p")? tail:(  tipo_pronome? classe_pronome? genere_pronome? 
		numero_pronome?  forma_pronome? funzione_pronome? tiporiflessivi?){return tail}
    

tipo_pronome= "p" {return(' Pronome Personale')}/
			  "f" {return(" Pronome Riflessivo")}/
			  "s" {return(" Pronome Possessivo")}/
              "d" {return(" Pronome Dimostrativo")}/
              "i" {return(" Pronome Indefinito")}/
              "r" {return(" Pronome Relativo")}/
              "t" {return(" Pronome Interrogativo")}/
              "e" {return(" Pronome Esclamativo")}/
              "n" {return(" Pronome Numerale")} 
    
classe_pronome=	"1" {return(" Prima Classe Persona")}/
              	"2" {return(" Seconda Classe Persona")}/
              	"3" {return(" Terza Classe Persona")} 

genere_pronome=	"m" {return(" Maschile")}/
              	"f" {return(" Femminile")}/
              	"n" {return(" Neutro")} 
numero_pronome=	"s" {return(" Singolare")}/
              	"p" {return(" Plurale")}
forma_pronome= 	"l" {return(" Pronome Libero")}/
              	"i" {return(" Pronome Libero In Composizione")}/
              	"y" {return(" Pronome Proclitico")}/
             	"x" {return(" Pronome Enclitico")} 
funzione_pronome="so" {return(' Libero Soggetto')}/
		"soi" {return(' Libero Soggetto Impersonale')}/
        "co" {return(' Libero Complemento')}/
        "ra" {return(' Libero Rafforzativo')}/
        "ac" {return(' Clitico Accusativo')}/
        "da" {return(' Clitico Dativo')}/
        "pt" {return(' Clitico Partitivo')}


tiporiflessivi="pr" {return(' Proprio')}/
		"le" {return(' Lessicalizzato')}/
        "im" {return(' Impersonale')}/
        "pa" {return(' Passivo')}/
        "re" {return(' Reciproco')}


Integer "integer"
  = _ [0-9]+ { return parseInt(text(), 10); }

_ "whitespace"= " "*

`
var categoriaGrammaticaleAggettivo = `
Expression = head:(Filtro){return 'Aggettivo,'+head.join()}
Filtro= fhead:("a")? tail:(  tipo_aggettivo classe_aggettivo? genere_aggettivo? 
		numero_aggettivo? grado_aggettivo? tipo_complemento? tipo_frase? 
		oggetto_indiretto?){return tail}

tipo_aggettivo = 
		"i" {return(" Indefinito")}/
		"t" {return(" Interrogativo")}/
		"e" {return(" Esclamativo")}/
		"n" {return(" Numerale")}/
		"d" {return(" Dimostrativo")}/
		"r" {return(" Relativo")}/
		"s" {return(" Possessivo")}/
		"l" {return(" In locuzione")}/
		"" 	{return(" Qualificativo")} 

    
classe_aggettivo =	"1" {return(" Prima Classe")}/
              		"2" {return(" Seconda Classe")} 

genere_aggettivo=	"m" {return(" Maschile")}/
              		"f" {return(" Femminile")}/
              		"n" {return(" Neutro")} 
              	
numero_aggettivo=	"s" {return(" Singolare")}/
              		"p" {return(" Plurale")}
              	
grado_aggettivo = 	"c+" {return(" Comparativo Di Maggioranza")}/
					"c-" {return(" Comparativo Di Minoranza")}/
        			"c=" {return(" Comparativo Di Uguaglianza")}/
        			"sr" {return(" Superlativo Relativo")}/
        			"sa" {return(" Superlativo Assoluto")}        		
        
tipo_complemento ="xc10" {return(" Introdotto Da VERSO")}/
    	"xc11" {return(" Introdotto Da SOPRA")}/
    	"xc12" {return(" Introdotto Da SOTTO")}/
    	"xc13" {return(" Introdotto Da DINANZI")}/
      	"xc1"  {return(" Introdotto Da A")}/ 
    	"xc2"  {return(" Introdotto Da CON")}/
   		"xc3"  {return(" Introdotto Da CONTRO")}/
    	"xc4"  {return(" Introdotto Da DA")}/
   	 	"xc5"  {return(" Introdotto Da DI")}/
    	"xc6"  {return(" Introdotto Da IN")}/
    	"xc7"  {return(" Introdotto Da PER")}/
    	"xc8"  {return(" Introdotto Da SU")}/
    	"xc9"  {return(" Introdotto Da TRA")}/ 	
    	"xc"   {return(" Introdotto Da Preposizione")}/
    	"xo1"  {return(" Oggetto Ind")}/
    	"xo5"  {return(" Oggetto Ind Compl Con DI")}/
    	"xo"   {return(" Oggetto Ind Pronom")}
        


tipo_frase =
    "xf1" {return("Con Infinito Retto Da A")}/
    "xf2" {return("Con Infinito Retto Da DA")}/
    "xf3" {return("Con Infinito Retto Da DI")}/
    "xf4" {return("Con Infinito Retto Da PER")}/
    "xf5" {return("Con Infinito Retto Da SE")}/
    "xh1" {return("Con Subordinata All Indicativo")}/
    "xh2" {return("Con Subordinata Al Congiuntivo")}/
    "xz1" {return("In Locuzione Imp Infinito")}/
    "xz2" {return("In LocuzioneImp Che Indicativo")}/
    "xz3" {return("In Locuzione Imp Che Congiuntivo")}/
    "xz4" {return("In Locuzione Imp Se Indicativo")}/
    "xz5" {return("In Locuzione Imp Se Congiuntivo")}/
    "xz6" {return("In Locuzione Imp Come Indicativo")}/
    "xz7" {return("In Locuzione Imp Quando Indicativo")}/
    "xz8" {return("In Locuzione Imp Perché Congiuntivo")}/
    "xz9" {return("In Locuzione Imp A Infinito")}
        

oggetto_indiretto = 
        ",o" {return(" Con Oggetto Indiretto")}
        
        
Integer "integer"
  = _ [0-9]+ { return parseInt(text(), 10); }

_ "whitespace"= " "*
		
`
var categoriaGrammaticaleArticolo = `

Expression = head:(Filtro){return 'Articolo,'+head.join()}
Filtro= fhead:("r")? tail:(  tipo? genere? numero?){return tail}

tipo = 
		"d" {return(" Determinativo")}/
		"i" {return(" Indeterminativo")} 

    

genere =	"m" {return(" Maschile")}/
             "f" {return(" Femminile")}
              	
numero =	"s" {return(" Singolare")}/
            "p" {return(" Plurale")}
 
        
Integer "integer"
  = _ [0-9]+ { return parseInt(text(), 10); }

_ "whitespace"= " "*
		

`
var citazione = `
Expression = head:(Filtro){return 'Citazione,'+head.join()}
Filtro= fhead:("f") tail:(  fake? tipo?){return tail}

fake = ""
tipo="l" {return(' Citazione Latina')}/
        "p" {return(' Citazione Provenzale')}/
        "r" {return(' Citazione Francese')}/
        "s" {return(' Citazione Spagnola')}/
        "e" {return(' Citazione Ebraica')}/
        "g" {return(' Citazione Greca')}

Integer "integer"
  = _ [0-9]+ { return parseInt(text(), 10); }

_ "whitespace"= " "*

`
	var onomastica = `Expression = head:(Filtro){return 'Onomastica,'+head.join()}
Filtro= fhead:("n") tail:(  proprio tipo?){return tail}

tipo="x" {return(' Separato')}/
        "t" {return(' Titolo')}
proprio = "p" {return("Nome Proprio")}

Integer "integer"
  = _ [0-9]+ { return parseInt(text(), 10); }

_ "whitespace"= " "*
`
	var congiunzione = ` 
Expression = head:(Filtro){return 'Congiunzione,'+head.join()}
Filtro= fhead:("c") tail:(  tipo? cordinativasubordinativa? tipocoordinativa? 
		tiposubordinativa*  complementodue?){return tail}
    

tipo = "lx" {return(' LocuzioneSeparata')}/
			  "c" {return(" Composta")}/
			  "l" {return(" Locuzione")}/
              "s" {return(" Semplice")} 
    
cordinativasubordinativa =	"c" {return(" Coordinativa")}/
              	"s" {return(" Subordinativa")} 

tipocoordinativa =	"c" {return(" Copulativa")}/
              	"d" {return(" Disgiuntiva")}/              	
              	"a" {return(" Avversativa")}/              	
              	"n" {return(" Conclusiva")}/              	
              	"e" {return(" Esplicativa")}/      	
              	"r" {return(" Correlativa")} 
tiposubordinativa =	"s" {return(" Soggettiva")}/
              	"o" {return(" Oggettiva")}/
              	"d" {return(" Dichiarativa")}/              	
              	"b" {return(" Completiva Obliqua")}/              	
              	"i" {return(" Interrogativa")}/              	
              	"f" {return(" Finali")}/
              	"c" {return(" Causali")}/
              	"n" {return(" Concessiva")}/              	
              	"u" {return(" Consecutiva")}/              	
              	"t" {return(" Temporale")}/              	
              	"m" {return(" Modale")}/
              	"e" {return(" Eccettuativa")}/
              	"p" {return(" Comparativa")}/              	
              	"v" {return(" Condizionale")}/              	
              	"z" {return(" Esclusiva")}/              	
              	"l" {return(" Limitativa")} 
complementodue = 	
             	"x" {return(" Locuzione Separata")} 

Integer "integer"
  = _ [0-9]+ { return parseInt(text(), 10); }

_ "whitespace"= " "*
`
//parser per categorie grammaticali
var parserVerbi = peg.generate(categoriegrammaticaliGrammar);
var parserSostantivi = peg.generate(categoriaGrammaticaleSostantivo);
var parserPreposizioni = peg.generate(categoriaGrammaticalePreposizione);
var parserAvverbi = peg.generate(avverbio);
var parserPronomi = peg.generate(pronome);
var parserAggettivi = peg.generate(categoriaGrammaticaleAggettivo);
var parserArticolo = peg.generate(categoriaGrammaticaleArticolo);
var parserCitazione = peg.generate(citazione);
var parserOnomastica = peg.generate(onomastica);
var parserCongiunzione = peg.generate(congiunzione);


});