var BASE_URL = ''; // "http://www.example.com/folder/"
var BASE_IMG = 'images'; // "http://www.example.com/folder/images"

var letter = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' ];
var numeri = { a: 0, b: 1, c: 2, d: 3, e: 4, f: 5, g: 6, h: 7 };
var ptToId = 
{
		p: 'b_pedone_0', n: 'b_cavallo', b: 'b_alfiere', r: 'b_torre', q: 'b_regina', k: 'b_re',
		P: 'pedone_0', N: 'cavallo', B: 'alfiere', R: 'torre', Q: 'regina', K: 're'		
};
var clr = ['#fff', '#ccc'];
var scacco_matto = false;
var turno = 0;
var caselle = [];
var col_cas = [];
var droppables;
var loader;
var valide;
var ima_B = ima_W = new Array();
var last_black_move = "";
var en_passant = "";
var hint = "";
Trascina = {
	P: false, N: false, B: true, R: true, Q: true, K: false
};
// Numero delle direzioni in cui un pezzo puo' muovere
NumeroDirezioni = {
	P: 0, N: 8, B: 4, R: 4, Q: 8, K: 8
};
// Direzioni dei vari pezzi in una matrice 10*12 (vedi matrice Da12A8[])
OffsetPezzi = {
	P:[   0,   0,   0,  0, 0,  0,  0,  0 ],
	N:[ -21, -19, -12, -8, 8, 12, 19, 21 ],
	B:[ -11,  -9,   9, 11, 0,  0,  0,  0 ],
	R:[ -10,  -1,   1, 10, 0,  0,  0,  0 ],
	Q:[ -11, -10,  -9, -1, 1,  9, 10, 11 ],
	K:[ -11, -10,  -9, -1, 1,  9, 10, 11 ]
};
/* Da12A8[] e' una matrice 10*12 utilizzata per verificare la legalita' 
   delle mosse. E' ottenuta aggiungendo ad una matrice 8*8 una 
   colonna per lato e due righe superiori ed inferiori con valori pari a -1,
   che semplificano il test di mosse che cadono al di fuori della scacchiera. */
Da12A8 = [
	 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	 -1,  0,  1,  2,  3,  4,  5,  6,  7, -1,
	 -1,  8,  9, 10, 11, 12, 13, 14, 15, -1,
	 -1, 16, 17, 18, 19, 20, 21, 22, 23, -1,
	 -1, 24, 25, 26, 27, 28, 29, 30, 31, -1,
	 -1, 32, 33, 34, 35, 36, 37, 38, 39, -1,
	 -1, 40, 41, 42, 43, 44, 45, 46, 47, -1,
	 -1, 48, 49, 50, 51, 52, 53, 54, 55, -1,
	 -1, 56, 57, 58, 59, 60, 61, 62, 63, -1,
	 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
];
// Per ogni casa della scacchiera 8*8, la matrice Da8A12[] fornisce 
// l'indice della corrispondente casa nella matrice 10*12 Da12A8[].
Da8A12 = [
	21, 22, 23, 24, 25, 26, 27, 28,
	31, 32, 33, 34, 35, 36, 37, 38,
	41, 42, 43, 44, 45, 46, 47, 48,
	51, 52, 53, 54, 55, 56, 57, 58,
	61, 62, 63, 64, 65, 66, 67, 68,
	71, 72, 73, 74, 75, 76, 77, 78,
	81, 82, 83, 84, 85, 86, 87, 88,
	91, 92, 93, 94, 95, 96, 97, 98
];		

function inject_from_null()
{
	var w = (window.ie ? document.body.offsetWidth : window.innerWidth);
	var h = (window.ie ? document.body.offsetHeight : window.innerHeight);

	scuro = new Element("div")
			.setStyles({'width': '100%', 'height': h, 'position': 'absolute', 'top': 0, 'left': 0, 
						'z-index': 2, 'overflow': 'hidden', 'background-color': '#000', 'opacity': 0.8 });
	scuro.injectInside(document.body);
	old_style_body = document.body.getStyle('overflow');
	document.body.setStyles({'overflow': 'hidden'});
	
	ajc = new Element("div")
			.setStyles({'width': 640, 'height': 480, 'position': 'absolute', 'top': (h/2)-240, 
						'left': (w/2)-320, 'background-color': '#fff', 'padding': 5, 'z-index': 3 , 'opacity': 1});
	ajc.injectAfter(scuro);
	
	ajc_main = new Element("div")
			.setStyles({'width': 615, 'height': 450, 'float': 'left', 'position': 'relative'});
	ajc_main.injectInside(ajc);

	close_lnk = new Element("div")
			.setStyles({'width': 66, 'height': 22, 'float': 'right', 'position': 'relative'});
	close_lnk.setHTML("<a href='#' onclick='close_all()'><img src='"+BASE_IMG+"/closelabel.gif' border='0' /></a>");
	close_lnk.injectInside(ajc);
	
	inject_base(ajc_main);
	
	var drag = ajc.makeDraggable();

}
function close_all()
{
	document.body.setStyles({'overflow': old_style_body});
	ajc.remove();
	scuro.remove();
}

