/* lingua (valore assegnato in advancedsearch.php, manageAccount.php, index.php, index2.php ) */
var lang = '';

/* funzione per aprire e chiudere i menu */
function EspandiMenu(row){
	var visibleElement = document.getElementById('v' + row);
	var hiddenElement  = document.getElementById('i' + row);
	
	if (hiddenElement.style.display == "none"){
		/* visualizza la lista di collezioni */
		hiddenElement.style.display = "block";
		visibleElement.style.display = "none";
	} else {
		if (visibleElement.style.display == "none") {
			/* visualizza la legenda */
			hiddenElement.style.display = "none";
			visibleElement.style.display = "block";
		}
	}
		
	
}

function findPosY(div) {
    var curtop = 0;
    var obj = document.getElementById(div);
 
   if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    } else if (obj.y)   curtop += obj.y;
    
    
  if (curtop < screen.height ) 
  	return screen.height;
  else 
  	return curtop;
}

/**
*/
function hide_docs(id){
  	var menu = document.getElementById(id);
  	if (menu.style.display == "block"){
	    menu.innerHTML='';
	    menu.style.display = "none";
  	}
  	return true;
}

/* controlli sulle form di ricerca */
function multiple_word (w, type){
	var alert1 = (lang=='IT' ? "Attenzione: i caratteri jolly non sono ammessi per questo tipo di ricerca" : "Warning: you can not use jolly character");
	if ( w != '' ) {
		myW = new String(w);
		results = myW.search( /\*/ );
		if ( results == -1 ) {
			return true;
		} else {
			if ( type == 'like' ) {
				alert (alert1);
				return false;
			} else 
				return true;
		}
	} else {
		return '';
	}	
}

/* verifica che ci sia una varibile a cui associare i risultati */ 
function tauro_findxmlvar(t, msg){
	if (t != '') {
		myQ = new String(t);
		rExp = /\$([a-z]+[0-9]*)*/gi;
		results = myQ.search(rExp);
		
		if ( results == -1 ) {
			// nessun pivot specificato
			return msg+'\n';
		} else {
			return '';
		}
	} else {
		return '';
	}
}

/**
 * controllo inserimento termini di ricerca
 */
function tauro_text(q, r, type){

	var alert1= (lang=='IT' ? "Attenzione: nessuna interrogazione definita" : "Warning: no query specified");
	if ( q == '' || r == '') {
		alert (alert1);
		return false;
	} else {
		jolly = multiple_word(q, type);
		if (!jolly) return false;
	}
	
	if ( type == 'adv' ) {
		var m = tauro_findxmlvar( q, 'Punto 2. Specificare almeno una variabile' ) +
		    tauro_findxmlvar( r, 'Punto 3. Le varibili della query devo essere presenti nel risultato' );
		if ( m != '' ) {
			alert (m);
			return false;
		}
	}
	return true;
}

/**
*/
function select_collection ( s ) {
	var alert1 = (lang=='IT' ? "Attenzione: selezionare almeno una collezione su cui effettuare la ricerca" : 
								"Warning: select one collection" );
	for (i=0; i < s.length; i++) {
		if ( s.elements[i].type == "checkbox" && s.elements[i].checked ) {
			break;
		}
	}
	if (i == s.length) {
		alert (alert1);
		return false;
	} else  {
		return true;
	}
}

function select_one_collection ( s ) {
	var alert2 = (lang=='IT' ? "Attenzione: selezionare esattamente una collezione su cui effettuare la ricerca" : 
								"Warning: select exactly one collection" );
	var c = 0;
	for (i=0; i < s.length; i++) {
		if ( s.elements[i].type == "checkbox" && s.elements[i].checked ) c++;
	}
	if ( c != 1 ) {
		alert (alert2);
		return false;
	} else { 
		return true;
	}
}


function search_regexp( err, re, st ) {
	var h1 = document.getElementById("ts");
	if ( re.checked ) {
		err.disabled = true;
		h1.innerHtml = 'Ricerca per espressioni regolari';
		st.value = 'reg';
		
	} else {
		err.disabled = false;
		h1.innerHtml = 'Ricerca semplice';
		st.value = 's';
	}
	return true;	
}

function search_diff( err, re, st ) {
	var h1 = document.getElementById("ts");
	if ( err.options[err.selectedIndex].value != 0 ){
		h1.innerHtml = 'Ricerca parole simili';
		st.value = 'like';
		re.disabled = true;
	}else { 
		h1.innerHtml = 'Ricerca semplice';
		st.value = 's';
		re.disabled = false;
	}
	return true;	
}



/* ********************************************** visualizzazione degli snippet **************************************** */
function tauro_setViewTagSnippet(newWin, block) {
	if (block){
			var divSnpts = document.getElementsByTagName('div');
			/* mostra/nasconde tag nel blocco */	
			for(var j=0; j < divSnpts.length; j++) { 
				if (divSnpts[j].className == 'snpt_1' ){
					if (divSnpts[j].style.display=='none')
						divSnpts[j].style.display = 'inline';
					else
						divSnpts[j].style.display = 'none';
				}
			}
	
	} else {
			
			/* mostra/nasconde tag negli snippet */
			
			var divSnpts = document.getElementsByTagName('div');
			var s = new Array();var k=0; var cname;
			
			if (navigator.appName == 'Netscape') {
				var id_snippet = document.getElementsByName("idsnpt");
				for(var j=0; j < id_snippet.length; j++) { s[k]=id_snippet[j].id; k++;}
			} else {
				for(var j=0; j < divSnpts.length; j++) {
					if ( divSnpts[j].name=="idsnpt" ){ s[k] = divSnpts[j].id; k++; }
				}
			}
			
			for( var i=0; i< divSnpts.length; i++ ) {
				for(var j=0; j < s.length; j++) { 
					cname = 'snpt_'+s[j];
					if (divSnpts[i].className == cname ){
						if (divSnpts[i].style.display=='none')
							divSnpts[i].style.display = 'inline';
						else
							divSnpts[i].style.display = 'none';
					}
				}						
						
			}
			
	}
	return true;
}


