/** (C) HTML.IT - insieme di funzioni ed oggetti utili per interagire con ajax */

/** FUNZIONI */

	// funzione per prendere un elemento con id univoco
		function prendiElementoDaId(id_elemento) {
			var elemento;
			if(document.getElementById)
				elemento = document.getElementById(id_elemento);
			else
				elemento = document.all[id_elemento];
			return elemento;
		};
	
	// funzione per assegnare un oggetto XMLHttpRequest
		function assegnaXMLHttpRequest() {
			var
				XHR = null,
				browserUtente = navigator.userAgent.toUpperCase();
			if(typeof(XMLHttpRequest) === "function" || typeof(XMLHttpRequest) === "object")
				XHR = new XMLHttpRequest();
			else if(window.ActiveXObject && browserUtente.indexOf("MSIE 4") < 0) {
				if(browserUtente.indexOf("MSIE 5") < 0)
					XHR = new ActiveXObject("Msxml2.XMLHTTP");
				else
					XHR = new ActiveXObject("Microsoft.XMLHTTP");
			}
			return XHR;
		};
		
		// funzione per leggere il contenuto presente
		// all'interno di un nodo XML, ad esempio
		// su <guida>ajax</guida> restituisce solo ajax
		function leggiContenuto(item, nomeNodo) {
		  return item.getElementsByTagName(nomeNodo).item(0).firstChild.nodeValue;
		}; 


/** OGGETTI / ARRAY */

	// oggetto di verifica stato
		var readyState = {
			INATTIVO:	0,
			INIZIALIZZATO:	1,
			RICHIESTA:	2,
			RISPOSTA:	3,
			COMPLETATO:	4
		};

	// array descrittivo dei codici restituiti dal server
	// [la scelta dell' array è per evitare problemi con vecchi browsers]
		var statusText = new Array();
		statusText[100] = "Continue";
		statusText[101] = "Switching Protocols";
		statusText[200] = "OK";
		statusText[201] = "Created";
		statusText[202] = "Accepted";
		statusText[203] = "Non-Authoritative Information";
		statusText[204] = "No Content";
		statusText[205] = "Reset Content";
		statusText[206] = "Partial Content";
		statusText[300] = "Multiple Choices";
		statusText[301] = "Moved Permanently";
		statusText[302] = "Found";
		statusText[303] = "See Other";
		statusText[304] = "Not Modified";
		statusText[305] = "Use Proxy";
		statusText[306] = "(unused, but reserved)";
		statusText[307] = "Temporary Redirect";
		statusText[400] = "Bad Request";
		statusText[401] = "Unauthorized";
		statusText[402] = "Payment Required";
		statusText[403] = "Forbidden";
		statusText[404] = "Not Found";
		statusText[405] = "Method Not Allowed";
		statusText[406] = "Not Acceptable";
		statusText[407] = "Proxy Authentication Required";
		statusText[408] = "Request Timeout";
		statusText[409] = "Conflict";
		statusText[410] = "Gone";
		statusText[411] = "Length Required";
		statusText[412] = "Precondition Failed";
		statusText[413] = "Request Entity Too Large";
		statusText[414] = "Request-URI Too Long";
		statusText[415] = "Unsupported Media Type";
		statusText[416] = "Requested Range Not Satisfiable";
		statusText[417] = "Expectation Failed";
		statusText[500] = "Internal Server Error";
		statusText[501] = "Not Implemented";
		statusText[502] = "Bad Gateway";
		statusText[503] = "Service Unavailable";
		statusText[504] = "Gateway Timeout";
		statusText[505] = "HTTP Version Not Supported";
		statusText[509] = "Bandwidth Limit Exceeded";

// aggiunge la classe "current" al nodo di nome oSuggestionNode e toglie la classe al nodo vecchio
AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) {

    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i];
        if (oNode == oSuggestionNode) {
            oNode.className = "current"
        } else if (oNode.className == "current") {
            oNode.className = "";
        }
    }
};
      
// cambia lo stile del layer a "hidden"
AutoSuggestControl.prototype.hideSuggestions = function () {
    this.layer.style.visibility = "hidden";
};   


// funzione che crea un elemento div nel document di classe "suggestion" e lo crea "hidden" e della stessa larghezza della textBox
// inoltre gestisce gli eventi del mouse sulla lista
AutoSuggestControl.prototype.createDropDown = function () {

    this.layer = document.createElement("div");
    this.layer.className = "suggestions";
    this.layer.style.visibility = "hidden";
    this.layer.style.width = this.textbox.offsetWidth;
    document.body.appendChild(this.layer);

    // gestione mouse
    var oThis = this;

    this.layer.onmousedown = this.layer.onmouseup =
    this.layer.onmouseover = function (oEvent) {
        oEvent = oEvent || window.event;
        oTarget = oEvent.target || oEvent.srcElement;

        if (oEvent.type == "mousedown") {
            oThis.textbox.value = oTarget.firstChild.nodeValue;
            oThis.hideSuggestions();
        } else if (oEvent.type == "mouseover") {
            oThis.highlightSuggestion(oTarget);
        } else { // mouseup
            oThis.textbox.focus();
        }
    };

};

