// Glossario javascript file
// version 1.0.0 26/10/2007 Andrea Rincon Ray

var glossario_field = null;
var glossario_form = null;
var glossario_url = null;

var glossario_delay = 800; //Ritardo in ms sulla ricerca

var glossario_max_results = 5;

var glossario_request_count = 1; // Token ricerca
var glossario_text = "";

var glossario_visible = false;

var glossario_default = "";

var glossario_requests = new Array();

var glossario_last_reply = 0;

var glossario_locale = "en_IT";


function initGlossario( idCampo, wsURL, locale ) {
	//alert('1. initGlossario sono entrato con idCampo='+idCampo+', wsURL='+wsURL+', e locale='+locale+'');
	idForm = idCampo;
	//alert('2. idForm diventa uguale a idCampo quindi idForm='+idForm);
	glossario_field = document.getElementById( idCampo );
	if ( glossario_field==null ) return;
	//alert('BREACK. qui si bloccava la funzione vediamo se è per colpa del campo '+document.getElementById( idCampo )+'');
	//alert('3. cerco il campo del glossario --> ' + document.getElementById( idCampo ));
	glossario_form = document.getElementById( idForm );
	if ( glossario_form==null ) return;
	//alert('4. cerco oggetto campo della form --> ' + glossario_form);
	
	glossario_url = wsURL;
	if ( glossario_url=="" ) return;
	//alert('5. ricevo la url alla quale mi collegherò --> ' + glossario_url);
	
	glossario_locale = locale;
	if ( glossario_locale==null ) return;
	//alert('6. ricevo la locale --> ' + glossario_locale);
	
	glossario_default = glossario_field.value;
	//alert('7. ricevo la locale --> ' + glossario_locale);
	glossario_field.onkeyup = glossarioFieldCallback;
	
	glossario_field.onblur= function() {
		window.setTimeout( 'hideGlossario();',	1000);
	}
	glossario_field.onclick = function() { if (glossario_field.value==glossario_default) glossario_field.value=""; }
	
}

addLoadEvent(injectGlossarioLayer);



function glossarioResultReset() {
	//alert('8. azzero tutto dentro il div di ricerca');
	var container = document.getElementById("glossario_results");
	var figli = container.childNodes;
	
	while ( figli.length>0 ) {
		container.removeChild( figli[0] );
		figli = container.childNodes;
	}
}




function injectGlossarioLayer() {
	
	var htmlOverlayer = "";
	
	glossario_outer_div1 = document.createElement('div');
	glossario_outer_div1.setAttribute('id', 'glossario_outer_div'); 
	//htmlOverlayer += "<div id='glossario_outer_div' style='display:none;'>";
		
		htmlOverlayer += "<div id='glossario_results'>";
			htmlOverlayer += "<div id='glossario_wait'>";
				htmlOverlayer += "Searching";
			htmlOverlayer += "</div>";
		htmlOverlayer += "</div>";
		
	//htmlOverlayer += "</div>";
	
	glossario_outer_div1.innerHTML = htmlOverlayer;
	document.body.appendChild(glossario_outer_div1);
	divOverlayer = document.getElementById("glossario_outer_div");
	//document.body.insertAdjacentHTML( "beforeEnd", htmlOverlayer );
	
	divOverlayer.style.display = "none";
	glossario_visible = false;
	
	glossarioResultReset();
	
}

function showGlossario( testo ) {
	//alert('9. sono nella showGlossario con come parametro il value del campo di ricerca --> '+testo);
	new_glossario_text = trim( testo );
	//alert('10. elimino dal testo eventuali caratteri speciali e spazi vuoti'+new_glossario_text);
	if ( new_glossario_text.length==0 ) {
		//alert('11. new_glossario_text(la value trimmata) è vuota');
		hideGlossario() ;
		return;
	}
	
	if ( new_glossario_text == glossario_text ) return;
	glossario_text = new_glossario_text;
	
	
	glossario_request_count++;
	//alert('19. incremento glossario_request_count che ora assume il valore di '+glossario_request_count+'');
	var query = new_glossario_text;
	var url = glossario_url + "?t=" + escape(glossario_request_count) + "&q=" + escape(query) + "&locale=" + escape(glossario_locale) + "&act=search";
	//alert('20. creo la url da lanciare che corrisponde a '+url+'');
	var req = false;
    
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }
    
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
    }
	//alert('21. istanzio loggetto xmlhttprequest e ottengo la req --> '+req+'');
	if(req) {

		req.onreadystatechange = new Function ("processReqChange(" + glossario_requests.length + ");");
		req.open("GET", url, true);
		req.send(null);
		//alert(url);
		glossario_requests.push( req );
		
		var dove = findPos( glossario_form );
		
		var divOverlayer = document.getElementById("glossario_outer_div");
		divOverlayer.style.display = "";
		divOverlayer.style.left = dove[0] + "px";
		var tp = dove[1] + dove[3];
		divOverlayer.style.top = tp + "px";
		glossario_visible = true;
	}
	
}