function tauro_checkAll() {
	var chkbox_snippet = document.getElementsByTagName('input');
	var e = document.getElementById('allbox'); 
	
	for ( var i=0; i<chkbox_snippet.length; i++) {
		if (chkbox_snippet[i].name != 'allbox' && chkbox_snippet[i].name != 'newWin')
				chkbox_snippet[i].checked = e.checked;
	}
}



/* ********************************************** controlli per la registrazione **************************************** */
var testpwd = true;

function checkPwd(value, cont){
	var alert1 = (lang=='IT' ? "La password deve essere composta almeno da 6 caratteri" : "Insert password: min. 6 characters" );
	if (value != '' && cont < 6){
		alert (alert1);
		document.f.user_pwd.value = '';
		document.f.user_pwd.focus();
		return false;
	}
	
	return true;
}

/**
*/
function comparePwd(v1, v2){
	var alert1 = (lang=='IT' ? "Le password digitate non corrispondono. Ridigitare entrambe le password" : "Password are different. Retype all password" );
	if (v2 != '' && v2 != v1){
		alert (alert1);
		document.f.user_pwd.value = '';
		document.f.user_repwd.value = '';
		document.f.user_pwd.focus();
		return false;
	}
	return true;
}

/**
*/
function CheckIscrizione(which){
  var alert1 = (lang=='IT' 	? "E-mail, login e password sono obbligatori" 
  							: "E-mail, login and password are mandatory" );
  if (document.images) {
    var pass=true
    for ( i=0; i<which.length; i++ ) {
      var tempobj = which.elements[i]
      if ( ( (tempobj.type=="text" || tempobj.type=="password" ) && tempobj.value=='' && 
     		( tempobj.name=="user_email" || 
     		  tempobj.name == "user_account" || 
     		  tempobj.name == "user_pwd" || 
     		  tempobj.name == "user_repwd" 
     		) ) ) 
     	{
		  alert(alert1);
		  pass = false;
		  break;
		} 
    }//end for
    if (!pass){
      return false;
    } else
      return true;
  }
}

/**
*/
function CheckDocument(which){
  var alert1 = (lang=='IT' 	? "I campi contrassegnati dall'asterisco sono obbligatori" 
  							: "I campi contrassegnati dall'asterisco sono obbligatori");
  if (document.images) {
    var pass=true
    for (i=0;i<which.length;i++){
      var tempobj = which.elements[i]
      if ( ( (tempobj.type=="text" && tempobj.name=="tit") || tempobj.type=="file") && tempobj.value==''){
		  alert(alert1);
		  pass = false;
		  break;
		} 
    }//end for
    if (!pass){
      return false;
    } else
      return true;
  }
}

/**
*/
function ShowChk( myid ) {
	if(!document.getElementById) return;
	chk       = document.createElement("input");
	lbl       = document.createElement("label");
	chk.id    = "pub";
	chk.setAttribute ("name","pub");
	chk.setAttribute ("type", "checkbox");
	chk.setAttribute ("value", "grp_pubblica");
	lbl.setAttribute ("for", chk.id);
	
	myid.appendChild(chk);
}


/* verifica che ci sia una varibile a cui associare i risultati */ 
function tauro_checkCollectionName(t){
	var alert1 = (lang== 'IT' ? "Il nome e' un campo obbligatorio" : "The name is a mandatory field");
	var alert2 = (lang== 'IT' ? "Caratteri non consentiti" : "Characters not allowed");
	if (t != '') {
		myQ = new String(t);
		rExp = new RegExp('[@\'"\\*\\?\\[\\]\|\\\\\\/;&]', "gi")
		results = myQ.search(rExp);
		if ( results == -1 ) {
			// non sono presenti caratteri errati
			return true;
		} else {
			alert ( alert2+': @ \' " \\ / * ? [ ] & ;' );
		}
	} else {
		alert (alert1);
	}
	return false;
}


function edit_news( el ){ 
	if ( el.id.substr( 0,2 ) == 'v_' ) {
		eli = document.getElementById('i_'+el.id.substr( 2 ) );
		if ( el.style.display == 'block' ) {
			el.style.display = 'none'; //el.innerHTML='';
			eli.style.display = 'block';
		} else {
			el.style.display = 'block';
			eli.style.display = 'none'; //eli.innerHTML='';
		}
	}		
}

function close_edit_news( id_div ){
	el = document.getElementById( id_div );

	if ( id_div.substr( 0,2 ) == 'i_' ) {
		elv = document.getElementById('v_' + id_div.substr( 2 ) );
		
		el.style.display = 'none';// el.innerHTML='';
		elv.style.display = 'block';
		
	}
	return false;	
}

/**************************************** Ricerca Avanzata ***************************************/

var icon_ccbgdiv = null;
var icon_ccdiv   = null;

var count_nodes  = 0;     /* conta i nodi presenti "veramente" nella query */
var index_query_tree = 0; /* lunghezza dell'array */

var lastfather   = 0;
var query_tree   = null;

/* indici per l'array relativo al nodo della query */
var TAGINDEX = 0;
var TAGPADRE = 1;
var FIGLI    = 2;
var TAGNAME  = 3;
var TAGTYPE  = 4;
var MAXDIST  = 5;
var REGEXP   =10;
var RETURN   = 6;
var ATTNAME  = 7;
var ATTVAL   = 8;
var SELINDX  = 9;

/* numero massimo di elementi restituibili */
var MAXPIVOT = 3;