//////////////////////////////////////////////////
//                Disegna i div                 //
//////////////////////////////////////////////////
function inject_base(cont)
{
	var dest = $(cont);
	//Log
	div = new Element("div", {'class': 'fondo'})
			.setStyles({'float': 'left', 'width': 102, 'height': 450, 'position': 'relative', 'font': '11px verdana', 'overflow': 'auto'});
	div.setHTML("<b>Log Partita:</b><br />");
	div.id = "log";
	div.injectInside(dest);	

	//Barra dei messaggi
	div = new Element("div", {'class': 'fondo'})
			.setStyles({'float': 'left', 'width': 475, 'height': 20, 'position': 'relative', 'font': '14px verdana', 'background-color': '#fff', 'border': '1px dashed #ccc', 'text-align': 'center', 'vertical-align': 'middle'});
	div.id = "messaggi";
	div.injectInside(dest);	

	//Mostra Informazioni
	div = new Element("div", {'class': 'fondo'})
			.setStyles({'float': 'right', 'width': 27, 'height': 26, 'position': 'relative'});
	div.setHTML("<input type=\"button\" onclick=\"show_about();\" value=\"?\" />");
	div.injectInside(dest);	

	//Scacchiera
	div = new Element("div", {'class': 'fondo'})
			.setStyles({'float': 'left', 'width': 402, 'height': 402, 'position': 'relative', 'border': '1px solid black'});
	div.id = "fondo";
	div.injectInside(dest);	

	//Garbage black&white
	div = new Element("div", {'class': 'fondo'})
			.setStyles({'float': 'right', 'width': 102, 'height': 200, 'position': 'relative', 'background-color': '#bbb'});
	div.id = "gnam_b";
	div.injectInside(dest);
	div = new Element("div", {'class': 'fondo'})
			.setStyles({'float': 'right', 'width': 102, 'height': 200, 'position': 'relative', 'background-color': '#eee'});
	div.id = "gnam_w";
	div.injectInside(dest);	

	//Options
	div = new Element("div", {'class': 'fondo'})
			.setStyles({'float': 'left', 'width': 502, 'height': 25, 'position': 'relative'});
	div.id = "opt";
	div.setHTML('<input type="button" id="new_game" onclick="reboot();" value="Nuova Partita"> : <span id="gname" style="font: 10px verdana;" title="Inserisci questo id nel prossimo campo per caricare la partita successivamente."></span> : <input type="text" id="to_load" size="7"> <input type="button" onclick="load_game();" value="Carica"> : <span style="font: 10px verdana;" title="Tempo di risposta massimo del PC">Tempo:</span> <select id="time_to_think"><option value="1">1s</option><option value="2">2s</option><option value="3" SELECTED>3s</option><option value="4">4s</option><option value="5">5s</option>');	
	div.injectInside(dest);

	//About
	div = new Element("div", {'class': 'fondo'})
			.setStyles({'width': 320, 'height': 240, 'position': 'absolute', 'left': 160, 'top': 120, 'display': 'none',
						'background-color': '#fff', 'border': '1px solid black', 'padding': 5, 'font': '12px Verdana'});
	div.id = "about_pop";
	div.setHTML('<div style="float: right"><a href="#" onclick="show_about();"><img src="'+BASE_IMG+'/closelabel.gif" border="0" /></a></div><span style="font: 16px Verdana;"><b>AjaxChess</b></span><br /><i>Versione:</i> 1.0<br /><p>Un progetto di <b>CereS</b><br />Scritto in Javascript utilizzando <a href="http://www.mootools.com" target="_blank">mooTools</a></p><p>Motore di gioco: gnuchess 5.07<br />Wrapper: phpChess (by CereS) 1.0</p><p style="font: 10px Sans-Serif;">This script is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.<br />Visita <a href="http://ceres.divxmania.it" target="_blank">ceres.divxmania.it</a> per informazioni.');
	div.injectInside(dest);		
	
	avvia();	
}

function show_about()
{
	var ab = $('about_pop');
	if (ab.getStyle('display') == 'block')
		ab.setStyle('display', 'none');
	else
		ab.setStyle('display', 'block');
}

//////////////////////////////////////////////////
//                   Start up                   //
//////////////////////////////////////////////////
function avvia()
{
	garb_b = $('gnam_b');
	garb_w = $('gnam_w');
	board = $('fondo');
	logger = $('log');
	msg_board = $('messaggi');
	baseX = board.getLeft()*2;
	baseY = board.getTop()*2;

	draw_pieces(board);
	droppables = $$('div.pos');
	loader = $('loader');
	draw_base();
	get_id();
	your_turn = true;
	scacco_matto = false;	
	my_alert("La Taverna ti augura Buona Partita!");
}
//////////////////////////////////////////////////
//                Nuova partita                 //
//////////////////////////////////////////////////
function reboot()
{
	garb_b.empty();
	garb_w.empty();
	board.empty();
	logger.innerHTML = "<b>Log Partita:</b><br />";
	turno = 0;
	caselle = [];
	col_cas = [];
	droppables = "";
	avvia();
}

