//overall variables
var rownum = 20;
var	colnum = 10;
var currentshape = new Array();
var centrerow = 0; // centre of rotation of the current shape
var centrecol = 0; // ditto
var levelmultipliers = new Array(0, 40, 100, 300, 1200);
var score = 0;
var level = 1;
var squaresoccupied = 0;
var linescount = 0;
var nexttype = Math.round(Math.random()*6);

//the shapes
var shapecolours = new Array('#cf53f0', '#53cff0', '#ffd700', '#ffa200', '#3110ad', '#31ad10', '#ad3110');
var centrerows = new Array(0, 0, 99, 0, 0, 0, 1);
var centrecols = new Array(5, 4, 99, 5, 5, 5, 5);
var shapesquares = new Array('r1c5', 'r0c4', 'r0c5', 'r0c6', 'r0c3', 'r0c4', 'r0c5', 'r0c6', 'r1c4', 'r1c5', 'r0c4', 'r0c5', 'r1c4', 'r0c4', 'r0c5', 'r0c6', 'r1c6', 'r0c4', 'r0c5', 'r0c6', 'r1c4', 'r1c5', 'r0c5', 'r0c6', 'r1c5', 'r1c6', 'r0c4', 'r0c5');

function writeboard() {
	// as you can probably imagine: put in the right divs
	document.write('<div id="tetrisboard">');
	for (i = 0; i < rownum; i++) {
		document.write('<div class="tetrisrow" id="row' + i + '">');
		for (j = 0; j < colnum; j++) {
			document.write('<div class="tetrissquare" id="r' + i + 'c' + j + '"></div>');
		}
		document.write('</div>');
	}
	document.write('</div>');
}

function addshape(type) {
	for (i = 0; i < 10; i++) {
		if (document.getElementById('r0c' + i).finished) {
			gameover(); // end if you've reached the top at start of go
		}
	}
	nexttype = Math.round(Math.random()*6); // will be used for the preview piece
	document.getElementById('previewpic').src = '/nerdfoolery/t' + nexttype + '.gif';
	var shapecolour = shapecolours[type];
	centrerow = centrerows[type];
	centrecol = centrecols[type];
	var newsquares = new Array(shapesquares[(type*4)], shapesquares[(type*4)+1], shapesquares[(type*4)+2], shapesquares[(type*4)+3])
	for (i = 0; i < newsquares.length; i++) {
		if (document.getElementById(newsquares[i]).occupied) {
			gameover(); // end if there's no room for the new one
			return false;
		}
	}
	currentshape = new Array(); // keep track of squares currently in play
	for (i = 0; i < newsquares.length; i++) {
		document.getElementById(newsquares[i]).occupied = true;
		document.getElementById(newsquares[i]).currentshape = true;
		document.getElementById(newsquares[i]).style.backgroundColor = shapecolour;
		document.getElementById(newsquares[i]).colour = shapecolour;
		currentshape.push(newsquares[i]);
	}
}

function movedown() {
	rowsfull = new Array();
	// check it's ok to move down
	for (i = 0; i < 4; i++) {
		rbelow = getrow(currentshape[i]) + 1;
		ccol = getcol(currentshape[i]);
		squarebelow = 'r' + rbelow + 'c' + ccol;		
		if (rbelow == 20) {
			var reachedground = true;
			break;
		}
		if (document.getElementById('r' + rbelow + 'c' + ccol).finished) {
			reachedground = true;
			break;
		}
	}
	// do so if possible
	if (!reachedground) {
		if (centrerow != 99) {
			centrerow += 1;
		}
		updatesquares(1, 0);
		coloursquares();
	}
	// otherwise, deal with reaching the bottom
	else {
		for (i = 0; i < 4; i++) {
			currentsquare = currentshape.shift();
			document.getElementById(currentsquare).finished = true;
			squaresoccupied++;
		}
		// work out which rows are full
		for (i = 19; i >= 0; i--) {
			colsfull = 0;
			for (j = 0; j < 10; j++) {
				if (document.getElementById('r' + i + 'c' + j).finished) {
					colsfull++;
				}
			}
			if (colsfull == 10) {
				rowsfull.push(i);
			}
		}
		score += (level * levelmultipliers[rowsfull.length]); //points for clearing lines
		// clear the empty rows
		for (i = 0; i < rowsfull.length; i++) {
			thisrow = rowsfull[i];
			for (j = 0; j < 10; j++) {
				document.getElementById('r' + thisrow + 'c' + j).occupied = false;
				document.getElementById('r' + thisrow + 'c' + j).finished = false;
				document.getElementById('r' + thisrow + 'c' + j).style.backgroundColor = 'white';
				squaresoccupied--;
			}
			linescount++;
		}
		document.getElementById('lines').firstChild.nodeValue = linescount;
		if (linescount == (5 * (Math.pow(level, 2) + level))) {
			level++;
			clearInterval(timer);
			timer = setInterval("movedown()", (1000 * Math.pow(0.7, (level - 1))));
				document.getElementById('level').firstChild.nodeValue = level;
		}
		//move other tiles down
		for (d = 0; d < rowsfull.length; d++) {
			for (r = (rowsfull[d] + d); r > 0; r--) {
				for (c = 0; c < 10; c++) {
					newsquare = document.getElementById('r' + r + 'c' + c);
					squareabove = document.getElementById('r' + (r - 1) + 'c' + c);
					if (squareabove.finished) {
						newsquare.occupied = true;
						newsquare.finished = true;
						newsquare.style.backgroundColor = squareabove.style.backgroundColor;
					}
					squareabove.occupied = false;
					squareabove.finished = false;
					squareabove.style.backgroundColor = 'white';
				}
			}
		}
		// bonus points for clearing the board
		if ((rowsfull.length > 0) && (squaresoccupied == 0)) {
			score += (4444 * level);
		}
		document.getElementById('score').firstChild.nodeValue = score;
		addshape(nexttype);
	}
}