var atts = new Array();

var qry;


/**
*/
function showMenu( selectedEl ) {
	
	/* mostra o nasconde il menu clikkato */
	el = document.getElementById( "tauro_menu_"+selectedEl );
	
	if ( el.style.display == "none" || el.style.display == "" ) 
		el.style.display = "block";
	else
		el.style.display = "none";
	
		
	/* chiude altri menu aperti */ 
	
	if (query_tree != null) {
		for (var i=0; i<query_tree.length; i++ ) {
			id = query_tree[i][TAGINDEX];
			var m = document.getElementById( "tauro_menu_"+id );
			if ( m != null ) {
				if ( id != selectedEl && m.style.display == "block" ){
					m.style.display = "none";
					break;
				}
			}
		}
	}
}

/**
*/
function popupQuery ( displaystyle ) {
	icon_ccdiv   = document.getElementById( "searchRuleChangerPopup" );
	icon_ccbgdiv = document.getElementById( "searchRuleChangerBackground" );	
	icon_ccdiv.style.display   = displaystyle;
	icon_ccbgdiv.style.display = displaystyle;
}



function scriviPathQuery( k ){
	var path = "/"+query_tree[ k ][TAGNAME];
	
	if ( k != query_tree[ k ][ TAGPADRE ] ) {
		path = scriviPathQuery( query_tree[ k ][ TAGPADRE ] )+path;
	}
	
	return path;
}

/**
mostra o nasconde la popup di inserimento nodo
*/						
function popupQueryNode ( displaystyle, id ) {
		
	/* titolo della popup */
	var txt_header = document.getElementById( "searchRuleChangerText1");
		
	/* mostra select */
	var select_tag = document.getElementById( "searchRuleChangerSelect_tag" );
	select_tag.selectedIndex = -1;
	select_tag.style.display = "inline";
	
	/* nasconde select per elenco attributi */
	var select_att = document.getElementById( "searchRuleChangerSelect_att" );
	select_att.style.display = "none";
	
	/* nasconde input text */
	var input_word = document.getElementById( "searchRuleChangerInputTxt" );
	input_word.style.display = "none";
	/* nasconde chebox reg-exp */
	var re  = document.getElementById( "searchRuleChangerInputChk" );
	re.style.display ="none";
	
	/* modifica caption pulsante */
	var div_butt_f = document.getElementById( "addSearchRule" );
	div_butt_f.style.display = "inline";

	if ( id == -1 ) { /* ha eliminato la root */
		
		txt_header.innerHTML = (lang=='IT' ? "Seleziona il tag radice della query." : "Select query root tag." )+
		"<br/><font size=\"-1\">"+
		(lang=='IT' ? "La query viene rappresentata con una struttura ad albero." : "The query is represented by a tree structure." )+
		"</font>";
		div_butt_f.setAttribute("value", (lang=='IT' ? "Aggiungi" : "Add") );
		div_butt_f.onclick = function () { icon_windowCloseDone('tauro_query_tag', 'root'); }
		select_tag.onkeypress= function (e) {if (navigator.appName == 'Netscape') { if (e.which)var x= e.which; } else { if ( window.event.keyCode) var x= window.event.keyCode;}  if (x==13) icon_windowCloseDone('tauro_query_tag', 'root'); }
		
	} else {

		txt_header.innerHTML = (lang=='IT' ? "Seleziona figlio o discendente di " : "Select son or descendant of ")+
		"<strong>"+scriviPathQuery(id)+"</strong>.";
		div_butt_f.setAttribute("value", (lang=='IT' ? "Figlio" : "Son"));
		div_butt_f.onclick = function () { icon_windowCloseDone('tauro_query_tag_'+lastfather, 'figlio'); }
		select_tag.onkeypress = function (e) {if (navigator.appName == 'Netscape') { if (e.which)var x= e.which; } else { if ( window.event.keyCode) var x= window.event.keyCode;}  if ( x == 13 ) icon_windowCloseDone('tauro_query_tag_'+lastfather, 'figlio');}
	}
		
	/* mostra pulsante discendente */
	var div_butt_d = document.getElementById( "addSearchRuleDisc" );
	if ( id == -1 ) {
		div_butt_d.style.display = "none";
	} else {
		div_butt_d.style.display = "inline";
		div_butt_d.onclick = function () { icon_windowCloseDone('tauro_query_tag_'+lastfather, 'disc'); }
		select_tag.onkeypress= function (e) {if (navigator.appName == 'Netscape') { if (e.which)var x= e.which; } else { if ( window.event.keyCode) var x= window.event.keyCode;}  if (x==13) icon_windowCloseDone('tauro_query_tag_'+lastfather, 'disc');}
	}
	popupQuery ( displaystyle );
}

