var myData = [  ];
function myDatas(){
	myData = getAllData();
	document.getElementById("demo").innerHTML =myData;
}

function getAllData(){
	var allMyData=[];
	var totPoints=0;
	for (e = 1; e < 7; e++) {

		var theUrl = "http://www.fantagazzetta.com/api/live/"+e+"?g=36";
		var res = theUrl.split("=");
		var callback = function(response){
			var team = JSON.parse(response);
			totPoints = calcPoints(team);
			myData.push({"team": "squadra"+e, "punti": totPoints, "Giornata ": res[1]})

			console.log(myData);

		}

		console.log(e);
		httpGetAsync(theUrl, callback);
	}

	return allMyData;
}

function calcPoints(team){
	var s = 0;
	var cont = 0;
	while (cont < Object.keys(team).length){		//per ogni elemento del team[JSON] estrae voto: e lo somma in cont
		var valueVote = team[cont].voto;
		var valueEvent = team[cont].evento;
		s += valueVote;
		if (valueEvent != ""){
		    valueEvent = toInt(valueEvent);
			s += valueEvent;
		}

	cont += 1;
	}

	return s;

}

function toInt(valueEvent){
	eventInt = 0;
	if (valueEvent.indexOf(',') !== -1){
		var arr = valueEvent.split(",");
		for (i = 0; i < arr.length; i++){
			eventInt += parseInt(arr[i]);
		}
	}else{
		eventInt = parseInt(valueEvent);
	}
	return eventInt;

}

function httpGetAsync(theUrl, callback){ //codice che fa cose
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)

	   if (xmlHttp.responseText) { callback(xmlHttp.responseText); }
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous
    xmlHttp.send(null);
}

function checkForCookies(){
	if(getCookie('isAuth') != 'true'){
		window.location.href = "./index.html";
	} else{
		var role = getCookie('role');
		if(role != 'user' && role != 'admin'){
			window.location.href = "./index.html";
		}
	}
}