function sideways(coldiff) {
	// again, check it's ok to move sideways
	coldiff = parseInt(coldiff);
	for (i = 0; i < 4; i++) {
		row = getrow(currentshape[i]);
		colside = getcol(currentshape[i]) + parseInt(coldiff);
		if ((colside == -1) || (colside == 10)) {
			var reachededge = true;
			break;
		}
		if (document.getElementById('r' + row + 'c'+ colside).finished) {
			var reachededge = true;
			break;
		}
	}
	// do so if possible
	if (!reachededge) {
		if (centrecol != 99) {
			centrecol += coldiff;
		}
		updatesquares(0, coldiff);
		coloursquares();
	}
}

function drop() {
	// work out the distances between shape and ground beneath it
	var highest = 19;
	var lowestrow = 0;
	for (i = 0; i < 4; i++) {
		row = getrow(currentshape[i]);
		if (row > lowestrow) {
			lowestrow = row;
		}
		col = getcol(currentshape[i]);
		for (j = row; j < 20; j++) {
			if (document.getElementById('r' + j + 'c' + col).finished) {
				if (j < highest) {
					highest = j;
				}
			}
		}
	}
	score += (19 - lowestrow);
	// drop down until you reach it
	for (drow = lowestrow; drow < highest; drow++) {
		movedown();
	}
}

function rotate(iterations) { // only going to ever go round in right angles
	if (centrerow != 99) { // since we don't want to rotate the square
		for (j = 0; j < iterations; j++) {
			// check it's possible to rotate here
			for (i = 0; i < 4; i++) {
				currentsquare = currentshape[i];
				oldrow = getrow(currentsquare);
				oldcol = getcol(currentsquare);
				rdiff = oldrow - centrerow;
				cdiff = oldcol - centrecol;
				newrow = centrerow + cdiff;
				newcol = centrecol - rdiff;
				if ((newrow < 0) || (newrow > 19) || (newcol < 0) || (newcol > 9)) {
					var cannotrotate = true;
					break;
				}
				if (document.getElementById('r' + newrow + 'c' + newcol).finished) {
					var cannotrotate = true;
					break;
				}
			}
			// then make rotation happen
			if (!cannotrotate) {
				for (i = 0; i < 4; i++) {
					currentsquare = currentshape[i];
					oldrow = getrow(currentsquare);
					oldcol = getcol(currentsquare);
					rdiff = oldrow - centrerow;
					cdiff = oldcol - centrecol;
					newrow = centrerow + cdiff;
					newcol = centrecol - rdiff;
					newsquare = 'r' + newrow + 'c' + newcol;
					document.getElementById(currentsquare).occupied = false;
					document.getElementById(currentsquare).currentshape = false;			
					document.getElementById(currentsquare).style.backgroundColor = 'white';
					currentshape[i] = newsquare;
				}
				coloursquares();
			}
		}
	}
}

function updatesquares(rowdiff, coldiff) {
	// give new squares the properties of occupied ones, and clear used ones
	for (i = 0; i < 4; i++) {
		currentsquare = currentshape[i];
		row = getrow(currentsquare);
		col = getcol(currentsquare);
		newrow = row + parseInt(rowdiff);
		newcol = col + parseInt(coldiff);
		newsquare = 'r' + newrow + 'c' + newcol;
		document.getElementById(currentsquare).occupied = false;
		document.getElementById(currentsquare).currentshape = false;			
		document.getElementById(currentsquare).style.backgroundColor = 'white';
		currentshape[i] = newsquare;
	}
}

function coloursquares() {
	// colour things in properly, or it'll just be a horrible mess
	for (i = 0; i < 4; i++) {
		sidesquare = currentshape[i];
		document.getElementById(sidesquare).occupied = true;
		document.getElementById(sidesquare).currentshape = true;
		document.getElementById(sidesquare).colour = document.getElementById(currentsquare).colour;
		document.getElementById(sidesquare).style.backgroundColor = document.getElementById(currentsquare).colour;
	}
}

function getrow(squareid) {
		var r = squareid.indexOf('r') + 1;
		var c = squareid.indexOf('c');
		return parseInt(squareid.substring(r, c));
}

function getcol(squareid) {
		var c = squareid.indexOf('c');
		return parseInt(squareid.substring(c + 1));
}

function gameover() {
	// how to deal with the end
	document.getElementById('left').disabled = true;
	document.getElementById('right').disabled = true;
	document.getElementById('down').disabled = true;
	document.getElementById('drop').disabled = true;
	document.getElementById('clockwise').disabled = true;
	document.getElementById('anticlockwise').disabled = true;
	clearInterval(timer);
}

// stuff to happen when the page is loaded
writeboard();
timer = setInterval("movedown()", 1000);