//////////////////////////////////////////////////
//          Carica una partita salvata          //
//////////////////////////////////////////////////
function load_game()
{
	var id = $('to_load').value;
	if (id == "" || !id || id == fname || id.length != 7)
		return;
	loader.style.display = 'block';
	myAjax = new Ajax(
				BASE_URL+'chess.php', 
				{
					method: 'get', 
					onComplete: function(request)
								{
									risposta = request.split("|");
									if (risposta[0] == "404")
									{
										//Errore!
										my_alert("Errore! La partita non esiste o non è recuperabile");
										loader.style.display = 'none';
										return;
									}
									else if(risposta[0] == "200")
									{
										//Tutto bene
										logger.innerHTML = "<b>Log Partita:</b><br />";
										logger.innerHTML += risposta[2];
										garb_b.empty();
										garb_w.empty();
										board.empty();
										t=risposta[2].split(".");
										tt = t[t.length-2].split(">");
										turno = tt[1].toInt() + 1;
										scacco_matto = false;
										caselle = [];
										col_cas = [];
										droppables = "";
										draw_pieces(board);
										droppables = $$('div.pos');
										loader = $('loader');
										draw_base();
										move_load(risposta[1]);
										your_turn = true;
										my_alert("Partita Caricata!!!");
										fname = id;
										$('gname').innerHTML = "<b>Game ID:</b>   "+fname;
										loader.style.display = 'none';
										return;
									}
									else
									{
										//Boh, qualcosa non va, generico stop
										my_alert("Il server è ubriaco, riprova più tardi.");
										loader.style.display = 'none';
										return;
									}
										
								}
				}
				).request({loadID: id});	

}

function move_load(strb)
{
	//srtb = r.....k.pp..Bpbp......p......b...............NP..PK.Pn.P.....B.R
	pN = 1;
	PN = 1;
	moved = new Array();
	for(i=0; i<64; i++)
	{
		to = caselle[i];
		pt = strb.substr(i,1);
		if (pt != ".")
		{
			ptID = ptToId[pt];
			if( moved.contains(ptID) && pt != "p" && pt != "P" )
			{ 
				ptID += "_";
			}
			else if( moved.contains(ptID) )
			{
				 ptID = (pt == "p" ? "b_" : "" ) + "pedone_" + (pt == "p" ? pN : PN);
				 (pt == "p" ? pN++ : PN++);
			}
			new Fx.Styles($(ptID), {duration: 250,transition: Fx.Transitions.linear})
			.start({
				'top'  : (8-to.substr(1,1).toInt()) * 50,
				'left' : numeri[to.substr(0,1)].toInt() * 50
			});
			moved.include(ptID);
		}
	}
	$$('div.pezzo').each(function (div)
	{
		if(!moved.contains(div.id))
			eat_piece(div.id);	
	});
	
}

//////////////////////////////////////////////////
//             Disegna la scacchiera            //
//////////////////////////////////////////////////
function draw_pieces(container)
{
	cc = 0;
	for (y = 0; y < 8; y++)
	{
		for (x = 0; x < 8; x++)
		{
			div = new Element("div", {'class': 'pos'})
					.setStyles({'width': 50, 'height': 50, 
								'background-color': clr[cc], 'position': 'absolute',
								'left': x*50, 'top': y*50
					});
			div.id = letter[x] + (8-y);
			div.title = div.id;
			div.injectInside(container);
			caselle.include(letter[x] + (8-y));
			col_cas[letter[x] + (8-y)] = clr[cc];
			cc = (cc == 1 ? 0 : 1);
		}
		cc = (cc == 1 ? 0 : 1);
	}
	div = new Element("div", {'class': 'loader'})
			.setStyles({'width': 32, 'height': 32, 'position': 'absolute', 'left': 184, 'top': 184, 'z-index': 1001});
	div.setHTML("<img src='"+BASE_IMG+"/loading.gif' />");
	div.id = "loader";
	div.title = "Loading...";
	div.injectInside(container);
}