function processReqChange( ind ) {
	
	//alert('22. onreadystatechange positivo quindi parto con la processReqChange');
	var req = glossario_requests[ind];
	//alert('23. recupero la req --> '+req+'');
	
	if ( req==null ) return;
	
	if (req.readyState == 4) {
		//alert('24. readyState = 4');// only if "OK"
		if (req.status == 200) {
            //alert('25. status = 200');
			//valutiamo il dom, con il risultato
			var token = req.responseXML.getElementsByTagName("token");
			 //alert('26. ottengo la collection di token nella responseXML --> '+token+'');
			if (token.length==0 || Number(token[0].textContent) <=glossario_last_reply ) return;
			
			glossario_last_reply = Number(token[0].textContent);
			
			var risultati = req.responseXML.getElementsByTagName("result");
			
			glossarioResultReset(); // vuotiamo i risultati
			
			var inputValue = document.getElementById('glossSearchField').value;

			////////////////////////AUTOCOMPLETAMENTO
			//if(x){window.clearTimeout(x);}
			//var x = window.setTimeout("autoDefine();", 3500);
			
			for ( var i = 0; i<risultati.length && i<glossario_max_results; i++ ) {
				var tit = risultati[i].getElementsByTagName("word");
				var quid = risultati[i].getElementsByTagName("id");

				if ( tit.length>0 && quid.length>0 ) {
					
					tit = tit[0].firstChild.nodeValue;
					quid = quid[0].firstChild.nodeValue;
					var stringTit = '<b>'; var n = 0;
					
					for(u=0;u<tit.length;u++){
						if(tit.charAt(u).toLowerCase() == inputValue.charAt(u).toLowerCase()){
							stringTit += tit.charAt(u);
							n = u;
						}
					}

					stringTit += '</b>';
					var newTit = stringTit + tit.substr(n+1,tit.length);
					
					//inserimento
					//var codice = "<div id='risultato_"+i+"' class='glossario_result'>";
					//codice += "<a class='title'>" + tit + "</p>";
					var ahref = '<a class="title" id="href1_'+i+'" name="'+quid+'">' + newTit + '</p>';
					//codice += "</div>"; 
					var codice = document.createElement('div');
					codice.setAttribute('id', 'risultato_'+i+'');
					codice.setAttribute('class', 'glossario_result');
					codice.innerHTML = ahref;
					
					// inserimento 
					var container = document.getElementById("glossario_results");
					//container.insertAdjacentHTML( "beforeEnd", codice );
					container.appendChild(codice);
					
					if(navigator.appName == 'Microsoft Internet Explorer'){
						document.getElementById('risultato_'+i+'').className = 'glossario_result';
						document.getElementById('href1_'+i+'').className = 'title';
					}

					var rigaRisultato = document.getElementById("risultato_"+i);
					
					rigaRisultato.onmousedown = new Function( "glossarioDefine('" + quid + "');" );
					
					rigaRisultato.onmouseover = new Function( "glossarioRollover('risultato_"+i+"');" );
					rigaRisultato.onmouseout = new Function( "glossarioRollout('risultato_"+i+"');" );
					
				}
			}
			
			if ( risultati.length==0 ) {
				glossarioResultReset();
				/*var newHTML = "";
				newHTML += "<div id='glossario_wait'>";
				newHTML += "Nessun risultato";
				newHTML += "</div>";*/

				var newHTML = document.createElement('div');
				newHTML.setAttribute('id','glossario_wait');
				newHTML.innerHTML = 'No Results';

				var container = document.getElementById("glossario_results");
				//container.insertAdjacentHTML( "beforeEnd", newHTML );	
				container.appendChild(newHTML);
			}
			
			
		} else {
			//alert("There was a problem retrieving the XML data:\n" + req.statusText);
			glossarioResultReset();
			/*var newHTML = "";
			newHTML += "<div id='glossario_wait'>";
			newHTML += "Servizio non disponibile";
			newHTML += "</div>";*/
			
			var newHTML1 = document.createElement('div');
			newHTML1.setAttribute('id','glossario_wait');
			newHTML1.innerHTML = 'The Service is not available';
	
			var container = document.getElementById("glossario_results");
			//container.insertAdjacentHTML( "beforeEnd", newHTML );
			container.appendChild(newHTML1);
		}
	}
}