/**

mostra o nasconde la popup di inserimento parole

*/
function popupQueryWords ( displaystyle ) {
	
	/* titolo della popup */
	var txt_header = document.getElementById( "searchRuleChangerText1");
	txt_header.innerHTML = (lang=='IT' ? "Parole contenute in ": "Words contained in")+
		scriviPathQuery(lastfather)+".<br/><font size=\"-1\">"+
		(lang=='IT' ? "Puoi inserire pi&#249; parole e utilizzare il carattere <strong>*</strong>." : "You can insert more words and use character <strong>*</strong>.")+
		"</font>";
	
	/* mostra input text */
	var input_word  = document.getElementById( "searchRuleChangerInputTxt" );
	input_word.value = '';
	input_word.style.display = "block";
	/* mostra chebox reg-exp */
	var re  = document.getElementById( "searchRuleChangerInputChk" );
	re.style.display ="block";
	input_word.onkeypress = function(e) {
		if (navigator.appName == 'Netscape') { 
			if (e.which) {
			  var x= e.which; 
			}
		} else { 
			if ( window.event.keyCode) {
			  var x= window.event.keyCode;
			}
		}  
		if (x==13) {
			icon_windowCloseDone('tauro_query_tag_'+lastfather, 'word')
		}
	};
	
	/* nasconde select tag */
	var select_tag  = document.getElementById( "searchRuleChangerSelect_tag" );
	select_tag.style.display = "none";
	
	/* nasconde select per elenco attributi */
	var select_att = document.getElementById( "searchRuleChangerSelect_att" );
	select_att.style.display = "none";
		
	/* modifica caption pulsante */
	var div_butt_f  = document.getElementById( "addSearchRule" );
	div_butt_f.setAttribute("value", (lang=='IT' ? "Aggiungi" : "Add") );
	div_butt_f.onclick = function () { icon_windowCloseDone('tauro_query_tag_'+lastfather, 'word'); }
	
	/* nasconde pulsante discendente */
	var div_butt_d = document.getElementById( "addSearchRuleDisc" );
	div_butt_d.style.display = "none";
	
	/* mostra la popup */
	popupQuery ( displaystyle );
}

/* assume che quando si chiama esista almeno un attributo per quel tag */
function popupAttributes ( displaystyle, id, a5 ) {
	var a;
	
	/* titolo della popup */
	var txt_header = document.getElementById( "searchRuleChangerText1");
	txt_header.innerHTML = (lang=='IT' ? "Seleziona un attributo e inserisci il valore" : "Select an attribute and insert value");
	
	var select_tag  = document.getElementById( "searchRuleChangerSelect_tag" );
	/* l'indice del tag serve per visualizzare solo gli attributi utili */
	
	if ( select_tag.selectedIndex != -1 ) 
		a = atts[ select_tag.selectedIndex ];
	else 
		a = atts[ query_tree[id][SELINDX] ];
	
	/* nasconde select dei tag */
	select_tag.style.display = "none";
	
	/* mostra input text */
	var input_word  = document.getElementById( "searchRuleChangerInputTxt" ); 
	input_word.value = '';
	input_word.style.display = "block";
	input_word.onkeypress = function(e) {if (navigator.appName == 'Netscape') { if (e.which)var x= e.which; } else { if ( window.event.keyCode) var x= window.event.keyCode;}  if (x==13) icon_windowCloseDone(id, 'att') };
	/* nasconde chebox reg-exp */
	var re  = document.getElementById( "searchRuleChangerInputChk" );
	re.style.display ="none";
	
	/* mostra select per elenco attributi */
	var select_att = document.getElementById( "searchRuleChangerSelect_att" );
	/* svuota la select */
	for (i=0; i< select_att.length; i++) { select_att.options[i] = null; }
	/* inserisce nuovi attributi */
	for (i=0; i< a.length; i++){  select_att.options[i] = new Option( a[i],a[i] );} 
	select_att.style.display = "block";
	
	/* modifica caption pulsante */
	var div_butt_f  = document.getElementById( "addSearchRule" );
	div_butt_f.setAttribute("value", (lang=='IT' ? "Aggiungi" : "Add") );
	div_butt_f.onclick = function () { 
								icon_windowCloseDone( id, 'att' ); 
								a5.innerHTML= (lang == 'IT' ? "Elimina attributo" : "Delete attribute" ); 
								a5.onclick = function () { _handler_delete_att( a5,id, query_tree[id][TAGNAME] );	};
						}
	
	/* nasconde pulsante discendente */
	var div_butt_d = document.getElementById( "addSearchRuleDisc" );
	div_butt_d.style.display = "none";
	
	/* mostra la popup */
	popupQuery ( displaystyle );
}




/**

aggiunge un nodo/parola alla query
*/
function createTocElement( id, tagName, type_node, ret, attname, attval ) {
	var txt;
	var li   = document.createElement("li");
	var div  = document.createElement("div");
	
	li.id = "li_"+id;
	li.className = "li_"+type_node;

	if (type_node != 'word') {
		if ( attname != '' && attval != '') {
			txt  = document.createTextNode("<"+tagName+" "+attname+"='"+attval+"' >");
		} else {
			txt  = document.createTextNode("<"+tagName+">");
		}
	} else
		txt  = document.createTextNode(tagName);
	
	var menu = createTocMenu( id, tagName, type_node, ret );
	
	var img  = document.createElement("img");
	img.className = "tauro_img";
	img.setAttribute("src", "./resources/freccia.gif");
	
	div.className = "tag";
	div.id = "tag_"+id;
	div.appendChild( txt );
	div.appendChild( img );
	if ( ret != null && ret != 0 ) { div.style.background = "#E1EFFB"; }
	div.onclick = function () { showMenu( id ) };
	
	li.appendChild(div);
	li.appendChild(menu);
	
	return li;
}

/**
aggiunge una voce al menu
*/
function createTocMenuElement( txt, attr_href, classn  ) {
	
	var t = document.createTextNode(txt);
	var div = document.createElement("div"); 
	if ( classn ) div.className = classn;
	div.appendChild(t);
	
	return div;

}

/**
*/
function removeSubtree ( n ) {
	
	var f = query_tree[ n ][ FIGLI ];
		
	/* ricorsione sui figli */
	var num_figli = f.length;
	for( var i = 0; i < num_figli; i++ ) {
			removeSubtree( f[ i ] );
	}
	/* cancella logicamente */
	query_tree[n] = '';
	/* diminuisce il numero di nodi nella query */
	count_nodes--;
}

