// CODICI TASTI
var LEFTARROW = 37;
var UPARROW = 38;
var RIGHTARROW = 39;
var DOWNARROW = 40;
var PAUSE = 19;

// VARIABILI GLOBALI
var idtimer = 0; // IDENTIFICATORE DEL TIMER
var tempobase; // INDICA L'INTERVALLO DI TEMPO TRA UNO SPOSTAMENTO E L'ALTRO (1/T = f)
var rigatestainiziale = Math.floor(ROWS / 2); // POSIZIONE INIZIALE CENTRATA
var colonnatestainiziale = Math.floor(COLS / 2); // POSIZIONE INIZIALE CENTRATA
var lunghezza; // LUNGHEZZA CORRENTE DEL SERPENTE
var occupatex; // ARRAY DELLE X DELLE LOCAZIONI OCCUPATE
var occupatey; // ARRAY DELLE Y DELLE LOCAZIONI OCCUPATE
var direzione; // DIREZIONE CORRENTE ("h" o "v")
var incremento; // VERSO DI SPOSTAMENTO: SX o SU -1, DX o GIU +1
var trascorso; // MOVIMENTI EFFETTUATI DALL'ULTIMO TOPO MANGIATO
var moved; // FLAG CHE INDICA SE E' STATO EFFETTUATO LO SPOSTAMENTO DALL'ULTIMA PRESSIONE
		   // DEI TASTI PER LA SCELTA DELLE DIREZIONI (elimina problemi di sovrapposizione)
var score; // PUNTEGGIO CORRENTE
var placed; // FLAG CHE INDICA SE IL NUOVO TOPO E' STATO POSIZIONATO O MENO (serve per nascondere
			// il topo fino a che non si preme il pulsante Play
var moving; // FLAG CHE INDICA SE L'OPERAZIONE DI MOVIMENTO E' IN CORSO (serve per evitare
			// esecuzioni parallele della funzione muovi() a causa di eventi timer pił
			// frequenti rispetto al tempo di esecuzione della funzione muovi()
var limitetempo; // NUMERO DI PASSI MASSIMI PER MANGIARE UN TOPO PRIMA CHE IL PUNTEGGIO VENGA
				 // ABBASSATO
var livello; // INDICA IL NUMERO DI MULTIPLI DI 20 PUNTI REALIZZATI
var parziale; // INDICA IL NUMERO DI PUNTI OTTENUTI DALL'INIZIO DEL NUOVO LIVELLO
// FUNZIONI

function resetdefault()
{
		tempobase = 150;
		livello = 1;
		lunghezza = 3;
		limitetempo = COLS + ROWS; // NECESSARIO PER COPRIRE LA DISTANZA MASSIMA
		occupatex =  new Array(colonnatestainiziale,
						  colonnatestainiziale + 1,
						  colonnatestainiziale + 2
						 );
		occupatey = new Array(rigatestainiziale,
						  rigatestainiziale,
						  rigatestainiziale
						 );
		direzione = "h";
		incremento = -1;
		trascorso = 0;
		score = 0;
		parziale = 0;
		moved = true;
		placed = false;
}

function disegna()
{
	var elemcas;
	var caselle = document.getElementsByName("elemcasella");
	for(i = 0; i < caselle.length; i++)
	{
		caselle[i].src = "img/sfondo.png";
		caselle[i].alt = "sfondo";
	}
	elemcas = document.getElementById("casella" + occupatey[0] + "_" + occupatex[0]);
	elemcas.src = "img/testa" + direzione + ".png";
	elemcas.alt = "testa";
	
	for(i = 1; i < occupatex.length-1; i++)
	{
		elemcas = document.getElementById("casella" + occupatey[i] + "_" + occupatex[i]);
		elemcas.src = "img/corpo.png";
		elemcas.alt = "corpo";
	}
	
	elemcas = document.getElementById("casella" + occupatey[occupatey.length-1] + "_" + occupatex[occupatex.length-1]);
	elemcas.src = "img/corpo.png";
	elemcas.alt = "coda";
	
	document.getElementById("score").value = score;
	document.getElementById("livello").value = livello;
	document.getElementById("tempo").value = tempobase - 10 * (livello-1);
}

function muro(elem)
{
	if(elem.alt == "sfondo")
	{
		elem.src = "img/muro.png";
		elem.alt = "muro";
	}
}

function muori()
{
	var miodiv = document.getElementById("messaggio");
	//miodiv.style.position = "relative";
	//miodiv.style.visibility = "visible";
	miodiv.style.display = "block";
	document.getElementById("btcambiastato").value = "Riavvia";
	pausa();
}

