/**
 * 
 */
 var resetResult;
 
$(document).ready(function() {
	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",}

	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 listaVersi = new Set()

	var currentMinimap = ''
	var listarisultati = [];
	var resultSentences = new Set()
	var minimapScrolling = false;
	var displayId = 'displaycanto'
	var minimapTopPos;
	
	//used in minimap
	//
	let minimap = document.createElement('div');
	let minimapSize = document.createElement('div');
	let viewer = document.createElement('div');
	let minimapContent = document.createElement('iframe');
	let scale = 0.1;
	let realScale;
	let mappedElement = '';
	
	resetResult=function(){
		//console.log('clean result')
		cleanSearchResult()
		esprlogica = []
	}
	
	hideMinimap();
	createAllDivCanti()
	const start = performance.now();
	showCantica('Inferno')
	showCantica('Purgatorio')
	showCantica('Paradiso')
	$("#InfernoCanto_1").attr('style', 'display:block')
	drawMinimap("InfernoCanto_1")
	const end = performance.now();
	console.log(`Load cantiche time: ${end - start} ms`);

	

	$("[data-cg]").hover(function() {
		var details=getHoverContent($(this).data("cg"))
		var index = details.indexOf(",");
		var categoria = "";
		if (index != -1){
			categoria = details.substring(0,index);
			details = details.substring(index+1);
		}else{
			categoria = details;
			details = "";
		}
		$(this).popover({title: categoria, content: details, trigger: "click"}); 
	});

	var mmih = 0
	var mmiw = 0
	
	
	$("#" + displayId).scroll(function() {
		if (minimapScrolling) {
			minimapScrolling = false
			console.log('no scroll')
		}
		else {
			console.log('yes scrolling')
			console.log("viewer top pos before: " + $('#minimapviewer').offset().top)
			trackScrollCanto()
			console.log("viewer top pos after: " + $('#minimapviewer').offset().top)
		}
	});


	jQuery(document).delegate('.navig-canto', 'click', function(e) {
		$('.canto').each(function() {
			$(this).attr("style", 'display:none');
		});
		// Crea id per la div che contiene il canto
		$("#" + $(this).attr('name').replace(" ", "_")).attr('style', 'display:block')
		manageMiniMap(this);
		
	});

	function manageMiniMap(divElem) {
		mmiw = $("#" + displayId).innerWidth();
		mmih = $("#" + displayId).innerHeight();
		drawMinimap($(divElem).attr('name').replace(" ", "_"))
	}
	
	//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 getHoverContent(categ){
		//console.log('Categoria '+categ)
		if(categ.includes('^')){
			categs=categ.split('^')
			mycat=[]
			for (cat of categs){
				mycat.push(cat[0])
			}
			console.log(mycat.join('-'))
			return categoriegrammaticali[mycat.join('-')]
		}
		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()
		}
		//console.log(categ[0])
		return categoriegrammaticali[categ[0]]
	}
	
	function drawMinimap(name){
		
		showMinimap(name)
		currentMinimap = name;

		//mmviewer diventa draggable
		var minimapTopPos = $('#minimapviewer').offset().top
		console.log("top viewer init " + minimapTopPos)

		$('#minimapviewer').draggable({
			axis: "y",
			containment: $('#displayminimap'),
			scroll: false,
			start: function(event, ui) { minimapScrolling = true; },
			stop: function(event, ui) { minimapScrolling = false; },
			drag: function(event, ui) {

				minimapScrolling = true;
				trackScrollViewer(ui.offset.top - minimapTopPos);
				console.log(ui);
			}
		});
	}
	
	function cleanSearchResult() {

		$(".badge").remove();

		//$( " .text-info" ).removeClass('text-info')
		$(" .text-info.font-weight-normal").removeClass('text-info font-weight-normal')//.addClass('f6 text-secondary text-nowrap font-weight-lighter')
		$(" .font-weight-bold.mark ").removeClass("font-weight-bold mark ")
		for (sentence of resultSentences){
			sid='.' +sentence.toString()
			$(sid).removeClass('font-italic')
		}
		
		listarisultati = []
		resultSentences=new Set()
		if (currentMinimap != '')
			showMinimap(currentMinimap)
	}
	
	
	function manageQuery(){
		cleanSearchResult()
		esprlogica = []
		jsonQuery=getJsonQuery()
		console.log("got json query")
		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)
	}
	
	//minimap management
	

	function showMinimap(element) {
		mmplace = document.getElementById('displayminimap')
		minimap.className = 'minimap__container'
		minimapSize.className = 'minimap__size'
		viewer.className = 'minimap__viewer'
		viewer.id = 'minimapviewer'
		minimapContent.className = 'minimap__content'
		minimap.append(minimapSize, viewer, minimapContent);

		mmplace.appendChild(minimap)

		let html = document.getElementById(element).outerHTML//innerHTML
		if (html == null | html == '')
			return;

		let iFrameDoc = minimapContent.contentWindow.document;
		var cssLinkb = document.createElement("link");
		cssLinkb.href = "https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css";
		cssLinkb.rel = "stylesheet";
		cssLinkb.type = "text/css";

		var cssLinkscroll = document.createElement("link");
		cssLinkscroll.href = "./css/browsingldc.css";
		cssLinkscroll.rel = "stylesheet";
		cssLinkscroll.type = "text/css";

		iFrameDoc.open();
		iFrameDoc.write(html);
		iFrameDoc.close();

		iFrameDoc.head.appendChild(cssLinkb);
		iFrameDoc.head.appendChild(cssLinkscroll);
		mappedElement = element

		getDimensionsDiv()

		window.addEventListener('scroll', trackScroll)
		window.addEventListener('resize', getDimensionsDiv)
	}



	
	function getInnerHeight(elm) {
		var computed = getComputedStyle(elm),
			padding = parseInt(computed.paddingTop) + parseInt(computed.paddingBottom);

		return elm.clientHeight - padding
	}
	
	function getDimensionsDiv() {
		var cantoplace = document.getElementById(displayId)
		var elementplace = document.getElementById(mappedElement)

		var bodyWidth = elementplace.clientWidth;
		var bodyRatio = elementplace.clientHeight / bodyWidth;
	 
		let winRatio = getInnerHeight(cantoplace) / (cantoplace.clientWidth);

		//minimap.style.width='15%';
		minimap.style.width = '100%';

		realScale = minimap.clientWidth / bodyWidth;

		minimapSize.style.paddingTop = `${bodyRatio * 100}%`
		viewer.style.paddingTop = `${winRatio * 100}%`;
		minimapContent.style.transform = `scale(${realScale})`;
		minimapContent.style.width = `${(100 / realScale)}%`;
		minimapContent.style.height = `${(100 / realScale)}%`; 
		//minimapContent.style.height=`100%`;
		minimapContent.style.float = 'right';
	}

	function trackScroll() {
		//console.log(window.scrollY)
		viewer.style.transform = `translateY(${window.scrollY * realScale}px)`
	}
	function trackScrollCanto() {
		console.log('cantoscrollT*realscale ' + document.getElementById(displayId).scrollTop * realScale + ' top: ' + document.getElementById(displayId).scrollTop)
		viewer.style.transform = `translateY(${document.getElementById(displayId).scrollTop * realScale}px)`
	}
	function trackScrollViewer(toppos) {
		console.log('scrollMMView top*1/realScale: ' + toppos * (1 / realScale) + ' top  pos: ' + toppos)
		did = document.getElementById(displayId)

		did.scrollTop = (toppos * (1 / realScale))
	}

	function hideMinimap() {
		$('.canto').each(function() {
			$(this).attr("style", 'display:none');
		});
		$(".minimap__container").remove();
		currentMinimap = ''
	}

	
	//Cantica management functions

	function showCantica(cantica) {
		//var listaCanti = new Set()
		var setVersi = new Set()
		//$("#loader").show();
		var containerForme = formeprima
		if (cantica == 'Paradiso')
			containerForme = formeterza
		if (cantica == 'Purgatorio')
			containerForme = formeseconda
		const endlc = performance.now();
		console.log(`Load `+cantica+` time: ${endlc - start} ms`);
		var elverso, formaItem
		for (var cmpItem of containerForme) {
		
			formaItem = cmpItem.split("_")
			
			//createDivVerso(cantica, num, canto, forma, catgram, pos)
			if (! setVersi.has(cantica + "_" + formaItem[3] + "_" + 'Canto_' + formaItem[1])){
				elverso=createDivVerso(cantica, formaItem[3], 'Canto_' + formaItem[1], formaItem[0], formaItem[4], formaItem[2], formaItem[5],formaItem[6])
				setVersi.add(cantica+ "_" + formaItem[3] + "_" + 'Canto_' + formaItem[1])
			}
			else{
				//setVersi = createDivVersi(setVersi, cantica, formaItem[3], 'Canto_' + formaItem[1])
				createSpanFormeNew(cantica, 'Canto_' + formaItem[1], formaItem[3], formaItem[0], formaItem[4], formaItem[2], formaItem[5],formaItem[6],elverso)
			}
			
			/*
			forma.numverso = formaItem[3];
			forma.canto = 'Canto ' + formaItem[1];
			forma.pos = formaItem[2];
			forma.form = formaItem[0];
			forma.catgramm = formaItem[4];
			forma.cantica = cantica;
			createSpanForme(forma)
			*/
		}
		//$("#loader").hide();
		return
	}
	
	
	function createSpanFormeNew(cantica, canto, numverso, forma, catgramm, pos, sentenceid, clausefunct, elementoverso) {
		var spanoccorrenza = $('<span />')
		//var pos = parseInt(pos)
		//spanoccorrenza.attr('id', cantica + "_" + canto+ "_" + numverso + "_" + pos)
		spanoccorrenza.attr('id', "_" + pos)
		spanoccorrenza.attr('data-cg', catgramm)
		spanoccorrenza.attr('class', sentenceid.replaceAll("-","_")+" "+clausefunct)
		//if (listarisultati.length > 0 && listarisultati.includes(spanoccorrenza.attr('id')))
		//	spanoccorrenza.attr('class', "font-weight-bold mark ")
		spanoccorrenza.append(forma+" ")
		//elementoverso = $('#' + cantica + "_" + canto + "_" + numverso)
		spanoccorrenza.appendTo(elementoverso)
		//elementoverso.append('&nbsp;')

	}
	/*
	function createDivVersi(setVersi, cantica, num, canto) {
		if (setVersi.has(cantica + "_" + num + "_" + canto))
			return setVersi
		else {
			var elementoverso = $('<p />')

			elementoverso.append(num + ". ")
			elementoverso.attr("style", "line-height: 0.5em")

			elementoverso.attr('class', 'f6 text-secondary text-nowrap font-weight-lighter')

			elementoverso.attr('id', cantica + "_" + canto + "_" + num)
			elementoverso.appendTo('#' + cantica + canto)
			setVersi.add(cantica + "_" + num + "_" + canto)
			return setVersi
		}

	}
	*/
	function createDivVerso(cantica, num, canto, forma, catgram, pos, sentenceid, clausefunct) {
		
			var elementoverso = $('<p />')

			elementoverso.append(num + ". ")
			elementoverso.attr("style", "line-height: 0.5em")

			elementoverso.attr('class', 'f6 text-secondary text-nowrap font-weight-lighter')

			elementoverso.attr('id', cantica + "_" + canto + "_" + num)
			
			var spanoccorrenza = $('<span />')
			//var pos = parseInt(pos)
			//spanoccorrenza.attr('id', cantica + "_" + canto+ "_" + num + "_" + pos)
			spanoccorrenza.attr('id', "_" + pos)
			spanoccorrenza.attr('data-cg', catgram)
			spanoccorrenza.attr('class', sentenceid.replaceAll("-","_")+" "+clausefunct)
		
			spanoccorrenza.append(forma+" ")
			spanoccorrenza.appendTo(elementoverso)
			
			elementoverso.appendTo('#' + cantica + canto)
			return elementoverso

	}

	
	function createAllDivCanti() {
		cantiche=["Inferno", "Purgatorio","Paradiso"]
		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.attr('style', 'display:none')
			divcanto.attr('id', (cantica + canto).replace(" ", "_"))
			titolocanto.appendTo(divcanto)
			divcanto.appendTo(' .blog-main')
			}
		}
	}


	//execute query
	
	async function executeQuerySearch(query) {
		$("#loader").show();
		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
				cantica = binding.get('Cantica').value;
				
				//canto
				canto = binding.get('Canto').value;
				
				//numero del verso
				numverso = binding.get('NumeroVerso').value;
				//posizione del frammento
				pos = binding.get('pos').value;
				//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/','')
				//console.log(sentenceid)
				/*
				if (!result.has(cantica + "_" + canto.replace(" ", "_") + "_" + numverso + "_" + pos)){
					result.add(cantica + "_" + canto.replace(" ", "_") + "_" + numverso + "_" + pos)
					resultsInCantica.push(cantica);
					resultsInCanto.push(cantica + canto)
				}*/
				if (!result.has("_" + pos)){
					result.add("_" + pos)
					resultsInCantica.push(cantica);
					resultsInCanto.push(cantica + canto)
				}
				
				resultClauses.add(cantica + "_" + canto.replace(" ", "_") + "_" + numverso + "-" +clfrom+'_'+clto+"-"+cltype)
				resultSentences.add(sentenceid)
				
				

			});
			seachbBindingsStream.on('end', () => {
				listarisultati = Array.from(result)
				//listaClausole= Array.from(resultClauses)
				cantiche = ["Inferno", "Purgatorio", "Paradiso"]

				//evidenzia periodi
				for (sentence of resultSentences){
					//$( " .text-info" ).removeAttr('class')
					
					sid='.' +sentence.toString()
					console.log(sid)
					$(sid).addClass('font-italic')
				}
				//evidenzia clausole
				for (clreg of resultClauses){
					//class="text-primary"
					comps=clreg.split('-')
					regbounds=comps[1].split("_")
					//console.log(comps[2])
					//console.log('one '+regbounds)
					
					for (var kr=parseInt(regbounds[0]); kr<=parseInt(regbounds[1]); kr++){
						//$("#"+"_"+kr.toString()).attr('class', "text-info font-weight-normal")
						$("#"+"_"+kr.toString()).addClass("text-info font-weight-normal")
						
					}
					
					
				}
				//evidenzia risultati
				for (ris of listarisultati) {
					idris = '#' + ris
					//$(idris).attr('class', "font-weight-bold mark ")
					$(idris).addClass("font-weight-bold mark ")

				}
				//aggiunge badge con totale risultati accanto alle cantiche
				i = 0
				for (cantica of cantiche) {
					i += 1
					let count = resultsInCantica.reduce((n, x) => n + (x === cantica), 0);
					if (count>0){
						var spanbadgecantica = $('<span />');
						spanbadgecantica.attr('class', 'badge badge-primary badge-pill ml-1');
						spanbadgecantica.append(count)
						spanbadgecantica.appendTo($('#cantica' + i))
					}
				}
				//aggiunge badge con totale risultati accanto ai canti

				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)
							//$("[name='nameofobject']")
							spanbadge.appendTo($('[name="' + cantica + 'Canto ' + k + '"]'))
							//spanbadge.insertAfter($('[name="'+cantica+'Canto '+k+'"]'))
						}
					}
				}


				//aggiorna minimap
				if (currentMinimap != '') {

					showMinimap(currentMinimap)

				}
				$("#loader").hide();

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

	};

/*
*	REGOLE DI PARSING PER VISUALIZZAZIONE PROPRIETÀ
*/

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"= " "*
		

`

//parser per categorie
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);


});