//////////////////////////////////////////////////
//              Disegna gli scacchi             //
//////////////////////////////////////////////////
function draw_base()
{
	imgs = [BASE_IMG+'/wr.png',BASE_IMG+'/wn.png',BASE_IMG+'/wb.png',BASE_IMG+'/wq.png',
		BASE_IMG+'/wk.png',BASE_IMG+'/wb.png',BASE_IMG+'/wn.png',BASE_IMG+'/wr.png', BASE_IMG+'/wp.png'];
	imgs_b = [BASE_IMG+'/br.png',BASE_IMG+'/bn.png',BASE_IMG+'/bb.png',BASE_IMG+'/bq.png',
		BASE_IMG+'/bk.png',BASE_IMG+'/bb.png',BASE_IMG+'/bn.png',BASE_IMG+'/br.png', BASE_IMG+'/bp.png'];

	/***************************************
	*      Disegna gli scacchi neri        *
	***************************************/
	pezzi = ['b_torre', 'b_cavallo', 'b_alfiere', 'b_regina', 'b_re', 'b_alfiere_', 'b_cavallo_', 'b_torre_'];
	ima_B = imgs_b.associate(pezzi);
	for (w = 0; w<16; w++)
	{
		name = (w<8 ? 'b_pedone_'+w : pezzi[w-8]);
		px = (w<8 ? w*50 : (w-8)*50);
		py = (w<8 ? 50 : 0);
		ima = (w<8 ? imgs_b[8] : imgs_b[w-8]);
		pezzo = new Element("div", {'class': 'pezzo'})
				.setStyles({'width': 50, 'height': 50, 'left': px, 'top': py, 'position': 'absolute'})
				.setStyle('background', 'url('+ima+')');

		pezzo.id = name;
		pezzo.injectInside(board); 
		set_movable_null(pezzo);
	}

	/***************************************
	*     Disegna gli scacchi bianchi      *
	***************************************/
	pezzi = ['torre', 'cavallo', 'alfiere', 'regina', 're', 'alfiere_', 'cavallo_', 'torre_'];
	ima_W = imgs.associate(pezzi);	
	for (w = 0; w<16; w++)
	{
		name = (w<8 ? 'pedone_'+w : pezzi[w-8]);
		px = (w<8 ? w*50 : (w-8)*50);
		py = (w<8 ? 300 : 350);
		ima = (w<8 ? imgs[8] : imgs[w-8]);
	
		pezzo = new Element("div", {'class': 'pezzo'})
				.setStyles({'width': 50, 'height': 50, 'left': px, 'top': py, 'position': 'absolute'})
				.setStyle('background', 'url('+ima+')');
		
		pezzo.id = name;
		pezzo.injectInside(board); 
		set_movable(pezzo);
	} 
}
//////////////////////////////////////////////////
//              Scrive un messaggio             //
//////////////////////////////////////////////////
function my_alert(mes)
{
	msg_board.setHTML("<b>"+mes+"</b>");
	bfx = new Fx.Styles(msg_board, {duration: 500,transition: Fx.Transitions.linear});
	to0 = '#ffcccc';
	to1 = '#ccffcc';
	to2 = '#ccccff';
	from0 = msg_board.getStyle("background-color");
	bfx.start({'background-color'  : to0})
	.chain(function(){this.start({'background-color'  : to1}) })
	.chain(function(){this.start({'background-color'  : to2}) })
	.chain(function(){this.start({'background-color'  : from0}) });		
}
//////////////////////////////////////////////////
//                Muove un pezzo                //
//////////////////////////////////////////////////
function move_piece(el, pos)
{
	if($(el).id.indexOf("pedone") > -1)
		attento_ep = true;
	else
		attento_ep = false;

	$$('div.pezzo').each(function (div)
	{
		pt = Math.round(div.getStyle('top').toInt()/50);
		pl = Math.round(div.getStyle('left').toInt()/50);
		posPezzo = letter[pl] + (8-(pt));
		//Si deve mangiare?
		if( posPezzo == pos )
		{
			to_eat = div.id;
			eat_piece(to_eat);
			return;
		}
		if( attento_ep == true && div.id.indexOf("b_pedone") > -1 )
		{
			if( letter[pl] == pos.substr(0,1) && pos.substr(1,1).toInt()-1 == 6 && (8-(pt)) == 5 )
			{
				en_passant = false;
				to_eat = div.id;
				eat_piece(to_eat);
				return;				
			}
		}
	});

	var fx = new Fx.Styles(el, {duration: 250,transition: Fx.Transitions.linear});
	fx.start({
		'top'  : (8-pos.substr(1,1).toInt()) * 50,
		'left' : numeri[pos.substr(0,1)].toInt() * 50
	});
	return fx;
}
//////////////////////////////////////////////////
//              Promuove un pezzo               //
//////////////////////////////////////////////////
function promote(el, cl)
{
	var to = ptToId[cl];
	//preso_id . b_preso_id
	var parti = to.split("_");
	
	if(parti[0] == "b")
	{
		var chk = "b_preso_"+parti[1];
		var im = ima_B[to];
	}
	else
	{
		var chk = "preso_"+parti[1];
		var im = ima_W[to];		
	}
	//Al posto di aggiungere prendo dal garbage...
	if( $(chk))
	{
		var pezzo = $(chk);
		if(pezzo.innerHTML == "")
			pezzo.remove();
		else
			pezzo.innerHTML = "";
	}

	if( $(to) ) to += "_";
	if( $(to) ) to += "1";

	pezzo = $(el);
	pezzo.id = to;
	pezzo.setStyle('background', 'url('+im+')');
}


//////////////////////////////////////////////////
//              Stiamo arroccando?              //
//////////////////////////////////////////////////
function arrocco(el, pos)
{
	id = $(el).id;
	if (id == "re")
	{
		if(pos == "a1")
			return "O-O-O";
		if(pos == "h1")
			return "O-O";
		return false;
	}
	else
	{
		return false;
	}
}

//////////////////////////////////////////////////
//              Aggiorna il log                 //
//////////////////////////////////////////////////
function log_mossa(white, black)
{
	att = logger.innerHTML;
	b = black.split("|");
	turno++;
	if (b[0] == "WON")
	{
		add = att + turno + ". " + white.replace("K", "&#9812;").replace("Q", "&#9813;").replace("R", "&#9814;")
			.replace("B", "&#9815;").replace("N", "&#9816;") + "#" + "<br />";
		return;
	}
	if (b[0] == "DRAW")
	{
		add = att + turno + ". PATTA<br />";
		return;		
	}
	add = att + turno + ". " + white.replace("K", "&#9812;").replace("Q", "&#9813;").replace("R", "&#9814;")
			.replace("B", "&#9815;").replace("N", "&#9816;") + "\t" + b[1].replace("K", "&#9818;").replace("Q", "&#9819;")
			.replace("R", "&#9820;").replace("B", "&#9821;").replace("N", "&#9822;") + "<br />";
	logger.setHTML(add);
	hint = b[2];
}

