var browserName = navigator.appName;

window.flickerFree = true;

var keyForRight = "F";
var keyForLeft = "S";
var keyForFire = " ";

var shiftRowsIntervalValue = 6000;
var anym = 300;

var action_type = 1;	//Determina il tipo di azione nel gioco

var gameState = 1;	//Controllare Gestita da due funzioni...

var min_ball = 2;

var score = 0;

var n_balls = 3;		//numero sfere

var n_id_balls = 4;

var s;

var scatta = 1;

N_IMG=12;
var myimages = new Array(N_IMG);
for(i=0; i<N_IMG; i++) myimages[i] = new Image();

	myimages[0].src = "images/pl_0.gif";
	myimages[1].src = "images/pl_1.gif";
	myimages[2].src = "images/pl_2.gif";
	myimages[3].src = "images/pl_3.gif";

	myimages[4].src = "images/q_0.gif";
	myimages[4].name = "0";
	myimages[5].src = "images/q_1.gif";
	myimages[5].name = "1";
	myimages[6].src = "images/q_2.gif";
	myimages[6].name = "2";
	myimages[7].src = "images/q_3.gif";
	myimages[7].name = "3";

	myimages[8].src = "images/q_0.gif";  //name=0 rende le palline "neutre"
	myimages[8].name = "0";
	myimages[9].src = "images/r_1.gif";
	myimages[9].name = "0";
	myimages[10].src = "images/r_2.gif";
	myimages[10].name = "0";
	myimages[11].src = "images/r_3.gif";
	myimages[11].name = "0";


function startGame() {
	changeButton();
	moveRows();

	if(browserName == "Microsoft Internet Explorer")
		document.onkeydown = captureKey;
	else {
		document.captureEvents(Event.KEYPRESS);
		document.onkeypress = captureKey;
	}
	setInterval("playGame()", shiftRowsIntervalValue);
	//setInterval("animation()", anym);
}


function playGame() {

	if (gameState == 1)
		gameState = moveRows();
	else {					//fine del gioco
		//window.alert ("GAME OVER! hai totalizzato " + score + " punti!");
		if (scatta) {
		scatta = 0;
		clearInterval(s);
		//location.reload();
		insertP();
		}
	}
}


function captureKey(e) {

	var t;
	if(browserName == "Microsoft Internet Explorer")
		t = window.event.keyCode;
	else
		t = e.which;
	var s = String.fromCharCode(t).toUpperCase();
	var direction = (s == keyForRight.toUpperCase())?"right":(s == keyForLeft.toUpperCase())?"left":null;
	if(direction != null) {
		movePlayer(direction);
		return;
	}
	if(s == keyForFire.toUpperCase())
		action();
}

function countRows(tableId) {

	var currentCellId = tableId + "r0c0";
	var currentCell = document.getElementById(currentCellId);
	if(currentCell == null)
		return 0;
	var i = 1;
	while(currentCell != null) {
		currentCellId = tableId + "r" + i + "c0";
		currentCell = document.getElementById(currentCellId);
		i++;
	}
	return (i - 1);

}

function countColumns(tableId) {

	var currentCellId = tableId + "r0c0";
	var currentCell = document.getElementById(currentCellId);
	if(currentCell == null)
		return 0;
	var i = 1;
	while(currentCell != null) {
		currentCellId = tableId + "r0" + "c" + i;
		currentCell = document.getElementById(currentCellId);
		i++;
	}
	return (i - 1);

}

function movePlayer(direction) {

	var select_col = new Array();
	var select_n_col = new Array();
	var i;

	for(i=0; i<countColumns("t2"); i++) {
		select_col = document.getElementById("t2r0c" + i);
		if(select_col.childNodes[0].style.visibility == "visible")
			break;
	}
	if((i == 0) && (direction == "left"))
		return;
	if((i == countColumns("t2") - 1) && (direction == "right"))
		return;
		
	select_col.childNodes[0].style.visibility = "hidden";
	select_n_col = document.getElementById("t2r0c" + ((direction == "left")?(i - 1):(i + 1)));
	select_n_col.childNodes[0].style.visibility = "visible";
}


function action() {

	if (action_type) {
		action_type = getBall ();
	}
	else {
		action_type = putBall ();
	}

}


function randomNumber () {

	var random;
	random = Math.round(Math.random()*3) + n_id_balls;
	return random;
}