function muovi()
{
	moving = true;
	var prossimax = direzione=="h"?occupatex[0]+incremento:occupatex[0];
	var prossimay = direzione=="v"?occupatey[0]+incremento:occupatey[0];
	if(prossimax==COLS || prossimax < 0) { moving = false; muori(); return; }
	if(prossimay==ROWS || prossimay < 0) { moving = false; muori(); return; }
	var newcas = document.getElementById("casella" + prossimay + "_" + prossimax);
	if(newcas.alt != "sfondo" && newcas.alt != "coda" && newcas.alt != "topo") { moving = false; muori(); return; }
	var cresci;
	if(newcas.alt == "topo") { cresci = true; }
	else cresci = false;
	//cresci = trascorso==12?true:false;
	var vecchiatesta = document.getElementById("casella" + occupatey[0] + "_" + occupatex[0]);
	vecchiatesta.src = "img/corpo.png";
	vecchiatesta.alt = "corpo";
	var ultima = document.getElementById("casella" + occupatey[occupatey.length - 1] + "_" + occupatex[occupatex.length - 1]);
	if(cresci)
	{
		occupatex[lunghezza] = 0;
		occupatey[lunghezza] = 0;
		lunghezza++;
		trascorso = 0;
	}
	else
	{
		ultima.src = "img/sfondo.png";
		ultima.alt = "sfondo";
		trascorso++;
	}
	for(i = occupatey.length -1; i > 0; i--)
	{
		occupatex[i] = occupatex[i-1];
		occupatey[i] = occupatey[i-1];
	}
	occupatex[0] = prossimax;
	occupatey[0] = prossimay;
	var nuovaultima = document.getElementById("casella" + occupatey[occupatey.length - 1] + "_" + occupatex[occupatex.length - 1]);
	nuovaultima.alt = "coda";
	newcas.src = "img/testa" + direzione + ".png";
	newcas.alt = "testa";
	if(trascorso == limitetempo) { trascorso = 0; abbassapunti(); }
	if(cresci) { alzapunti(); posizionatopo(); }
	moved = true;
	moving = false;
}

function abbassapunti()
{
	score--;
	document.getElementById("score").value = score;
}

function alzapunti()
{
	score += 2*livello;
	parziale += 2*livello;
	document.getElementById("score").value = score;
	if(parziale > livello * 10)
	{
			livello++;
			parziale = 0;
			clearInterval(idtimer);
			idtimer = setInterval("muovi()", tempobase - 10 * (livello-1));
			document.getElementById("livello").value = livello;
			document.getElementById("tempo").value = tempobase - 10 * (livello-1);
	}
}

function play()
{
	idtimer = window.setInterval('muovi()', tempobase);
	if(!placed)
	{
		posizionatopo();
	}
}

function posizionatopo()
{
	// POSIZIONA IL TOPO A CASO EVITANDO LE CASELLE GIA' UTILIZZATE PER IL SERPENTE
	do
	{
		var col = Math.round(Math.random() * (COLS-1));
		var row = Math.round(Math.random() * (ROWS-1));
	} while(document.getElementById("casella" + row + "_" + col).alt!="sfondo");
	document.getElementById("casella" + row + "_" + col).alt = "topo";
	document.getElementById("casella" + row + "_" + col).src = "img/topo.png";
	placed = true;
}

function pausa()
{
	window.clearInterval(idtimer);
	idtimer = 0;
}

function cambiastato()
{
	if(document.getElementById("btcambiastato").value == "Play")
	{
		document.getElementById("btcambiastato").value = "Pausa";
		play();
	}
	else if(document.getElementById("btcambiastato").value == "Pausa")
	{
		document.getElementById("btcambiastato").value = "Play";
		pausa();
	}
	else if(document.getElementById("btcambiastato").value == "Riavvia")
	{
		var miodiv = document.getElementById("messaggio");
		//miodiv.style.position = "absolute";
		//miodiv.style.visibility = "hidden";
		miodiv.style.display = "none";
		resetdefault();
		disegna();
		document.getElementById("btcambiastato").value = "Play";
	}
}

function esamina(ev)
{
	switch(ev.keyCode)
	{
		case LEFTARROW:
			if(direzione=="v" && moved && idtimer!=0)
			{
				incremento = -1;
				direzione = "h";
				moved = false;
			}
			break;
		case UPARROW:
			if(direzione=="h" && moved && idtimer!=0)
			{
				incremento = -1;
				direzione = "v";
				moved = false;
			}
			break;
		case RIGHTARROW:
			if(direzione=="v" && moved && idtimer!=0)
			{
				incremento = 1;
				direzione = "h";
				moved = false;
			}
			break;
		case DOWNARROW:
			if(direzione=="h" && moved && idtimer!=0)
			{
				incremento = 1;
				direzione = "v";
				moved = false;
			}
			break;
		case PAUSE:
			cambiastato();
			break;
	}
}