// funzione che calcola la distanza dal bordo sinistro della pagina del textBox, prendendo per ogni nodo della pagina, la distanza dal nodo padre, fino al nodo body
AutoSuggestControl.prototype.getLeft = function () {

    var oNode = this.textbox;
    var iLeft = 0;

    while(oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;
    }

    return iLeft;
};

// idem come sopra
AutoSuggestControl.prototype.getTop = function () {

    var oNode = this.textbox;
    var iTop = 0;

    while(oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }

    return iTop;
};

// funzione che accetta una lista di suggerimenti e li mostra nel layer, in pratica crea un div dentro a layer per ogni suggerimento e ci scrive dentro la parola
AutoSuggestControl.prototype.showSuggestions = function (aSuggestions) {
    var oDiv = null;
    this.layer.innerHTML = "";
	
    for (var i=0; i < aSuggestions.length; i++) {
	
        oDiv = document.createElement("div");
        oDiv.appendChild(document.createTextNode(aSuggestions[i]));
        this.layer.appendChild(oDiv);
    }
	//POSIZIONO QUI I SUGGERIMENTI IN BASE A DOVE SI TROVA ATTUALMENTE IL CAMPO RICERCA
	if (document.getElementById('key'))
	{
		this.layer.style.top = "112px";
		this.layer.style.left = findPosX(document.getElementById('key')) - 12 + "px";
		this.layer.style.position = "absolute";
		this.layer.style.visibility = document.getElementById('key').style.visibility;
	}
};

AutoSuggestControl.prototype.nextSuggestion = function () {
    var cSuggestionNodes = this.layer.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) {
        var oNode = cSuggestionNodes[++this.cur];
        this.highlightSuggestion(oNode);
        this.textbox.value = oNode.firstChild.nodeValue;
    }
};

AutoSuggestControl.prototype.previousSuggestion = function () {
    var cSuggestionNodes = this.layer.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur > 0) {
        var oNode = cSuggestionNodes[--this.cur];
        this.highlightSuggestion(oNode);
        this.textbox.value = oNode.firstChild.nodeValue;
    }
};

// funzione che verrà bindata per gestire gli eventi key arrow
AutoSuggestControl.prototype.handleKeyDown = function (oEvent) {
    switch(oEvent.keyCode) {
        case 38: //up arrow
            this.previousSuggestion();
            break;
        case 40: //down arrow
            this.nextSuggestion();
            break;
        case 13: //enter
            this.hideSuggestions();
            break;
    }
};

       
//Definizione della classe AutoSuggestControl
function AutoSuggestControl(oTextbox, oProvider) {
    this.cur = -1;
    this.layer = null;
    this.provider = oProvider;
    this.textbox = oTextbox;
    this.init(); // assegno la gestione del onkeyup del textbox alla funzione handleKeyUp
}

// creo il metodo selectRange della classe AutoSuggestControl
// questa funzione seleziona la stringa del textbox a partire da iStart per iLength caratteri
AutoSuggestControl.prototype.selectRange = function (iStart, iLength) {
    if (this.textbox.createTextRange) { // explorer
        var oRange = this.textbox.createTextRange();
        oRange.moveStart("character", iStart);
        oRange.moveEnd("character", iLength - this.textbox.value.length);
        oRange.select();
    } else if (this.textbox.setSelectionRange) { // mozilla
        this.textbox.setSelectionRange(iStart, iLength);
    }

    this.textbox.focus();
};

// funzione che seleziona scrive il Suggerimento sSuggestion nel textField e seleziona la parte rimanente da scrivere
// accetta come parametro la stringa suggerita sSuggestion e fa uso della funzione selectRange appena vista
AutoSuggestControl.prototype.typeAhead = function (sSuggestion) {
    if (this.textbox.createTextRange || this.textbox.setSelectionRange) {
        var iLen = this.textbox.value.length;
        this.textbox.value = sSuggestion;
        this.selectRange(iLen, sSuggestion.length);
    }
};

//funzione che controlla che i suggerimenti aSuggestions (ci possono essere + diuna parola che comincia per xxx) ci siano e seleziona la prima
// il secondo parametro serve per il dropDown menu, ed è un booleano che indica se fare o no il typeAhead, e se è false, nasconde la tendina
AutoSuggestControl.prototype.autosuggest = function (aSuggestions,  bTypeAhead) {
	
    if (aSuggestions.length > 0) {
	    if (bTypeAhead) {
	    
		    this.typeAhead(aSuggestions[0]);
		}
		this.showSuggestions(aSuggestions);
	    } else {
		this.hideSuggestions();
    }
};

