// JavaScript Document
if (!window.console) console = { log: function(){} };

var xmlHttp = createXmlHttpRequestObject(); 
//xmlHttp.open("POST", "server/actionsObj.php", true);

xmlHttp.onreadystatechange = handleRequestStateChange;

var data = null;

function createXmlHttpRequestObject() { 
	// contiene il riferimento all'oggetto XMLHttpRequest 
	var xmlHttp;
	// se il browser �� Internet Explorer 6 o pi�� vecchio
	if(window.ActiveXObject) {
		try {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {
			xmlHttp = false;
		}
	}
	// se �� Mozilla o altri
	else {
		try {
			xmlHttp = new XMLHttpRequest();
		} catch (e) {
			xmlHttp = false;
		}
	}
	// ritorna l'oggetto o errore
	if (!xmlHttp) {
		alert("Error creating the XMLHttpRequest object.");
	} else {
		return xmlHttp;
	}
}


function loadToDo() {
	
	request_type = "load";
	
	if (xmlHttp) {

		try {
			
			xmlHttp.open("POST", "server/actionsObj.php", true);
			xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
			// xmlHttp.onreadystatechange = handleRequestStateChange;
			params = "action=" + request_type;
			xmlHttp.send(params);
		}
		// messaggio di errore
		catch (e) {
			alert("Can't connect to server:\n" + e.toString());
		}
	}
}


function sendToDo() {
	console.log("sendToDo");
	request_type = "insert";
	var todoText = document.getElementById('my-todo').value;
	document.getElementById('my-todo').value = "";
	
	if (todoText.length > 2) {
	
		if (xmlHttp) {
			// cerca di connetterti al server
			try {
				
				//Send the proper header information along with the request
				
				xmlHttp.open("POST", "server/actionsObj.php", true);
				xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
				// xmlHttp.onreadystatechange = handleRequestStateChange;
				params = "text=" + escape(todoText) + "&action=" + request_type;
				xmlHttp.send(params);
			}
			// messaggio di errore
			catch (e) {
				alert("Can't connect to server:\n" + e.toString());
			}
		}
	}
}


function updateToDo(todo_id, status) {
	
	request_type = "update";
	
	if (xmlHttp) {

		try {
			
			xmlHttp.open("POST", "server/actionsObj.php", true);
			xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
			// xmlHttp.onreadystatechange = handleRequestStateChange;
			params = "action=" + request_type + "&id=" + todo_id + "&status=" + status;
			xmlHttp.send(params);
		}
		// messaggio di errore
		catch (e) {
			alert("Can't connect to server:\n" + e.toString());
		}
	}
}



function deleteToDo(todo_id) {
	
	request_type = "delete";
	
	if (xmlHttp) {

		try {
			
			xmlHttp.open("POST", "server/actionsObj.php", true);
			xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
			// xmlHttp.onreadystatechange = handleRequestStateChange;
			params = "action=" + request_type + "&id=" + todo_id;
			xmlHttp.send(params);
		}
		// messaggio di errore
		catch (e) {
			alert("Can't connect to server:\n" + e.toString());
		}
	}
}

function handleRequestStateChange() {
	
	/*
	1 - uninitialized - Has not started loading yet
	2 - loading - Is loading
	3 - interactive - Has loaded enough and the user can interact with it
	4 - complete - Fully loaded
	*/// quando readyState �� 4, la risposta �� completata	
	if (xmlHttp.readyState == 4) {
		// controllo che lo stato della richiesta sia OK
		if (xmlHttp.status == 200) {
			try {
				
				data = JSON.parse(xmlHttp.responseText);
				var type = data["type"];
				
				switch(type) {
					
					case "load" :
						handleLoad();
					break;
					
					case "insert" :
					  	handleInsert();
					break;
					
					case "update" :
					 	handleUpdate();
					break;
					
					case "delete" :
					  	handleDelete();
					break;
					
				}
				
			} catch(e) {
				// display error message
				alert("Error reading the response: " + e.toString());
			}
		} else {
			// display status message
			alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
		}
	}
	
	console.log("xmlHttp.readyState: " + xmlHttp.readyState);
		
}

function handleLoad() {
	  var todos = data["todos"];
	  var toDoList="<ul id='todo-list'>";
	  var html = "";
	  
	  if (todos.length > 0) {
		  
		   document.querySelector('#my-to-do-list-container').insertAdjacentHTML('afterbegin', toDoList);
		   var toDoListRef = document.getElementById("todo-list");
		  
		   for (var i = 0; i < todos.length; i++) {
			  
			  html += "<li id='todo_" + todos[i]['id'] + "'" + ((todos[i]['completed'] === "1") ? "class='completed'>" : ">")  + "<span class='todo_text'>" + todos[i]['text'] 
							+ "</span> <span class='deleter'>x</span></li>\n"; 
		  	}
			toDoListRef.insertAdjacentHTML('beforeend', html);
		 	addDeleteListener();
			addUpdateListener();
	  } else {
		  html = "<p>Add a to do!</p>"
		  document.querySelector('#my-to-do-list-container').innerHTML = html;
	  }
}



function addDeleteListener() {
		[].forEach.call( document.querySelectorAll('.deleter'), function(el) {
   			el.addEventListener('click', function() {
				
				var id = this.parentNode.getAttribute("id");
				alert("delete id: " + id)
				deleteToDo(id);
				
		}, false);
		
	});
}

function addUpdateListener() {
		[].forEach.call( document.querySelectorAll('.todo_text'), function(el) {
   			el.addEventListener('dblclick', function() {
			
			  var id = this.parentNode.getAttribute("id");
			  
			  
			  var status = !hasClass(this.parentNode, 'completed');
			  
			  alert("doubleclick id: " + id + " / status: " + status);
			  updateToDo(id, status);
			});
		});
}

function hasClass(element, cls) {
    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}

function handleInsert() {
	console.log("to do added");
	
	// trova tutti i todo, in questo caso uno
	var todos = data["todos"];
	
	// crea una variabile per la risposta
	var html="";
	
	if (!document.getElementById("todo-list")) {
		var toDoList = document.createElement('ul');
		toDoList.setAttribute('id', 'todo-list');
		var container = document.querySelector('#my-to-do-list-container');
		container.innerHTML = "";
		container.appendChild(toDoList);
	}
	
	// cicla sui todo
	//for (var i = 0; i < todos.length; i++) {
    	console.log(todos[0]);
		var id 
		html += "<li id='todo_" + todos[0]['id'] + "'><span class='todo_text'>" + todos[0]['text'] + "</span> <span class='deleter'>x</span></li>\n";
		
		/*
		beforebegin - Before the element itself.
		afterbegin - just inside the element, before its first child.
		beforeend - just inside the element, after its last child.
		afterend - after the element itself.
		*/
		
		document.querySelector('#todo-list').insertAdjacentHTML('beforeend', html);
		
		
		// aggiunta listener sui nuovi elementi
		document.getElementById('todo_' + todos[0]['id']).querySelector('.deleter').addEventListener('click', function() {
				
				var id = this.parentNode.getAttribute("id");
				alert("delete id: " + id)
				deleteToDo(id);
				
		}, false);
		
		document.getElementById('todo_' + todos[0]['id']).querySelector('.todo_text').addEventListener('dblclick', function() {
			  var id = this.parentNode.getAttribute("id");
			  var status = !hasClass(this.parentNode, 'completed');
			  updateToDo(id, status);
		});
	//}
	
}

function handleUpdate() {
      if (data['updated'] == true) {
		  var element = document.getElementById(data['id'])
		  if(hasClass(element, 'completed')) {
			element.className = "";  
		  } else {
			element.className = "completed";
		  }
	  }
}


function handleDelete() {
      if (data['deleted'] == true) {
		  
		  var elemToBeDeleted = document.querySelector("#" + data['id']);
		  fadeAndDestroy(elemToBeDeleted);

		 
	  }
}


function fadeAndDestroy(element) {
    var op = 1;  // initial opacity
    var timer = setInterval(function () {
        if (op <= 0.1){
            clearInterval(timer);
			var toDoList=document.getElementById("todo-list");
			toDoList.removeChild(element);
			
			// se �� l'ultimo elemento ad essere rimosso risetta i messaggio "add to do"
			if (document.querySelectorAll('#todo-list > li').length == 0) {
		  		//console.log(jQuery('#todo-list > li').length);
				var html = "<p>Add a to do!</p>";
		  		document.getElementById('my-to-do-list-container').innerHTML = html;
	  		 }
			
        }
        element.style.opacity = op;
        element.style.filter = 'alpha(opacity=' + op * 100 + ")";
        op -= op * 0.1;
    }, 50);
}



document.addEventListener('DOMContentLoaded', function() {
	
	loadToDo();
	
	document.querySelector('#to_do_submit').addEventListener('click', sendToDo, false);
}, false);