/**var query 
*/
function createQuery( el ){
	
	var query = ''; var pivot = ''; var dist=''; var att ='';
	
	/* questo elemento fa parte del risultato */
	var pivot = ( el[ RETURN ] != 0  ? "xml_var='$"+el[ TAGINDEX ]+"'" : "");
	/* specifica la distanza */
	var dist  = ( el[ MAXDIST ] != 0 && el[ MAXDIST ] != -1 ? "xml_maxdist='"+el[ MAXDIST ]+"'"  : "");
	/* attributi */
	var att   = ( el[ATTNAME]!='' && el[ATTVAL]!='' ? el[ATTNAME]+"='"+el[ATTVAL]+"'" : "");
	
	if ( el[ TAGTYPE ] == 'word' ) 
		/* parte di query relativa alle parole */
		query += queryWord( el, pivot ); 
	else {
		if ( el[ FIGLI ].length == 0 ) {
			/* tag puntuale */
			query += "<"+el[ TAGNAME ]+" "+att+" "+pivot+" "+dist+"/>";
		} else {
			var q = "<"+el[ TAGNAME ]+" "+ att+" "+pivot+" "+dist+"> ";
			
			for( var i = 0; i < el[ FIGLI ].length; i++ )
				q += createQuery( query_tree[ el[ FIGLI ][ i ] ] );
				
			query += q+" </"+el[ TAGNAME ]+">";
		}
	}
	
	return(query);
}


/**
*/
function parentela (q, n, p) {
	nodo = n; padre = p;
	while ( nodo != padre ) {
		if ( q[padre][ RETURN ] ) return "*"+q[padre][TAGNAME]+" ";
		
		nodo = padre;
		padre = q[padre][TAGPADRE];
	}
	
	if ( q[nodo][ RETURN ] ) return "*"+q[nodo][TAGNAME]+" ";
		
	return "* ";
			
}

/**
*/
function createResult( q ) {
	var r=''; 
	for ( var i=0; i<q.length; i++ ) {
		if ( q[i][RETURN] ) { 
			if ( q[i][TAGTYPE] == 'word' )
				r += "$"+q[i][TAGINDEX]+" "+q[i][TAGNAME]+" "+1+" "+parentela ( q, q[i][TAGINDEX], q[i][TAGPADRE] );
			else
				r += "$"+q[i][TAGINDEX]+" "+q[i][TAGNAME]+" "+0+" "+parentela ( q, q[i][TAGINDEX], q[i][TAGPADRE] );
		}
	}
	
	return r;
}



function serializeQuery_tree ( q ) {
	var str_query_tree='';
	
	for (var i=0; i< q.length; i++) {
		// ogni elemento e' un array
		for (var j=0; j< q[i].length; j++) {
				
			// questo elemento e' un array
			if ( j == FIGLI ) 
				str_query_tree += q[i][j].join(" + ") +" # "; // separatore di lista figli
			else {
				if (j ==  q[i].length-1 ) 
				str_query_tree += q[i][j];
			else
				str_query_tree += q[i][j]+" # "; // separatore di elemento
			}
		} 
		
		if (i <  q.length-1 ) str_query_tree += " | " //separatore di nodo
			 
	}

	return str_query_tree;
}


/* s e' la rappresentazione della query */
function unserializeQuery_tree( s ) {
	var query_node;
	var j=0;
	/* dalla stringa crea array di nodi */
	var qt = s.split(" | ");
	
	query_tree = new Array(); 
	
	/* query_tree e' un array di array */
	for(var i = 0; i < qt.length; i++) {
		
		if ( qt[i].length > 0 ) {
			
			query_node = qt[i].split(" # ");
			query_node[FIGLI] = query_node[FIGLI].split(" + ");
			
			/* controllo necessario perche' lo split genera un array lungo 1 se non ci sono elementi */
			if (query_node[FIGLI].length == 1 && query_node[FIGLI][0]=='') query_node[FIGLI] = new Array();
			
			query_tree[j]=query_node;
			j++;
			/* sono i nodi effettivi */
			count_nodes++;
			
		} else {
			/* qt[i].length == 0  se la query aveva subito una cancellazione di un nodo precedentemente */
			query_tree[j] = new Array();
			j++;
		}
	}
	/* lunghezza dell'array */
	index_query_tree = query_tree.length;
	
	var ul = document.getElementById("tauro_query_tag");
	var li = rewriteQueryTree( 0 ); 
	ul.appendChild( li );
}

function rewriteQueryTree( i ) {
	lastfather = i;
	
	var ul = document.createElement("ul");
	ul.className = "tauro_query_tag";
	ul.id = "tauro_query_tag_"+i;
	
	var li = createTocElement( i, query_tree[i][TAGNAME], query_tree[i][TAGTYPE], query_tree[i][RETURN], query_tree[i][ATTNAME], query_tree[i][ATTVAL] );
	
	li.appendChild(ul);
	if ( query_tree[i][ FIGLI ].length == 0 ) {
			/* tag puntuale o parola*/			
			i++;
	} else {
			
			if ( i < query_tree.length ) {
				
				var l = query_tree[i][ FIGLI ].length;
				
				for( var j = 0; j < l; j++ ){
					ul.appendChild( rewriteQueryTree( query_tree[i][ FIGLI ][j] ) );
				}				
			}
	}
		
	return( li );
}


function _handler_delete_att( a5, id, tagName ){
	var tmpTagName = query_tree[id][TAGNAME];
	showMenu( id );
											
	var tag = document.getElementById( "tag_"+id );
	var s = new String( tag.innerHTML );
	
	myRegExp = new RegExp(query_tree[id][ATTNAME]+"='"+query_tree[id][ATTVAL]+"'", "gi");
	tag.innerHTML = s.replace(myRegExp, "")
	a5.innerHTML= (lang == 'IT' ? "Aggiungi attributo a &lt;"+tmpTagName+"&gt;" : "Add attribute &lt;"+tmpTagName+"&gt;");
	a5.onclick = function () {  _handler_add_att(a5,id, tagName ); };
	
	query_tree[id][ATTNAME]= '';
	query_tree[id][ATTVAL] = '';
}


