// variabile che conterra' l'oggetto di comunicazione
var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject(){
	var xmlHttp;
	
	if(window.ActiveXObject){
		console.log("IE less than 7");
		try {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch(e){
			xmlHttp = false;
		}
	} else {
		console.log("others");
		try {
			xmlHttp = new XMLHttpRequest();
		} catch(e){
			xmlHttp = false;
		}
	}
	
	if(!xmlHttp) {
		console.log("error creating XMLHttp");
	} else {
		return xmlHttp;
	}
}



document.addEventListener("DOMContentLoaded", function(){
	var myButton = document.getElementById("myButton");
	console.log("DOMContentLoaded");
	myButton.addEventListener("click", process);
});

function process(){
	console.log("carica lista");
	
	if (xmlHttp) {
		try {
			xmlHttp.open("GET", "server/index.php", true);
			xmlHttp.onreadystatechange = handleRequestStateChange;
			xmlHttp.send(null); 
		} catch(e) {
			console.log("error opening connection: " + e.toString());
		}
		
	}
}

function handleRequestStateChange(){
	console.log("handleRequestStateChange: " + xmlHttp.readyState);
	
	if(xmlHttp.readyState == 4){
		if(xmlHttp.status == 200){
			try{
				handleServerResponse();
			} catch(e){
				console.log("errore nella lettura della risposta");
			}
			
		} else {
			console.log("file not found");
		}
	}
}

function handleServerResponse(){
	console.log("handleServerResponse: " + xmlHttp.responseText);
	console.log("handleServerResponse");
	
	var responseJSON = JSON.parse(xmlHttp.responseText);
	
	var html = "<ul>";
	
	for (var i=0; i < responseJSON.books.length; i++) {
		html += "<li>" + responseJSON.books[i].title + "</li>";
	}
	html += "</ul>";
	
	var myDiv = document.getElementById("myDivElement");
	myDiv.innerHTML = "<p>Server answers: " + html + "</p>";
	
}
