// Javascript for myChess
// ``````````````````````

window.onload = onLoad;

function onLoad() {	
	addEventsToCells();
	ID('moreHistory').onclick = loadMoreHistory;
}

// Hiding the info bar

function hideInfo() {
	if (ID('info')) ID('info').style.display = 'none';
}

// Board cell selection

var board_tbl, board_rows, board_cols;
function addEventsToCells() {
	board_tbl  = ID('board');
	board_rows = board_tbl.rows.length;
	board_cols = board_tbl.rows[0].cells.length; 

	for (y=1; y < board_rows-1; y++) for (x=1; x < board_cols-1; x++) {
		board_tbl.rows[y].cells[x].onclick = onCell;
	}
}

function onCell() {
	for (y=0; y < board_rows; y++) for (x=0; x < board_cols; x++) {
		if (board_tbl.rows[y].cells[x] == this) onCellSelected(x, y);
	}
}

function onCellSelected(x,y) {
	if (! ID('moveEntry')) return;

	var content = ID('moveEntry').value;
	var columns = ['a','b','c','d','e','f','g','h'];
	var move_str;
	if (board_reverse) {
		move_str = columns[8-x]+(y);
	} else {
		move_str = columns[x-1]+(9-y);
	}
	if (content.length == 2) {
		ID('moveEntry').value += ' '+move_str;
	} else if (content.length == 0) {
		ID('moveEntry').value = move_str;
	}
}

// Loading full history

function loadMoreHistory() {
	ID('history').innerHTML = 'Loading...';
	ajaxGet('?p=history&id='+myAuth,
		function(data) {
			ID('history').innerHTML = data;
			ID('moreHistory').style.display = "none";
		},
		function() {
			ID('history').innerHTML = 'Error loading history.';
		}
	);
}

// Framework

function ID(el) {
	return document.getElementById(el);
}

function ajaxGet(address, onSuccess, onFailure) {	
	var requester;
	if (window.XMLHttpRequest) {
		requester = new XMLHttpRequest();
		if (requester === null) {
			onFailure();
			return;
		}
	} else if (window.ActiveXObject) { 
		try {
			requester = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (ex) {
			onFailure();
			return;
		}
	} else {
		onFailure();
		return;
	}
	
	requester.onreadystatechange = function() {
		if (requester.readyState == 4 /*complete*/){
			if (requester.status == 200 || window.location.href.indexOf("http") == -1){
				onSuccess(requester.responseText);
			} else {
				onFailure();
			}
		}
	}
	
	requester.open("GET", address, true);
	requester.send(null);	
	return;
}