// questa funzione controlla quale tasto è stato premuto e se è il caso di procedere con l'autosuggest
AutoSuggestControl.prototype.handleKeyUp = function (oEvent) {
    var iKeyCode = oEvent.keyCode;
    
    if (iKeyCode == 8 || iKeyCode == 46) {
        this.provider.requestSuggestions(this, false);

    } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode <= 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
        //ignore
    } else {
        //this.provider.requestSuggestions(this);
	this.provider.requestSuggestions(this, false);
    }
};

// funzione per far gestire alla funzione handleKeyUp l'evento keyUp del controllo textbox della classe AutoSuggestControl
AutoSuggestControl.prototype.init = function () {
    var oThis = this;
    this.textbox.onkeyup = function (oEvent) { // quando si verifica un evento onkeyup, esegui questa funzione passandogli l'oggetto oEvent che è una cosa propria del DOM
        if (!oEvent) { // può essere che con Explorer non ci sia l'oggett oEvent, al suo posto viene utilizzato l'oggetto event della classe window
            oEvent = window.event;
        }
	
        oThis.handleKeyUp(oEvent); // assegno a handleKeyUp la gestione dell'evento onkeyUp
    };
    
    
    // per gestire le freccie e l'enter per il menu a tendina
    this.textbox.onkeydown = function (oEvent) {

        if (!oEvent) {
            oEvent = window.event;
        }

        oThis.handleKeyDown(oEvent);
    };
    
    // per gestire la perdita del focus, dovrò nascondere la tendina
     this.textbox.onblur = function () {
        oThis.hideSuggestions();
    };

    this.createDropDown();
};

// è la classe provider
function StateSuggestions() {

    this.states = [
    "Abelardo","Antonio","Amilcare","Aida","Amanda","Alberto","Adelaide","Anna","Alessandra","Alessandro","Andrea",
    "Baldassarre","Beatrice","Benedetta","Benito","Berto","Bruno",
    "Caio","Calimero","Calliope","Callimaco","Callisto","Carlo","Cecilia","Claudia","Ciro","Cristian",
    "Dafne","Dante","Danilo","Davide","Denis","Domenico",
    "Emilio","Ernesto","Evaristo",
    "Fabio","Francesco","Federico","Ferruccio",
    "Giacomo","Giuseppe","Gianfranco","Gigi","Geronimo","Geremia","Gerardo","Geppetto","Gabriele","Guglielmo","Guerrino","Gambadilegno","Galbusera","Guido",
    "Luigi","Libero","Laura","Loretta","Luca",
    "Mario","Michele","Mauro","Mattia",
    "Nicola","Nino","Nivea",
    "Oreste","Olga","Olimpia","Oscar","Osvaldo","Omar",
    "Pippo","Peppino","Pasquale","Patrizia","Piero",
    "Quarto","Quirino",
    "Roberta","Roberto","Romeo","Remigio","Rosanna","Raffaele",
    "Sabina","Saverio","Silvano","Silvio","Simone","Sempronio",
    "Tizio","Tiziano","Tullio",
    "Ubaldo","Ugo","Umberto","Ulisse",
    "Veronica","Vinicio","Valentina","Valentino","Virgilio","Vladimiro",
    "Walter","Wanda","Wilma",
    "Zenone","Zaccaria"
    ];
}

// funzione che richiede i suggerimenti passandogli un AutoSuggestControl
StateSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl,  bTypeAhead) 
{
    var aSuggestions = [];
    var sTextboxValue = oAutoSuggestControl.textbox.value;
    
    if (sTextboxValue.length > 0)
	{
		var ajax = assegnaXMLHttpRequest();
	
		if(ajax) 
		{
			ajax.onreadystatechange = function() 
			{
				if(ajax.readyState === readyState.COMPLETATO) 
				{
					if(statusText[ajax.status] === "OK")
					{
						if(ajax.responseXML)
						{
							var xml = ajax.responseXML.documentElement;
							var nome = xml.getElementsByTagName("nome");
							for(var a = 0; ((a < nome.length) && (a < 8)); a++) 
							{
								aSuggestions.push(nome[a].childNodes[0].nodeValue);
							}
							
							oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);
	
						}
					}
				} 
			}
	
			ajax.open("get", "query_valori_ricerca.asp?val=" + sTextboxValue, true);
			ajax.setRequestHeader("connection", "close");
			ajax.send(null);
		}
	}
};

window.onload = function () {
                var oTextbox = new AutoSuggestControl(document.getElementById("key"), new StateSuggestions());        
            }