function insertNewRow () {

	var currentCellId;
	var currentCell;
	var n_col = countColumns("t1") - 1 ;
	var ran;
	for (i=0; i<= n_col; i++) {
		ran = randomNumber();
		currentCellId = "t1r0c"+ i;
		currentCell = document.getElementById(currentCellId).childNodes[0];
		currentCell.src = myimages[ran].src;
		currentCell.name = myimages[ran].name;
	}

}


function moveRows () {

	var currentCellId;
	var currentCell;
	var newCellId;
	var newCell;
	var k;
	var j;
	
	for(var i=countRows("t1") - 2; i>=0; i--) {
		k= i+1;
		for(var j=0; j<countColumns("t1"); j++) {
			currentCellId = "t1r" + i + "c" + j;
			newCellId = "t1r" + k + "c" + j;
			currentCell = document.getElementById(currentCellId).childNodes[0];
			newCell = document.getElementById(newCellId).childNodes[0];
			//window.alert(currentCell.src.subtring());
			
			//if (currentCell.name == 0)
			//	newCell.src = myimages[4].src;
			//else newCell.src = currentCell.src;
			
			newCell.src = currentCell.src;
			newCell.name = currentCell.name;
		}
	}
	insertNewRow();
	gameState = gameOver();
	return gameState;
}


function playerPosition () {

	var select_col = new Array();
	var select_n_col = new Array();
	var i;

	for(i=0; i<countColumns("t2"); i++) {
		select_col = document.getElementById("t2r0c" + i);
		if(select_col.childNodes[0].style.visibility == "visible")
			break;
	}
	return i;
}


function getBall () {

	var currentCellId;
	var currentCell;
	var playerCellId;
	var playerCell;
	var pos;
	var n_image;
	
	pos = playerPosition ();
	
	
	for(var i=countRows("t1") - 1; i>=0; i--) {
		
		currentCellId = "t1r" + i + "c" + pos;	
		currentCell = document.getElementById(currentCellId).childNodes[0];
		n_image = currentCell.name;		
		if (n_image == 0)
			continue;
		else {
		

			for (var i=0; i<=countRows("t1"); i++) {
			currentCell.src = myimages[4].src;
			currentCell.name = myimages[4].name;
			playerCellId = "t2r0" + "c" + i;
			playerCell = document.getElementById(playerCellId).childNodes[0];
			playerCell.src = "images/pl_" + n_image + ".gif";
			playerCell.name = n_image;
			}
		return 0;	
		}
	}
	return 1;
}


function putBall () {

	var currentCellId;
	var currentCell;
	var playerCellId;
	var playerCell;
	var pos;
	var n_image;
	var n_player_image;
	var k;
	
	pos = playerPosition ();
	
	for(var i=countRows("t1") - 1; i>=0; i--) {
		
		playerCellId = "t2r0" + "c" + pos;
		playerCell = document.getElementById(playerCellId).childNodes[0];
		currentCellId = "t1r" + i + "c" + pos;	
		currentCell = document.getElementById(currentCellId).childNodes[0];
		n_image = currentCell.name;

		
		if ((n_image == 0) && (i!=0)) {	
			continue;
		}
		else {
			k = i+1;
			if ((n_image == 0) && (i==0)) {
				k = 0;
			}
			
			currentCellId = "t1r" + k + "c" + pos;
			currentCell = document.getElementById(currentCellId).childNodes[0];
			n_player_image = n_id_balls + Number(playerCell.name);
			currentCell.src = myimages[n_player_image].src;
			currentCell.name = myimages[n_player_image].name;
			for (var i=0; i<=countRows("t1"); i++) {
				playerCellId = "t2r0" + "c" + i;
				playerCell = document.getElementById(playerCellId).childNodes[0];
				playerCell.src = "images/pl_0.gif";
			}
			removeElement(current_row=k, current_column=pos, balltype=Number(currentCell.name), currentCellId);
			return 1;		
		} 
	} 
	return 0;
}


function gameOver () {

	var currentCellId;
	var currentCell;
	var n_rows = countRows("t1") - 1;
	for(var i=0;  i<countColumns("t1"); i++) {
		currentCellId = "t1r" + n_rows + "c" + i;
		currentCell = document.getElementById(currentCellId).childNodes[0];
		if(Number(currentCell.name)) {
			//window.alert ("GAME OVER! hai totalizzato " + score + " punti!");
			clearInterval();
			setInterval("playGame()", 1);
			return 0;
		}
	
	}
	return 1;
}