//////////////////////////////////////////////////
//            Mostra un suggerimento            //
//////////////////////////////////////////////////
function show_hint()
{
	if( hint == "" )
	{
		my_alert("Ancora prima di iniziare???");
		return;
	}
	if( hint != "Non saprei..." )
		my_alert("Prova: <b>"+hint+"</b>");
	else
		my_alert("Nessun aiuto disponibile al momento");
}


//////////////////////////////////////////////////
//    Genera la mossa in notazione algebrica    //
//////////////////////////////////////////////////
function ari_mossa(pezzo, mossa)
{
	pte = $(pezzo);
	parti = pte.id.split("_");
	from = mossa.substr(0,2);
	to = mossa.substr(2,2);
	add = "";	

	nota = {pedone:'', cavallo:'N', alfiere:'B', torre:'R', regina:'Q', re:'K'};

	if (parti[0] == "b")
		clid = nota[parti[1]];
	else
		clid = nota[parti[0]];

	if(clid != "" && clid != "Q" && clid != "K")
	{
		//var legali = compute_legal(clid, mossa);	
		var pezzo1 = $(parti[0]);
		var pezzo2 = $(parti[0]+"_");
		if(pezzo1 && pezzo2)
		{
			pt1 = Math.round(pezzo1.getStyle('top').toInt()/50);
			pl1 = Math.round(pezzo1.getStyle('left').toInt()/50);
			post1 = letter[pl1] + (8-(pt1));
			pt2 = Math.round(pezzo2.getStyle('top').toInt()/50);
			pl2 = Math.round(pezzo2.getStyle('left').toInt()/50);
			post2 = letter[pl2] + (8-(pt2));
			
			diff = false;

			legal1 = compute_legal(clid, post1);
			legal2 = compute_legal(clid, post2);
			legal1.each(function(id){
				if( legal2.contains(id) && id == to )
					diff = true;
			});
			
			if (diff == true)
				add = (pl1 == pl2 ? mossa.substr(1,1) : mossa.substr(0,1));
		}
	}
	//Promozione
	if(clid == "" && to.substr(1,1) == "8")
	{
		//Long stoy short... Uno promuove SEMPRE a donna!
		to += "=Q";
	}
	
	if (vuoto(to) == false)
	{
		if (clid == "")
			return from.substr(0,1)+"x"+to;
		else
			return clid+add+"x"+to;
	}
	else
	{
		return clid+add+to;
	}

}

//////////////////////////////////////////////////
//Fa lampeggiare tutte le possibili destinazioni//
//////////////////////////////////////////////////
function highlight_possibles(pos)
{
	$$('div.pezzo').each(function (div)
	{
		pt = Math.round(div.getStyle('top').toInt()/50);
		pl = Math.round(div.getStyle('left').toInt()/50);
		posPezzo = letter[pl] + (8-(pt));
		if( posPezzo == pos)
		{
			pts = div.id;
		}
	});	
	pte = $(pts);
	parti = pte.id.split("_");
	nota = {pedone:'', cavallo:'N', alfiere:'B', torre:'R', regina:'Q', re:'K'};
	if (parti[0] == "b")
		clid = nota[parti[1]];
	else
		clid = nota[parti[0]];	
	valide = compute_legal(clid, pos);
	valide.each(function(id){
		var sq = $(id);
		var from = col_cas[sq.id];
		var to = '#ccccff';
		var hiFX = new Fx.Styles(sq, {duration: 250,transition: Fx.Transitions.linear});
		hiFX.start({'background-color'  : to})
		.chain(function(){this.start({'background-color'  : from}) });		
		
	});
}

