baseColor   = "#000000";
bgColor     = "#FFFFFF";
tdArray     = null;
colorArray  = null;
tdCount     = 0;
changeCount = 1; // changeCount starts at 1 because there is always one cell that already has the baseColor

function getRandomCell() {
	var length = tdArray.length;
	var i = Math.round(Math.random() * 1000) % length;
	
	return tdArray[i];
}

function changeColor() {
	var tdElement = getRandomCell();
	
//alert(baseColor + ' = ' + bgColor);
	if ((changeCount != tdCount) && (baseColor != bgColor)) {
//alert('tds=' + tdCount + ' cnt=' + changeCount + ' td=' + tdElement.style.backgroundColor + " bc=" + baseColor + " bg=" + bgColor);

		if (tdElement.style.backgroundColor != baseColor) {
			if (tdElement.style.backgroundColor != bgColor) {
				changeCount++;
			}
			
			tdElement.style.backgroundColor = baseColor;
		}
		else {
			tdElement.style.backgroundColor = bgColor;
		}
	}
	else {
//alert(tdCount+'else' + changeCount);
//alert('change bg color');
		initializeTdColors();
	}
}

function buildColorArray() {
	colorArray = new Array(tdArray.length);
	
	for (i = 0; i < tdArray.length; i++) {
		colorArray[i] = tdArray[i].style.backgroundColor;
	}
}

function getRandomColor() {
	var length = colorArray.length;
	var i = Math.round(Math.random() * 1000) % length;
//	alert(colorArray[i]);
	return colorArray[i];
}

function initializeTdColors() {
	for (i = 0; i < tdArray.length; i++) {
		tdArray[i].style.backgroundColor = "#FFFFFF";
	}
	
	randomizeTdColors();
	
	bgColor = document.getElementById("body").style.backgroundColor = baseColor;
	changeCount = 2; // changeCount resets to 2 because 1 cell in the new set will be the bgColor and 1 will be the baseColor. need to count them.
	baseColor = getRandomColor();
}

function randomizeTdColors() {
	for (i = 0; i < tdArray.length; i++) {
		tdArray[i].style.backgroundColor = colorArray[i];
	}
}

function init() {
//alert('1');
	tdArray = document.getElementsByTagName("td");
//alert('2');
	tdCount = tdArray.length;
//alert('3');
	buildColorArray();
//alert('4');
	
	var tdElement = getRandomCell();
//alert('5');
	baseColor = tdElement.style.backgroundColor;
//alert('6');
	
	setInterval("changeColor()",1000);
}