function removeElement(row, column, balltype, currentCellId) {
	
	var ball_animation= 8 + balltype;
	var total_count=0;				//contatore delle sfere distrutte
	total_count = removeUpElement(row, column, balltype, currentCellId);
	if  (total_count == null) 
		total_count = 0;
	
	element_to_remove = new Array (currentCellId);
	
	if (column !=0) {				//controllo a sinistra;
		for (var i=column -1; i>=0; i--) {
			currentCellId = "t1r" + row + "c" + i;
			currentCell = document.getElementById(currentCellId).childNodes[0];
			if (currentCell.name != balltype)
				break;
			element_to_remove.push(currentCellId);
		}
	}
	
	var k = countColumns("t1") - 1;
	if (column !=k) {				//controllo a destra;
		for (var i=column +1; i<=k; i++) {
			currentCellId = "t1r" + row + "c" + i;
			currentCell = document.getElementById(currentCellId).childNodes[0];
			if (currentCell.name != balltype)
				break;
			element_to_remove.push(currentCellId);
		}
	}
	
	var n_el= element_to_remove.length;
	if (n_el> min_ball) {
		for (var i=0; i<n_el; i++) {
			var cellId = element_to_remove [i];
			var cell = document.getElementById(cellId).childNodes[0];
			cell.src = myimages[ball_animation].src;
			cell.name = myimages[ball_animation].name;
		}
	total_count = total_count + n_el;		// totale delle sfere distrutte
	
	}
	if (total_count > 1) {
		countScore (total_count);
	}
	setTimeout("animation()", anym);
}

function animation () {

	for(var i=countRows("t1") - 2; i>=0; i--) {	
		for(var j=0; j<countColumns("t1"); j++) {
			currentCellId = "t1r" + i + "c" + j;
			newCellId = "t1r" + i + "c" + j;
			currentCell = document.getElementById(currentCellId).childNodes[0];
			newCell = document.getElementById(newCellId).childNodes[0];
			//window.alert(currentCell.src.subtring());
			
			if (currentCell.name == 0)
				newCell.src = myimages[4].src;
			else newCell.src = currentCell.src;
		}
	}
}

function removeUpElement(row, column, balltype, currentCellId) {

	var ball_animation= 8 + balltype;
	var count = 0;
	if (Number(row) > 1 ) {
		
		
		for (i=row-1; i>=0; i--) {		
			var f_upCellId = "t1r" + i + "c" + column;
			f_upCell = document.getElementById(f_upCellId).childNodes[0];		
			if (f_upCell.name != balltype)
				break;
			else count +=1;
		}
		if (count >= min_ball ){
			for (var i=count; i>=0; i--) {
				var n_elem = row - i;
				cellId = "t1r" + n_elem + "c" + column;
				var cell = document.getElementById(cellId).childNodes[0];
				cell.src = myimages[ball_animation].src;
				cell.name = myimages[ball_animation].name;
	
			}
		return count + 1;		//palle distrutte verso l'alto
		}
	}
}


function countScore (points) {
	
	if (points >=6)
		score += points * 20;
	else  if (points >=4)
		score += points * 10;
	else
		score += points * 5;
	newscore = document.createTextNode (String(score));

	cell = document.getElementById("scoreId").firstChild;	
	
	
	if(browserName == "Microsoft Internet Explorer") {
		cell.removeNode(false);
	}
	else {
		cell.parentNode.removeChild(cell);
	}
	newCell = document.getElementById("scoreId");
	newCell.appendChild(newscore);
}


function exitFromGame() {

	var userChoice = window.confirm("Vuoi terminare la partita?");
		if(userChoice == true)
			location.reload();
}


function changeButton() {
	
	var startButtonDiv = document.getElementById("buttonId").parentNode;
	if(browserName == "Microsoft Internet Explorer")
		while(startButtonDiv.hasChildNodes() == true)
			startButtonDiv.lastChild.removeNode(false);
	else
		while(startButtonDiv.hasChildNodes() == true)
			startButtonDiv.removeChild(startButtonDiv.lastChild);
			
	cell = document.createElement("button");
	c_text = document.createTextNode ("Termina la partita");
	cell.appendChild (c_text);
	startButtonDiv.appendChild(cell);
	cell.onclick = exitFromGame;
}

function insertP() {

	user_name = window.prompt("Inserisci il tuo nome!");
	document.forms[0].elements[0].value = user_name;
	document.forms[0].elements[1].value = score;
	document.forms[0].submit();
	
}

function visClass() {

	document.forms[0].elements[0].value = "a";
	document.forms[0].elements[1].value = -1;
	document.forms[0].submit();
	
}

