/**
 * @author Giovanni
 */
/** (C) HTML.IT - insieme di funzioni ed oggetti utili per interagire con ajax */

/** FUNZIONI */


	function loadList(tb, id){

		var xmlHttp = assegnaXMLHttpRequest();
		xmlHttp.open('GET', 'control/getoptions.php?table='+tb+'&id='+id, true);
		xmlHttp.onreadystatechange = function() {
			if(xmlHttp.readyState == readyState.COMPLETATO) {
				
				//Stato OK
				if (statusText[xmlHttp.status] == "OK") {
					var resp = xmlHttp.responseText;
					
					if(resp) {
						//Le coppie di valori nella striga di risposta sono separate da; èè
						var values = resp.split(';');
						//Il primo elemento è l'ID della lista.
						var listId = values.shift();
						var select = document.getElementById(listId);
						//Elimina i valori precedenti
						while (select.options.length) {
							select.remove(0);
						} 
						if(listId == 'province') {
							addOption (select, 0, '-- Seleziona --');
						}
						if(listId == 'regioni') {
							addOption (select, 0, '-- Seleziona --');
						}
						var limit = values.length;
						
						for(i=0; i < limit; i++) {
							var pair = values[i].split('|');
							//aggiunge un elemento <option>
							if (listId == 'regioni' & parseInt(id) == parseInt(pair[0])) {
								addOption(select, pair[0], pair[1], true);
							}
							else 
								addOption(select, pair[0], pair[1], false);
						}
					}
				} else {
					alert(xmlHttp.status);
				}
			}
		}
		xmlHttp.send(null);
	}
	
	function showmenu(menuname,param,callback) {
		var ajax = assegnaXMLHttpRequest(), menuelem = prendiElementoDaId("search_menu"), tabelem = prendiElementoDaId("results_table"),	
			usaLink = true;
		
		if(ajax) {
			tabelem.innerHTML='';
			menuelem.innerHTML='<div align="center"><img src="template/images/ajax-loader_bar.gif" alt="" /></div>';
			
    		usaLink = false;
			phpUrl='control/getmenu.php?menutype='+menuname;
			ajax.open("get", phpUrl, true);
			ajax.setRequestHeader("connection", "close");
		    ajax.onreadystatechange = function() {
				if(ajax.readyState === readyState.COMPLETATO) {
	        		if(statusText[ajax.status] === "OK") {
		        		menuelem.innerHTML = ajax.responseText;
						tabelem.innerHTML = "";
						if(menuname=='accordion') var myMenu = new ImageMenu($$('#imageMenu a'),{openWidth:200, border:2 });
						if (menuname == 'lettera' | menuname == 'regione' | menuname == 'settore') {
							loadList('regioni', param);
							if (menuname == 'regione') loadList('province', param);
							if (menuname == 'settore') {
								prendiElementoDaId(param).selected = true;
							}
						}
						if (callback==1) showresults(menuname,param);
					}
					else {
	         			menuelem.innerHTML = "Impossibile effettuare l'operazione richiesta.<br />";
	          			menuelem.innerHTML += "Errore riscontrato: " + statusText[ajax.status];
	        		}
	      		} 
    		}
			ajax.send(null);
  		}
   		return usaLink;
	}
	
	function showresults(searchtype,parametro){
		var ajax = assegnaXMLHttpRequest(), tabelem = prendiElementoDaId("results_table"),	
			usaLink = true;
		
		if(ajax) {
			tabelem.innerHTML='<div align="center"><img src="template/images/ajax-loader_bar.gif" alt="" /></div>';
    		usaLink = false;
			params=0;
			phpUrl='control/getsearchresults.php'; 

			if ((searchtype != null)&(parametro != null)) {
				phpUrl += (params == 0 ? "?" : "&")+searchtype+"="+parametro;
				params++;
			}
			
			if (prendiElementoDaId("nome") != null) {
				phpUrl += (params == 0 ? "?" : "&") + "nome=" + prendiElementoDaId('nome').value;
				params++;
			}

			if (prendiElementoDaId("regioni") != null) {
				if (prendiElementoDaId("regioni").value != "0" & prendiElementoDaId("regioni").value != "") {
					phpUrl += (params == 0 ? "?" : "&") + "regione=" + prendiElementoDaId('regioni').value;
					params++;
				}
			}
			
			if (prendiElementoDaId("province") != null) {
				if (prendiElementoDaId("province").value != "0" & prendiElementoDaId("province").value != "") {
					phpUrl += (params == 0 ? "?" : "&") + "provincia=" + prendiElementoDaId('province').value;
					params++;
				}
			}
			if (prendiElementoDaId("settori") != null) {
				if (prendiElementoDaId("settori").value != "0" & prendiElementoDaId("settori").value != "") {
					phpUrl += (params == 0 ? "?" : "&") + "settore=" + prendiElementoDaId('settori').value;
					params++;
				}
			}
			ajax.open("get", phpUrl, true);
			ajax.setRequestHeader("connection", "close");
		    ajax.onreadystatechange = function() {
				if(ajax.readyState === readyState.COMPLETATO) {
	        		if(statusText[ajax.status] === "OK") {
						tabelem.innerHTML = ajax.responseText;
						box = new MultiBox('mb', {descClassName: 'multiBoxDesc', useOverlay:true});
					}
					else {
	         			tabelem.innerHTML = "Impossibile effettuare l'operazione richiesta.<br />";
	          			tabelem.innerHTML += "Errore riscontrato: " + statusText[ajax.status];
	        		}
	      		} 
    		}
			ajax.send(null);
  		}
   		return usaLink;
	}
	
	function showmacroresults(searchtype,param){
		showmenu(searchtype,param,1);
		//showresults(searchtype,param);
	}



	//Aggiunge un elemento <option> ad una lista <select>
	function addOption(select, value, text, selected) {
		var option = document.createElement("option");
		option.value = value,
		option.text = text;
		if (selected) option.selected=true;
		try {
			select.add(option, null);
		} catch(e) {
			//Per Internet Explorer
			select.add(option);
		}
	}
	
	//Ritorna il valore dell'elemento <option> selezionato in una lista
	function getSelected(select) {
		return select.options[select.selectedIndex].value;
	}
		

	// 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;
	};



/** 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";