////////////////////////AUTOCOMPLETAMENTO
/*function autoDefine(){
	var inputValue = document.getElementById('glossSearchField').value;
	if(document.getElementById('href1_0')){
		var firstResult = document.getElementById('href1_0').innerHTML;
	}else{var firstResult = '';}
	var string = firstResult.toString(); var newString = '';

	for(h=0;h<string.length;h++){
		if(string.charAt(h) != '<' && string.charAt(h) != '>' && string.charAt(h) != '/'){
			if(string.charAt(h).toLowerCase() == 'b' || string.charAt(h).toLowerCase() == 'p'){
				j = h + 1;
				if(string.charAt(j) != ">"){newString += string.charAt(h);}
			}else{
				newString += string.charAt(h);
			}
		}
	}
	//alert('newString='+newString);
	document.getElementById('glossSearchField').value=newString;
}*/

function glossarioRollover( elemento ) {
	var container = document.getElementById(elemento);
	if (container==null) return;
	container.style.backgroundColor="#AAAAAA";
}

function glossarioRollout( elemento ) {
	var container = document.getElementById(elemento);
	if (container==null) return;
	container.style.backgroundColor="";
}


function hideGlossario() {
	
	if ( glossario_visible==false ) return;
	
	//Nascondiamo capo glossario
	glossario_visible = false;
	var divOverlayer = document.getElementById("glossario_outer_div");
	
	
	// Resettiamo
	glossarioResultReset();
	
	//reinseriamo
	/*var newHTML = "";
	newHTML += "<div id='glossario_wait'>";
	newHTML += "Ricerca";
	newHTML += "</div>";*/
	
	var newHTML2 = document.createElement('div');
	newHTML2.setAttribute('id','glossario_wait');
	newHTML2.innerHTML = 'Searching';
	
	var container = document.getElementById("glossario_results");
	//container.insertAdjacentHTML( "beforeEnd", newHTML );
	container.appendChild(newHTML2);
	//alert('12. carico allinterno del div di ricerca la semplice scritta "Ricerca"');
		
	divOverlayer.style.display = "none";
	//alert('13. hideGlossario , nascondo la ricerca');
	glossario_text = "";
	
}



function glossarioFieldCallback() {
	//alert('14. sono entrato nell glossarioFieldCallback(keyup)');
	var query = glossario_field.value;
	//alert('15. ottengo il nuovo value');
	// se ultima lettera è != da " " settiamo il timeout, altrimenti inviamo subito la ricerca
	var lastchar = query.substr( query.length-1 ,1);
	//alert('16. ottengo lultimo carattere del value');
	if ( lastchar!==" ") {
		//alert('17. se lultimo carattere non è vuoto sparo la glossarioTimeoutHandler con come unico parametro la query(value del campo di ricerca)');
		window.setTimeout( 'glossarioTimeoutHandler(\''+ query +'\')',	glossario_delay);
	} else {
		showGlossario( query );
	}
	
}

function glossarioTimeoutHandler( testo ) {
	//alert('18. questa funzione non fa altro che controllare se il testo è cambiato o meno e restituire la showGlossario');
	//valutiamo se il campo è mutato. nel caso non lo sia portiamo avanti
	var query = glossario_field.value;
	if ( testo!=query ) return;
	showGlossario( testo );
	
}



// --------------------------------------------------------------------| Caricamento contenuto

function glossarioDefine( testo ) {
	
	//document.getElementById('explainText').focus();
	document.getElementById('glossSearchField').blur();
	var query = testo;
	var url = glossario_url + "?t=0&q=" + escape(query) + "&locale=" + escape(glossario_locale) + "&act=define";
	
	var req = false;
    
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }
    
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
    }
	
	if(req) {
		req.onreadystatechange = function(){ processGlossChange(req); }
		req.open("GET", url, true);
		req.send(null);
	}
	
	hideGlossario();
}




function processGlossChange(page_request) {
	containerid = "explainText";
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1) ) {
		var elementoDiv =  document.getElementById(containerid);
		if (elementoDiv==null) return;
		divExpTxtObj = document.getElementById("divExplainText");
		document.getElementById("glossBody").style.height = '132px';
		divExpTxtObj.style.display="block";
		elementoDiv.innerHTML = page_request.responseText;
	}
}

// --------------------------------------------------------------------| Compatibility patch e utility

function Browser() {

	var ua, s, i;

	this.isIE    = false;
	this.isNS    = false;
	this.version = null;

	ua = navigator.userAgent;

	s = "MSIE";
	if ((i = ua.indexOf(s)) >= 0) {
    	this.isIE = true;
    	this.version = parseFloat(ua.substr(i + s.length));
    	return;
	}

	s = "Netscape6/";
	if ((i = ua.indexOf(s)) >= 0) {
    	this.isNS = true;
    	this.version = parseFloat(ua.substr(i + s.length));
    	return;
  	}

  	// Treat any other "Gecko" browser as NS 6.1.

  	s = "Gecko";
  	if ((i = ua.indexOf(s)) >= 0) {
    	this.isNS = true;
    	this.version = 6.1;
    	return;
  	}
}