function _handler_add_att( a5,id, tagName ){
	showMenu( id );
	popupAttributes( "block", id, a5 );
	/*a5.innerHTML= (lang == 'IT' ? "Elimina attributo" : "Delete attribute" ); 
	a5.onclick = function () { _handler_delete_att( a5,id, query_tree[id][TAGNAME] );	};*/
}

/**
*/
function createTocMenu( id, tagName, type_node, ret ) {	
	
	var div = document.createElement("div");
	div.className = "tauro_menu";
	div.id = "tauro_menu_"+id;
	var tit3 = (lang=='IT' ? "Elimina" : "Delete");
	var tit4 = (lang=='IT' ? "Restituisci" : "Return");
	var tit5 = (lang=='IT' ? "Non restituire" : "Do not return");
	
	var alert1 = (lang=='IT' ? "E' possibile inserire al massimo 5 nodi" : "Insert at most 5 nodes");
	if (type_node != 'word') {
		var tit1 = (lang=='IT' ? 
			"Aggiungi figlio/discendente di <"+tagName+">" 
			: "Add son or descendant of <"+tagName+">");
		/* -------------- aggiungi tag -------------- */
		var a1 = createTocMenuElement( tit1, "#", "menu_item" );
		a1.onclick = function () {

			if ( count_nodes < 5 ) {
				lastfather = id;
				showMenu( id ); 
				popupQueryNode("block", id);
			} else {
				alert(alert1);
			}
		
		};
		
		/*  -------------- aggiugi parola  -------------- */
		var tit2 = (lang=='IT' ? 
				"Aggiungi parole da ricercare in <"+tagName+">" 
				: "Add search words in <"+tagName+">");
		var a2 = createTocMenuElement( tit2, "#", "menu_item" );
		a2.onclick = function () { 

			if ( count_nodes < 5 ) {
				lastfather = id; 
				showMenu( id ); 
				popupQueryWords("block");
			} else {
				alert(alert1);
			}
		};
				
		/*  -------------- restringi su attributo  -------------- */
		var tit6;var a5;
		var select_tag  = document.getElementById( "searchRuleChangerSelect_tag" );
		
		if ( ( atts[ select_tag.selectedIndex ] ||  query_tree[id][SELINDX] ) &&
			 query_tree[id][ATTNAME]=='' ) 
		{
			/* aggiungi nuovo attributo */
			tit6 = (lang == 'IT' ? 
				"Aggiungi attributo a <"+tagName+">" 
				: "Add attribute <"+tagName+">");
			a5 = createTocMenuElement( tit6, "#", "menu_item_line_above" );
			a5.onclick = function () { _handler_add_att(a5,id, tagName ); };
				
		} else if ( query_tree[id][ATTNAME] ) {
			
			/* Elimina attributo */
			tit6 = (lang == 'IT' ? "Elimina attributo" : "Delete attribute" );
			a5 = createTocMenuElement( tit6, "#", "menu_item_line_above" );
			a5.onclick = function () { _handler_delete_att(a5,id, tagName ); };
			
		} else {
			/* attributi non presenti, comando disabilitato */
			tit6 = (lang == 'IT' ? "Attributi non presenti" : "No attributes");
			a5 = createTocMenuElement( tit6, "#", "menu_item_line_above" );
			a5.style.background = "#E5E5E5";
		}
				
		
		div.appendChild( a1 );
		div.appendChild( a2 );
		div.appendChild( a5 );
		
		/*  -------------- elimina sottalbero  -------------- */
		var a3 = createTocMenuElement( tit3+" <"+tagName+">", "#", "menu_item_line_above");
		
		/*  -------------- risultato  -------------- */
		var a4 = createTocMenuElement( (ret != null && ret != 0 ? tit5 : tit4)+" <"+tagName+">", 
						"#", 
						"menu_item_line_above" );
		
	} else {

		/*  -------------- elimina sottalbero -------------- */
		var a3 = createTocMenuElement( tit3+" "+tagName, "#", "menu_item_line_above");
		/* -------------- risultato  -------------- */		
		var a4 = createTocMenuElement( tit4+" "+tagName, "#", "menu_item_line_above" );
		
	}

	
	a3.onclick = function () { 
		if ( id == 0 ) {
			/* root */
			var subtree = document.getElementById( "tauro_query_tag" );	 
		} else {
			/* nodo interno */ 
			var p = query_tree[ id ][ TAGPADRE ];
			var subtree = document.getElementById( "tauro_query_tag_"+p ); 
		}
		
		/* rimuove il sottoalbero dalla pagina */
		n = document.getElementById( "li_"+id ); 
		subtree.removeChild( n );
		
		/* rimuove il sottoalbero dall'array */
		p = query_tree[ id ][ TAGPADRE ]; lf_p = query_tree[p][ FIGLI ]; 
		removeSubtree( id );
		/* elimina il puntatore al figlio cancellato*/
		for(var i=0; i < lf_p.length; i++ ) { 
			if ( lf_p[i] == id ) {
				lf_p.splice(i, 1);
				break;
			}
		}
		if ( id == 0 ) {
			/* solo root: modifica submit */
			var b = document.getElementById( "submitTRQuery" );
			b.style.display = "none";
			
			popupQueryNode("block", -1);
		}
	};


	/* aggiungi al risultato */
	a4.onclick = function () { 
		var n = document.getElementById( "tag_"+id );
		if (query_tree[ id ][ RETURN ] == 0 ){

			n.style.background = "#E1EFFB";
			query_tree[ id ][ RETURN ] = 1;
			if (type_node != 'word') {
				a4.innerHTML = tit5+" &lt;"+query_tree[ id ][ TAGNAME ]+"&gt;";
			} else {
				a4.innerHTML = tit5+query_tree[ id ][ TAGNAME ];
			}

		} else {

			n.style.background = "#ffffff";
			query_tree[ id ][ RETURN ] = 0;
			if (type_node != 'word') {
				a4.innerHTML = tit4+" &lt;"+query_tree[ id ][ TAGNAME ]+"&gt;";
			} else {
				a4.innerHTML = tit4+" "+query_tree[ id ][ TAGNAME ];
			}

		}
		showMenu( id );
	
	};
	
	div.appendChild( a3 );
	div.appendChild( a4 );	
	
	return div;
}