//////////////////////////////////////////////////
// Genera la lista delle mosse valide del pezzo //
//////////////////////////////////////////////////
function compute_legal(el, mossa)
{
	from_x = numeri[mossa.substr(0,1)];
	from_y = mossa.substr(1,1).toInt();
    CasaCorrente = ((8-from_y)*8 + from_x);
	valid = new Array();
	if (el == '')
	{
		//Pedone
		if (from_y != 8 && vuoto(letter[from_x]+(from_y+1)) )
		{
			valid.include(letter[from_x]+(from_y+1));
			if (from_y == 2 && vuoto(letter[from_x]+(from_y+2)))
				valid.include(letter[from_x]+(from_y+2));
		}
		if (avversario( letter[from_x-1]+(from_y+1)))
			valid.include(letter[from_x-1]+(from_y+1));			
		if (avversario( letter[from_x+1]+(from_y+1)))
			valid.include(letter[from_x+1]+(from_y+1));
		//En passant?
		if (last_black_move.substr(1,1) == "7" && last_black_move.substr(3,1) == "5" 
			&& from_y == 5 && avversario(last_black_move.substr(2,2), "b_pedone") )
		{
			var last_piu = numeri[last_black_move.substr(0,1)]+1;
			var last_meno = numeri[last_black_move.substr(0,1)]-1;
			if (from_x == last_piu)
			{
				valid.include(letter[last_piu]+6);
			}
			else if (from_x == last_meno)
			{
				valid.include(letter[last_meno]+6);
			}
		}	
	}
	else
	{
		for (Direzione = 0; Direzione < NumeroDirezioni[el]; Direzione++) 
		{
			CasaDestinazione = CasaCorrente;
			while (true) 
			{
				CasaDestinazione = Da12A8[Da8A12[CasaDestinazione] + OffsetPezzi[el][Direzione]];
				if (CasaDestinazione == -1)
					break;
				if ( !vuoto(caselle[CasaDestinazione]) ) 
				{
					if (avversario(caselle[CasaDestinazione]))
						valid.include(caselle[CasaDestinazione]);				
					break;
				}				
				valid.include(caselle[CasaDestinazione]);				
				if (!Trascina[el])
					break;
			}
		}
		if(el == "K")
		{
			if (mossa.substr(0,2) == "e1")
			{
				var t1 = $('torre');
				if(t1)
				{
					pt = Math.round(t1.getStyle('top').toInt()/50);
					pl = Math.round(t1.getStyle('left').toInt()/50);
					post1 = letter[pl] + (8-(pt));
					if( post1 == "a1" && vuoto("b1") && vuoto("c1") && vuoto("d1") )
						valid.include("a1");
				}
				var t2 = $('torre_');
				if(t2)
				{
					pt = Math.round(t2.getStyle('top').toInt()/50);
					pl = Math.round(t2.getStyle('left').toInt()/50);
					post2 = letter[pl] + (8-(pt));
					if( post2 == "h1" && vuoto("f1") && vuoto("g1") )
						valid.include("h1");
				}

			}				
			//Il Re non può andare sotto scacco, quindi devo controllare tutte le posizioni controllate
			//dall'avversario ed escluderle!
			valid_avv = new Array();
			$$('div.pezzo').each(function (div)
			{
				pt = Math.round(div.getStyle('top').toInt()/50);
				pl = Math.round(div.getStyle('left').toInt()/50);
				posPezzo = letter[pl] + (8-(pt));
				pte = div.id;
				parti = pte.split("_");
				nota = {pedone:'', cavallo:'N', alfiere:'B', torre:'R', regina:'Q', re:'K'};
				if (parti[0] == "b")
				{
					clid = nota[parti[1]];
					valid_avv.merge(compute_legal_avv(clid, posPezzo));
				}
			});	
			valid_avv.each(function(rm){
				valid.remove(rm);
			});			
		}
	}
	return valid;	
}

//////////////////////////////////////////////////
// Genera la lista delle mosse valide del pezzo //
//////////////////////////////////////////////////
function compute_legal_avv(el, mossa)
{
	from_x = numeri[mossa.substr(0,1)];
	from_y = mossa.substr(1,1).toInt();
    CasaCorrente = ((8-from_y)*8 + from_x);
	valid_ = new Array();
	if (el == '')
	{
		if (avversario_pc( letter[from_x-1]+(from_y-1)))
			valid_.include(letter[from_x-1]+(from_y-1));			
		if (avversario_pc( letter[from_x+1]+(from_y-1)))
			valid_.include(letter[from_x+1]+(from_y-1));
	}
	else
	{
		for (Direzione = 0; Direzione < NumeroDirezioni[el]; Direzione++) 
		{
			CasaDestinazione = CasaCorrente;
			while (true) 
			{
				CasaDestinazione = Da12A8[Da8A12[CasaDestinazione] + OffsetPezzi[el][Direzione]];
				if (CasaDestinazione == -1)
					break;
				if ( !vuoto(caselle[CasaDestinazione]) ) 
				{
					if (avversario_pc(caselle[CasaDestinazione]))
						valid_.include(caselle[CasaDestinazione]);				
					break;
				}				
				valid_.include(caselle[CasaDestinazione]);				
				if (!Trascina[el])
					break;
			}
		}
	}
	return valid_;
}