var browser = new Browser();

function findPos(obj) {
	
	var mw = mh = 0;
	mw = obj.offsetWidth;
	mh = obj.offsetHeight;
	
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	
	return [curleft,curtop,mw,mh];
}

function addResizedEvent(func) {	
	var oldonload = window.onresize;
	if (typeof window.onresize != 'function') {
    	window.onresize = func;
	} else {
		window.onresize = function(){
		oldonload();
		func();
		}
	}
}

addResizedEvent(hideGlossario);

function trim(s) {
	var l=0; var r=s.length -1;
	while(l < s.length && s[l] == ' ')
	{	l++; }
	while(r > l && s[r] == ' ')
	{	r-=1;	}
	return s.substring(l, r+1);
}

function addLoadEvent(func) {	
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
    	window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

////////////////////////////////////////////// Cross-browser implementation
var precKey = false; 
var firstPass = true;
var nId = '';
document.onkeydown = keyDown

function keyDown(e) {
	if(document.all){
		var key=event.keyCode;
		var realKey = String.fromCharCode(event.keyCode);
	}else{
		var key = e.which;
		var realKey = String.fromCharCode(e.which);
	}
	selectWord(key);
}

function selectWord(key){
	if(key != '38' && key != '40' && key != '13'){
		precKey = false;
		firstPass = true;
	}
	if(document.getElementById('risultato_0')){
		var exist = document.getElementById('risultato_0');
		precKey = (precKey)? precKey:exist;
		var reduce = precKey.id.substr(10,1);
		//alert('reduce = '+reduce);
		var rKey = 'risultato_' + (parseInt(reduce)-1);
		//alert('rKey = '+rKey);
		var aKey = 'risultato_' + (parseInt(reduce)+1);
		//alert('aKey = '+aKey);
		if(key == '38' && exist && reduce>0){
			//alert('entro nel reduce con key='+key+',exist='+exist+'e reduce='+reduce);
			nId = rKey.substr(10,1);
			if(document.getElementById(rKey)){
				var nElement = document.getElementById(rKey);
				//alert(nId);
				precKey.style.backgroundColor = '';
				nElement.style.backgroundColor = '#999';
				precKey = nElement;
			}
		}
		if(key == '40' && exist && reduce<4){
			if(firstPass){var aKey = 'risultato_0';firstPass = false;}
			//alert('entro nel adding con key='+aKey+',exist='+exist+'e firstpass='+firstPass);
			nId = aKey.substr(10,1);
			if(document.getElementById(aKey)){
				var nElement = document.getElementById(aKey);
				//alert(nId);
				precKey.style.backgroundColor = '';
				nElement.style.backgroundColor = '#999';
				precKey = nElement;
			}
		}
		if(key == '13' && exist && reduce){
			document.getElementById('glossSearchField').blur();
			var hrefId = 'href1_' + nId;
			if(document.getElementById(hrefId)){
				var testo = document.getElementById(hrefId).name;
				//alert('ho schiacciato invio il numero id è ' + testo);
				window.setTimeout('glossarioDefine( '+testo+' )', 600);
			}
			precKey = false; firstPass = true;
		}
	}
}

// Workaround safari
if (navigator.vendor == "Apple Computer, Inc." || navigator.vendor == "KDE") { 
	
	function Document() {}
	function Event() {}
	function HTMLCollection() {}
	function HTMLElement() {}
	function Node() {}
	Document.prototype       = window["[[DOMDocument]]"];
	Event.prototype          = window["[[DOMEvent]]"];
	HTMLCollection.prototype = window["[[HTMLCollection.prototype]]"];
	HTMLElement.prototype    = window["[[DOMElement.prototype]]"];
	Node.prototype           = window["[[DOMNode.prototype]]"];
	
}
//Workaround per l'inserimento dinamico di elementi in firefox
if( typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement ) {
	HTMLElement.prototype.insertAdjacentElement = function (where,parsedNode) { 
		switch (where){
		case 'beforeBegin':
			this.parentNode.insertBefore(parsedNode,this)
			break;
		case 'afterBegin':
			this.insertBefore(parsedNode,this.firstChild);
			break;
		case 'beforeEnd':
			this.appendChild(parsedNode);
			break;
		case 'afterEnd':
			if (this.nextSibling) this.parentNode.insertBefore(parsedNode,this.nextSibling);
			else this.parentNode.appendChild(parsedNode);
			break;
		}
	}

	HTMLElement.prototype.insertAdjacentHTML = function (where,htmlStr) {
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where,parsedHTML)
	}


	HTMLElement.prototype.insertAdjacentText = function (where,txtStr) {
		var parsedText = document.createTextNode(txtStr)
		this.insertAdjacentElement(where,parsedText)
	}
}