/**/
function subQueryWord( arrwords, pivot ){
	var searchText = ''; var word;
	
	for ( var i = 0; i< arrwords.length; i++ ) {
		word = arrwords[i];
		
		var len = word.length;
		var first = word.search( /\*/ );
		
		var last = -1;
		for (var j=len; j>0 && word[j]!= "*"; j--);
		if (word[j] == "*")	last = j;
		
		if ( first == -1 ) {
			/* ricerca esatta */
			searchText += "<xml_exact "+pivot+">"+word+"</xml_exact>";
		} else {
			
			if ( first == last ) {
				/* ricerca per regexp, suffix, prefix */
				if (first != 0 && first != len-1 ) {
					searchText += "<xml_regexp "+pivot+">^"+word.replace(/\*/ , ".*")+"$</xml_regexp>";
				} else if ( first == 0 ) {
					searchText += "<xml_suffix "+pivot+">"+ word.substr(1, len)+"</xml_suffix>";
				} else if (	first == len-1 ) {
					searchText += "<xml_prefix "+pivot+">"+word.substr(0,first)+"</xml_prefix>";
				}
			} else {
				/* ricerca per contenuto */
				searchText += "<xml_contained "+pivot+">"+word.substr(first+1, last-1)+"</xml_contained>";
			}
		}
	}
	
	return searchText;
}


/**
*/
function queryWord( el, pivot ) {
	
	var myString = new String( el[TAGNAME] );
	
	if ( el[REGEXP] == 0 ) {
		/* divide la stringa in parole */
		rE = /[^\w\*]+/;
		splitString = myString.split( " " );
	
		var l = splitString.length;
	
		if ( l > 1 ){
			var maxprox = l-1;
	    	return "<xml_proximity "+pivot+" xml_maxprox='"+maxprox+"'>"+subQueryWord(splitString, '')+"</xml_proximity>";
		} else {
			 return subQueryWord(splitString, pivot);
		}
	} else {
		return "<xml_regexp "+pivot+">"+el[TAGNAME]+"</xml_regexp>";
	}
}

/**
*/
function startSearch () {
	var countPivot=0;
	var alert1 = (lang == "IT" ? "Restituzione vuota: almeno un nodo deve essere restituito" : "Empty return: select at least one node");
	var alert2 = (lang == "IT" ? "Troppi nodi selezionati: al massimo includere 3 nodi nel risultato" : "Too much selected nodes: 3 nodes max");
	
	/* controlla che esista almeno un pivot nel risultato e non siano + di 3 */
	for (var i=0; i<query_tree.length; i++ ){
		if ( query_tree[i] != '' && query_tree[i][RETURN] == 1 ) 
			countPivot++;
		
	}
	if ( countPivot == 0 ) {
		alert (alert1);
		return false;
	} else if (countPivot > MAXPIVOT )	{
		alert (alert2);
		return false;
	} else {
		/* array con info per costruzione risultato */
		document.forms['TRQLform'].r.value = createResult( query_tree );
		/* query in TRIL */ 
		document.forms['TRQLform'].q.value = createQuery( query_tree[0] ); 
		/* html relativo alla query */
		var qry  = document.getElementById( "tauro_query_tag" );
		document.forms['TRQLform'].tree.value = encodeURIComponent(qry.innerHTML);
		/* rappresentazione dell'albero della query */ 
		document.forms['TRQLform'].qt.value   = serializeQuery_tree ( query_tree );

		document.forms['TRQLform'].submit();
		return true;
	}
}

/* qt=rappresentazione dell'albero della q */
function reloadQuery( qt, l, action, step ) {
	
	var f = document.createElement("form");

	var tree = document.createElement("input");
	tree.setAttribute("type", "hidden");
	tree.setAttribute("name", "qt");
	tree.setAttribute("value", qt);
	f.appendChild(tree);
	
	var st = document.createElement("input");
	st.setAttribute("type", "hidden");
	st.setAttribute("name", "st");
	st.setAttribute("value", "adv");
	f.appendChild(st);
	
	if ( l != '' ) {
		var i8 = document.createElement("input");
		i8.setAttribute("type", "hidden");
		i8.setAttribute("name", "lang");
		i8.setAttribute("value", l );
		f.appendChild(i8);
	}
	if ( step != '' ) {
		var he = document.createElement("input");
		he.setAttribute("type", "hidden");
		he.setAttribute("name", "step");
		he.setAttribute("value", step );
		f.appendChild(he);
	}
	f.action = action;
	f.method = "POST";
	document.body.appendChild(f);
	
	f.submit();
	
	return true;
}