//////////////////////////////////////////////////
//   Controlla se una casa è occupata o meno    //
//////////////////////////////////////////////////
function avversario(pos, type)
{
	//avversario('a3')
	//	True SOLO se la casella è OCCUPATA da computer
	//	False se la casella è VUOTA o occupata da me
	//avversario('a3', 'b_re')
	//	True SOLO se la casella è OCCUPATA da uno specifico pezzo
	//	False se la casella è VUOTA o occupata da me

	pres = false;
	if (type)
		target_type = type;
	else
		target_type = false;		
	$$('div.pezzo').each(function (div)
	{
		pt = Math.round(div.getStyle('top').toInt()/50);
		pl = Math.round(div.getStyle('left').toInt()/50);
		posPezzo = letter[pl] + (8-(pt));
		//C'è un pezzo, ed è dell'avversario
		if( target_type == false )
		{
			if( posPezzo == pos && div.id.substr(0,2) == "b_")
			{
				pres = true;
			}
		}
		else
		{
			if( posPezzo == pos && div.id.indexOf(target_type) > -1)
			{
				pres = true;
			}
		}		
	});
	return pres;
}
//////////////////////////////////////////////////
//   Controlla se una casa è occupata o meno    //
//////////////////////////////////////////////////
function avversario_pc(pos, type)
{
	//avversario('a3')
	//	True SOLO se la casella è OCCUPATA da me
	//	False se la casella è VUOTA o occupata da computer
	//avversario('a3', 're')
	//	True SOLO se la casella è OCCUPATA da uno specifico pezzo
	//	False se la casella è VUOTA o occupata da computer

	pres = false;
	if (type)
		target_type = type;
	else
		target_type = false;		
	$$('div.pezzo').each(function (div)
	{
		pt = Math.round(div.getStyle('top').toInt()/50);
		pl = Math.round(div.getStyle('left').toInt()/50);
		posPezzo = letter[pl] + (8-(pt));
		//C'è un pezzo, ed è dell'avversario
		if( target_type == false )
		{
			if( posPezzo == pos && div.id.substr(0,2) != "b_")
			{
				pres = true;
			}
		}
		else
		{
			if( posPezzo == pos && div.id.indexOf(target_type) > -1)
			{
				pres = true;
			}
		}		
	});
	return pres;
}
//////////////////////////////////////////////////
//   Controlla se una casa è occupata o meno    //
//////////////////////////////////////////////////
function vuoto(pos)
{
	//vuoto('a3')
	//	True SOLO se la casella è VUOTA
	//	False se la casella è OCCUPATA
	pres = false;
	$$('div.pezzo').each(function (div)
	{
		pt = Math.round(div.getStyle('top').toInt()/50);
		pl = Math.round(div.getStyle('left').toInt()/50);
		posPezzo = letter[pl] + (8-(pt));
		//C'è un pezzo qualsiasi
		if( posPezzo == pos.substr(0,2))
		{
			pres = true;			
		}
	});
	if(pres == true)
		return false;
	else
		return true;
}

//////////////////////////////////////////////////
//                Mangia un pezzo                //
//////////////////////////////////////////////////
function eat_piece(el)
{
	pte = $(el);
	parti = pte.id.split("_");

	if (parti[0] == "b")
		clid = "b_preso_" + parti[1];
	else
		clid = "preso_" + parti[0];	

	if( $(clid) )
	{
		n = ($(clid).innerHTML == "" ? 1 : $(clid).innerHTML.toInt()) + 1;
		$(clid).setHTML(n);
	}
	else
	{
		var clone = pte.clone()
		.setStyles({'opacity': 0.7, 'position': 'relative', 'float': 'left', 'left':'', 'top':''})
		.removeEvents()
		.removeClass("pezzo");
		clone.id = clid;

		if(pte.id.substr(0,2) != "b_")
			clone.injectInside(garb_b);		
		else
			clone.injectInside(garb_w);	
	}
	pte.remove();
}

//////////////////////////////////////////////////
//            Trova e muove un pezzo            //
//////////////////////////////////////////////////
function find_move(pos)
{
	/****************************************
	*            Abbiamo vinto!!!           *
	****************************************/
	if (pos.split("|")[0] == "WON")
	{
		scacco_matto = true;
		my_alert("Scacco MATTO! Hai vinto, bravo :)");
		$$('div.pezzo').each(function (div)
		{
			if(div.id.substr(0,2) == "b_")
			{
				div.setStyles({'opacity': 0.6});
			}
		});
		alert("Hai vinto, bravo!\n Appena puoi passa in Taverna, ti aspetta una birra offerta!!! \n Il codice è: "+pos.split("|")[1]+"\n\n Segnatelo per bene e non scordarlo!!!");
		return;		
	}
	/****************************************
	*            Partita patta!!!           *
	****************************************/
	if (pos == "DRAW")
	{
		scacco_matto = true;
		my_alert("PATTA! Riprova, la vittoria è vicina :)");
		$$('div.pezzo').each(function (div)
		{
			div.setStyles({'opacity': 0.6});
		});		
		return;
	}
	/****************************************
	*                Arrocchi               *
	****************************************/
	if(pos.split("|")[0] == "O-O") //Arrocco corto
	{
		move_piece("b_re", "g8");
		move_piece("b_torre_", "f8");
		return
	}
	if(pos.split("|")[0] == "O-O-O") //Arrocco lungo
	{
		move_piece("b_re", "c8");
		move_piece("b_torre", "d8");
		return
	}
	/****************************************
	*          Cattura En Passant           *
	****************************************/
	if( pos.indexOf("ep") > 0)
		eat_ep = pos.substr(pos.indexOf("ep")+2,2);
	else
		eat_ep = "";

	$$('div.pezzo').each(function (div)
	{
		pt = Math.round(div.getStyle('top').toInt()/50);
		pl = Math.round(div.getStyle('left').toInt()/50);
		posPezzo = letter[pl] + (8-(pt));
		if( posPezzo == pos.substr(0,2) )
		{
			mv = div.id;
			if ( div.id.indexOf("b_pedone") > -1 && (8-(pt)) == 7 && pos.substr(3,1).toInt() == 5 )
				en_passant = posPezzo;
		}
		/****************************************
		*       Si deve mangiare un pezzo?      *
		****************************************/
		if( posPezzo == pos.substr(2,2) || posPezzo == eat_ep )
		{
			to_eat = div.id;
			eat_piece(to_eat);
		}
		if(div.id == "re")
		{
			pos_re = posPezzo;
		}
			
	});
	pfx = move_piece(mv, pos.substr(2,2));
	if( pos.indexOf("=") > 0 )
		promote( mv, pos.substr(pos.indexOf("=")+1,1).toLowerCase() )
	
	/****************************************
	*        Scacco!!! Lampeggia RE         *
	****************************************/	
	if (pos.substr(4,1) == "+")
	{
		from = col_cas[$(pos_re).id];
		to = "#ffcccc";
		ScaccoFX = new Fx.Styles($(pos_re), {duration: 250,transition: Fx.Transitions.linear});
		ScaccoFX.start({'background-color'  : to})
		.chain(function(){this.start({'background-color'  : from}) })
		.chain(function(){this.start({'background-color'  : to}) })
		.chain(function(){this.start({'background-color'  : from}) });		
	}
	/****************************************
	*             Scacco Matto!!!           *
	****************************************/
	if (pos.substr(4,1) == "#")
	{
		scacco_matto = true;
		my_alert("Scacco MATTO! Il computer ti ha battuto :)");
		$$('div.pezzo').each(function (div)
		{
			if(div.id.substr(0,2) != "b_")
			{
				div.setStyles({'opacity': 0.6});
			}
		});		
	}

}

