var xmlHttp = getXmlHttpObject();

//carica la lista di valori 
//dalla tabella table
//dalla colonna col per il valore data
//restituisce la colonna res
//e scrive nel componente dest
//loadList('comuni','pv',getSelected(this),'code','name','municipality','".$this->municipality."')
function loadList(table, col, src, val, name, dest, selected){
	xmlHttp.open('GET', 'list.php?table='+table+'&col='+col+'&src='+src+'&val='+val+'&name='+name+'&dest='+dest+'&selected='+selected, true);
	xmlHttp.onreadystatechange = stateChanged;
	xmlHttp.send(null);
}

function addOption(select, value, text, selected) {
	//Aggiunge un elemento <option> ad una lista <select>
	var option = document.createElement("option");
	option.value = value,
	option.text = text;
	if(value==selected){
		option.selected=true;
	}
	try {
		select.add(option, null);
	} catch(e) {
		//Per Internet Explorer
		select.add(option);
	}
}

function getSelected(select) {
	//Ritorna il valore dell'elemento <option> selezionato in una lista
	return select.options[select.selectedIndex].value;
}

function stateChanged() {
	if(xmlHttp.readyState == 4) {
		//Stato OK
		if (xmlHttp.status == 200) {
			var resp = xmlHttp.responseText;
			
			if(resp) {
				//i valori sono separati da ;
				var values = resp.split(';');
				//Il primo elemento è l'ID della lista.
				var listId = values.shift();
				var select = document.getElementById(listId);
				//Il secondo elemento è l'elemento selezionato
				var selected = values.shift();
				//Elimina i valori precedenti
				while (select.options.length) {
					select.remove(0);
				}
				var limit = values.length;
				for(i=0; i < limit; i+=2) {
					//aggiunge un elemento <option>
					addOption(select, values[i], values[i+1], selected);
				}
			}
		} else {
			alert(xmlHttp.responseText);
		}
	}
}

function getXmlHttpObject(){
  	var xmlHttp=null;
  	try{
    	// Firefox, Opera 8.0+, Safari
    	xmlHttp=new XMLHttpRequest();
	}catch (e){
    	// Internet Explorer
    	try{
     		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      	}catch (e){
      		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      	}
    }
  	return xmlHttp;
}