function changeLanguage( st, meta, tree, qt, r, c_id, q, action, meth, l ) {
	var f = document.createElement("form");

	var i1 = document.createElement("input");
	i1.setAttribute("type", "hidden");
	i1.setAttribute("name", "st");
	i1.setAttribute("value", st);
	f.appendChild(i1);
	
	var i2 = document.createElement("input");
	i2.setAttribute("type", "hidden");
	i2.setAttribute("name", "meta");
	i2.setAttribute("value", meta);
	f.appendChild(i2);
	
	var i3 = document.createElement("input");
	i3.setAttribute("type", "hidden");
	i3.setAttribute("name", "tree");
	i3.setAttribute("value", tree);
	f.appendChild(i3);
	
	var i4 = document.createElement("input");
	i4.setAttribute("type", "hidden");
	i4.setAttribute("name", "qt");
	i4.setAttribute("value", qt);
	f.appendChild(i4);
	
	var i5 = document.createElement("input");
	i5.setAttribute("type", "hidden");
	i5.setAttribute("name", "r");
	i5.setAttribute("value", r);
	f.appendChild(i5);
	
	var i6 = document.createElement("input");
	i6.setAttribute("type", "hidden");
	i6.setAttribute("name", c_id);
	i6.setAttribute("value", c_id);
	f.appendChild(i6); 
	
	var i7 = document.createElement("input");
	i7.setAttribute("type", "hidden");
	i7.setAttribute("name", "q");
	i7.setAttribute("value", decodeURIComponent(q) );
	f.appendChild(i7); 

	var i8 = document.createElement("input");
	i8.setAttribute("type", "hidden");
	i8.setAttribute("name", "lang");
	i8.setAttribute("value", l );
	f.appendChild(i8);
	
	f.action = action;
	f.method = meth;
	document.body.appendChild(f);
	f.submit();
	
	return true;
}

function changeLanguageSC( kw, whr, action, meth, l ) {
	var f = document.createElement("form");

	var i1 = document.createElement("input");
	i1.setAttribute("type", "hidden");
	i1.setAttribute("name", "kw");
	i1.setAttribute("value", kw);
	f.appendChild(i1);
	
	var i2 = document.createElement("input");
	i2.setAttribute("type", "hidden");
	i2.setAttribute("name", "whr");
	i2.setAttribute("value", whr);
	f.appendChild(i2);
	
	var i8 = document.createElement("input");
	i8.setAttribute("type", "hidden");
	i8.setAttribute("name", "lang");
	i8.setAttribute("value", l );
	f.appendChild(i8);
	
	f.action = action;
	f.method = meth;
	document.body.appendChild(f);
	f.submit();
	
	return true;
}


/**
*/
function icon_windowCloseDone( id, type_node ){
	
	var max_dist = 0;
	var wregexp  = 0;
	var ul; 
	var li; 
	var query_node; 
	var q;
	var n;
	var input_word;
	var sti;
	var alert1 = (lang=="IT" ? "Inserire un testo su cui ricercare" : "Insert search string");
	var alert2 = (lang=="IT" ? "Selezionare un tag per la query" : "Select query tag");
	
	popupQuery( "none" );
	
	if ( type_node == 'word' ) {
			
		/* WORD: legge il testo inserito */
		input_word  = document.getElementById( "searchRuleChangerInputTxt" );
		n = input_word.value; sti= 0;
		if ( input_word.value == '' ) { 
			alert(alert1); 
			return; 
		}
		/* verifica se e' un'espressione regolare */
		if ( document.getElementById( "re" ).checked ) { 
			wregexp = 1; 
		}
		max_dist = -1;
	
	} else if ( type_node == 'att') {
		
		/* ATT: legge coppia [nome, val] */
		var select_att = document.getElementById( "searchRuleChangerSelect_att" );
		var tag        = document.getElementById( "tag_"+id );
		input_word     = document.getElementById( "searchRuleChangerInputTxt" );
		
		if (input_word.value == '') { 
			alert(alert1); 
			return; 
		}

		query_tree[id][ATTNAME] = atts[query_tree[id][SELINDX]][select_att.selectedIndex];
		query_tree[id][ATTVAL]  = input_word.value;
		tag.innerHTML += query_tree[id][ATTNAME]+"='"+query_tree[id][ATTVAL]+"'" ; 
		
		/* TODO. modifica voce di menu da aggiungi a elimina */
						
		return;
	} else {
					
		/* TAG: legge il tag selezionato */		
		var select_tag = document.getElementById( "searchRuleChangerSelect_tag" );
		if ( select_tag.selectedIndex == -1 ) {
			alert (alert2);
			location.replace('advancedSearch.php?st=adv');
			return;
		}
		
		if ( type_node == 'root' ) {
			query_tree  = new Array();
			count_nodes = 0; index_query_tree = 0; lastfather  = 0;
		} else {
			max_dist = ( (type_node == 'figlio') ? 1 : -1 );
		}
		
		n = select_tag.options[ select_tag.selectedIndex ].value;
		sti = select_tag.selectedIndex;
	}

	query_node = Array( 	index_query_tree, //indice tag
				lastfather,       //indice padre di tag nella query
				Array(),          //array di figli di tag nella query
				n,                //nome tag
				type_node,        //tipo
				max_dist,         //dist
				0,                //res
				'',               //nome att
				'',               //val att
				sti,              //tag_selected_index
				wregexp           //reg exp
			);

	query_tree.push(query_node);

	/* il padre punta al figlio */
	if ( type_node != 'root' ) { 
		var l = query_tree[ lastfather ][ FIGLI ].length;
		query_tree[ lastfather ][ FIGLI ][ l ] = index_query_tree ;
	}
	
	var ul = document.createElement("ul");
 	ul.className = "tauro_query_tag";
 	ul.id = "tauro_query_tag_"+index_query_tree;
	
 	/* crea elemento */
 	li = createTocElement( index_query_tree, n, type_node, 0, '', '' );
 	li.appendChild(ul);
 	
	/*estrae il div con id = tauro_query*/
	q = document.getElementById( id );
	q.appendChild(li);
	
	count_nodes++;
	index_query_tree++; 
	var b = document.getElementById( "submitTRQuery" );
	b.style.display = "block";
}