//////////////////////////////////////////////////
//           Rende un pezzo muovibile           //
//////////////////////////////////////////////////
function set_movable(el)
{
	el.addEvent('mousedown', function(e) 
	{
		e = new Event(e).stop();
		var clone = this.clone()
		    .setStyles(this.getStyles()) // this returns an object with left/top/bottom/right, so its perfect
		    .setStyles({'opacity': 0.6, 'position': 'absolute'})
		    .addEvent('emptydrop', function() {
				this.remove();
				droppables.removeEvents();
			}).injectInside(board);
		
		droppables.addEvents({
			'drop': function() {
				cid = clone.id;
				pid = this.id;
				droppables.removeEvents();
				clone.remove();
				this.effect('background-color', {wait: false}).start(col_cas[this.id]);
				mossa = pos_start+this.id;
				ar = arrocco(cid, pid);
				if(ar != false)
					mossa = ar;
				else
					mossa = ari_mossa(cid, mossa);

				if (!valide.contains(this.id)) return my_alert("Ma dove vai?!?!");
				if (your_turn == false) return;
				if (pos_start == pid) return;
				if (scacco_matto == true) return;				
				/****************************************
				*		Chiamata Ajax al server         *
				****************************************/
				loader.style.display = 'block';
				your_turn = false;
				var call = new Ajax(
				BASE_URL+'chess.php', 
				{
					method: 'get', 
					onComplete: function(request)
					{
							if( request == "Illegal Move" )
							{
								your_turn = true;
								my_alert( "Mossa non valida!" );
							}
							else
							{
								//Arrocco
								if(ar != false)
								{
									if(ar == "O-O")
									{
										//Corto
										move_piece("re", "g1");
										pfx = move_piece("torre_", "f1");		
									}
									else
									{
										//Lungo
										move_piece("re", "c1");
										pfx = move_piece("torre", "d1");		
									}
								}
								else
								{
									pfx = move_piece(cid, pid);
								}
								if( mossa.indexOf("=") > 0 )
									promote( cid, mossa.substr(mossa.indexOf("=")+1,1) );
								pfx.chain(function(){find_move(request)});
								log_mossa(mossa, request);
								last_black_move = request;
								your_turn = true;
							}
							loader.style.display = 'none';
					}
				}
				).request({fname: fname, move: mossa, time: $('time_to_think').value});			

			},
			'over': function(){
				this.setStyle('background-color', '#ccffcc');
			},
			'leave': function(){this.setStyle('background-color', col_cas[this.id]);}
		});
 
		var drag = clone.makeDraggable({
			container: board,
			droppables: droppables,
			'onStart' : function()
			{
				t = Math.round(this.element.getStyle('top').toInt()/50);
				l = Math.round(this.element.getStyle('left').toInt()/50);
				pos_start = letter[l] + (8-(t));
				
				highlight_possibles(pos_start);
			}
		}); // this returns the dragged element
 
		drag.start(e); // start the event manual
	}); 
}

//////////////////////////////////////////////////
//         Non fa nulla (serve per IE)          //
//////////////////////////////////////////////////
function set_movable_null(el)
{
	el.addEvent('mousedown', function(e) 
	{
		//Senza questa funzione IE non mostra 
		//gli scacchi dell'avversario... CHE MERDA!
	}); 
}
//////////////////////////////////////////////////
//         Invia una richiesta al server        //
//////////////////////////////////////////////////
function get_id()
{
	loader.style.display = 'block';
	myAjax = new Ajax(
			BASE_URL+'chess.php', 
			{
				method: 'get', 
				onComplete: function(request)
							{
								fname = request;
								loader.style.display = 'none';
								$('gname').innerHTML = "<b>Game ID:</b>   "+request;
							}
			}
			).request({request_id: 1});
}
	