// my way of avoiding the canvas to redraw faster than it can handle
(function(){
	var list=[];
	Function.prototype.wait = function(){
		var i=list.length;
		while (i -- >0) if (list[i][0]==this) return;
		i=arguments;
		list[list.length]=[this,setTimeout(function(){
			list.shift()[0].apply(window,i);
		},1)];
	}
})();


Number.prototype.toLength = function(n){
	var str = this.toString();
	while (str.length<n) str = '0'+str;
	return str;
}

var setCookie=function(name, value) {
	if(window.widget) widget.setPreferenceForKey(encodeURIComponent(value), name)
	else document.cookie = name+"="+encodeURIComponent(value)+
		"; expires="+(new Date(new Date().getTime()+(360*24*60*60*1000))).toGMTString()+"; path=/";
}

var getCookie=function(name) {
	if(window.widget) return decodeURIComponent(widget.preferenceForKey(name))||null;
	if(new RegExp(name+'\=([^;]*);','').test(document.cookie+';') ) return decodeURIComponent(RegExp.$1);
	return null;
}


window.onload=function(){
    
	function g(e){return document.getElementById(e);}

	g('container').style.visibility = 'visible';
    g('loading').style.display = 'none';

	var ctx=g('canvas').getContext('2d');;
	var sprite=g('sprite').getContext('2d');

	function storeBest(){
		var pos;
		for (var gameType=0; gameType<3; gameType++) {
			for (pos=0; pos<3; pos++) {
				setCookie('best'+gameType+''+pos+'score', best[gameType][pos][0]);
				setCookie('best'+gameType+''+pos+'name', best[gameType][pos][1]);
			}
		}
	}
	
	function getBestStr(i){
		str='<B>'+['Traditional','Time Attack','Garbage'][i]+'</B>';
		for (j=0; j<3; j++) {
			str+='<BR>'+(j+1)+'. '+best[i][j][1]+' ('+(i==2 ? niceTime(best[i][j][0]) : best[i][j][0])+')';
		}
		return str;
	}
	
	function displayBest(){
		var str, j;
		for (var i=0; i<3; i++) {
			g('best'+(i+1)).innerHTML = getBestStr(i);
		}
	}
	
	g('bestType').onchange=function(){
		var n = this.options.selectedIndex;
		for (var i=0; i<3; i++) g('best'+(i+1)).style.display = (i==n) ? 'block' : 'none';
	}
	
	var best = [
		[
			['0','Empty'],
			['0','Empty'],
			['0','Empty']
		],[
			['0','Empty'],
			['0','Empty'],
			['0','Empty']
		],[
			['3599','Empty'],
			['3599','Empty'],
			['3599','Empty']
		]
	];
			
	if (getCookie('best11score')==null) {
		storeBest();
	}
	else {
		for (var gameType=0; gameType<3; gameType++) {
			for (pos=0; pos<3; pos++) {
				best[gameType][pos][0] = Number(getCookie('best'+gameType+''+pos+'score')) || 0;
				best[gameType][pos][1] = getCookie('best'+gameType+''+pos+'name');
			}
		}
	}
	
	displayBest();
	
	sprite.translate(100,150);
	ctx.translate(100, 150);
	ctx.lineJoin=ctx.lineCap='round';
	ctx.globalAlpha=sprite.globalAlpha=0.9;
	ctx.lineWidth=sprite.lineWidth=0.7;
	ctx.strokeStyle='#000';



	var innerRadius = 40;

	function iso(x, y, r) {
		r = r ? innerRadius : 60;
		return {
			x: r*Math.cos((2*Math.PI)*((x-theta)/15-1/4))*(y+30)/30,
			y: 200-y*20*(y/2+60)/60 - 0.3*r*Math.sin((2*Math.PI)*((x-theta)/15-1/4))
		}
	}

	var field, theta, lines;
	var ghost = getCookie('ghost');
	if (ghost==null || ghost==1) {
		g('set_ghost').checked=true;
		ghost=true;
	}
	else ghost = false;

	var game_mode=1;

	function clearField(){
		var i,j,r;	

		x=0;

		field = []; for (i=0; i<15; i++) field[i] = new Array(15);
		theta=0;
		lines=0;
		g('score').innerHTML = (game_mode==3) ? '+6' : '000';
		
		if (game_mode==1) {
			var f = field;
			f[10][0] = f[11][0] = f[10][1] = f[11][1] = 1;	
			f[9][0] = f[9][1] = f[9][2] = f[9][3] = 2;	
			f[8][0] = f[7][0] = f[7][1] = f[6][0] = 3;	
			f[12][0] = f[13][0] = f[13][1] = f[13][2] = 4;	
			f[3][0] = f[4][0] = f[5][0] = f[5][1] = 5;
			f[1][0] = f[2][0] = f[2][1] = f[3][1] = 6;
			f[7][3] = f[7][2] = f[6][2] = f[6][1] = 7;
		}
		if (game_mode==2) {
			var f=field;
			f[0][0] = f[3][0] = f[6][0] = f[9][0] = f[12][0] = (Math.random()*6+1)>>0;
		
		}
		if (game_mode==3) {
			for (i=0; i<9; i++) {
				for (j=0; j<5; j++) {
					r = (Math.random()*15)>>0;
					if (field[r][i]) {
						j--;
						continue;
					}
					else field[r][i]=1;
				}
			}
		}



	}
	clearField();

	CanvasRenderingContext2D.prototype.drawFront = function(x,y,r){
		this.beginPath();
		var co=iso(x, y-1, r); this.moveTo(co.x, co.y);
		co=iso(x, y, r); this.lineTo(co.x, co.y);
		co=iso(x+1, y, r); this.lineTo(co.x, co.y);
		co=iso(x+1, y-1, r); this.lineTo(co.x, co.y);
		this.closePath();
		this.fill();
		this.stroke();
	}


	CanvasRenderingContext2D.prototype.drawTop = function(x, y){
		this.beginPath();
		var co = iso(x, y); this.moveTo(co.x, co.y);
		co = iso(x, y, true); this.lineTo(co.x, co.y);
		co = iso(x+1, y, true); this.lineTo(co.x, co.y);
		co = iso(x+1, y); this.lineTo(co.x, co.y);
		this.closePath();
		this.fill();
		this.stroke();
	}
	CanvasRenderingContext2D.prototype.drawSide = function(x,y){
		this.beginPath();
		co = iso(x, y); this.moveTo(co.x, co.y);
		co = iso(x, y, true); this.lineTo(co.x, co.y);
		co = iso(x, y-1, true); this.lineTo(co.x, co.y);
		co = iso(x, y-1); this.lineTo(co.x, co.y);
		this.closePath();
		this.fill();
		this.stroke();
	}

	var displayGold = false;

	function drawCylinder(clear){
        
		ctx.clearRect(-100,-150,200,400);

/*
	for (var i=0; i<=15; i+=0.1) {
		var co=iso(i, -1);
		if (i==0) ctx.moveTo(co.x, co.y);
		else ctx.lineTo(co.x, co.y);
	
	}
	ctx.stroke();
	ctx.beginPath();
*/



		var xOff = ((theta)%15+15)%15>>0;

		var x=0,y,i;

		var intensity;

		var block_type;

		var burntBlocks=0;
		for (i=0; i<15; i++) {
			x=[7,8,6,9,5,10,4,11,3,12,2,13,1,14,0][i];
			for (y=0; y<16; y++) {
				if (field[((x+xOff)%15+15)%15][y]) {
					intensity=0.2+0.8*i/14;
					if (game_mode==3) ctx.globalAlpha = Math.max((intensity-0.3)/0.7, 0);
					var block_type = field[((x+xOff)%15+15)%15][y]-1;
					if (game_mode==3 && y>=3) block_type = 7;
					if (displayGold) block_type = 8;
					switch(block_type) {
						case 0 : ctx.fillStyle = 'rgb('+((intensity*255)>>0)+','+((intensity*0)>>0)  +','+((intensity*0)>>0)  +')'; break;
						case 1 : ctx.fillStyle = 'rgb('+((intensity*0)>>0)  +','+((intensity*255)>>0)+','+((intensity*0)>>0)  +')'; break;
						case 2 : ctx.fillStyle = 'rgb('+((intensity*0)>>0)  +','+((intensity*0)>>0)  +','+((intensity*255)>>0)+')'; break;
						case 3 : ctx.fillStyle = 'rgb('+((intensity*255)>>0)+','+((intensity*255)>>0)+','+((intensity*0)>>0)  +')'; break;
						case 4 : ctx.fillStyle = 'rgb('+((intensity*255)>>0)+','+((intensity*0)>>0)  +','+((intensity*255)>>0)+')'; break;
						case 5 : ctx.fillStyle = 'rgb('+((intensity*0)>>0)  +','+((intensity*255)>>0)+','+((intensity*255)>>0)+')'; break;
						case 6 : ctx.fillStyle = 'rgb('+((intensity*220)>>0)+','+((intensity*220)>>0)+','+((intensity*220)>>0)+')'; break;
						case 7 : ctx.fillStyle = 'rgb('+((intensity*100)>>0)+','+((intensity*100)>>0)+','+((intensity*100)>>0)+')'; break;
						case 8 : ctx.fillStyle = 'rgb('+((intensity*190)>>0)+','+((intensity*190)>>0)+','+((intensity*0)>>0)  +')'; break;
						default: ctx.fillStyle = 'white';
					}
					ctx.drawFront(x+xOff,y, i<7+(theta%1+1%1));
					if (!field[((x+xOff)%15+15)%15][y+1]) ctx.drawTop(x+xOff,y);
					if (i%2!=0 || i==0 && (theta%1+1)%1!=0.75) if (!field[((x+1+xOff)%15+15)%15][y]) ctx.drawSide(x+xOff+1,y);
					if (i%2==0 && i!=14 || ((theta%1+1)%1==0.75 && i==1)) if (!field[((x-1+xOff)%15+15)%15][y]) ctx.drawSide(x+xOff,y);
				}
			}
		}
	}
	
	var nextType;
	
	var tetra = new (function(){
		var block;
		
		var x=-2;
		var y;
		var type;
		
		var rotated;

		var blockData = [
			[
				[{x:1,y:2}, {x:2,y:2}, {x:1,y:1}, {x:2,y:1}]
			],
			[
				[{x:0,y:1}, {x:1,y:1}, {x:2,y:1}, {x:3,y:1}],
				[{x:1,y:3}, {x:1,y:2}, {x:1,y:1}, {x:1,y:0}]
			],
			[
				[{x:0,y:2}, {x:1,y:2}, {x:2,y:2}, {x:1,y:1}],
				[{x:2,y:2}, {x:1,y:3}, {x:1,y:2}, {x:1,y:1}],
				[{x:1,y:3}, {x:0,y:2}, {x:1,y:2}, {x:2,y:2}],
				[{x:0,y:2}, {x:1,y:3}, {x:1,y:2}, {x:1,y:1}]
			],
			[
				[{x:0,y:2}, {x:1,y:2}, {x:2,y:2}, {x:0,y:1}],
				[{x:1,y:3}, {x:1,y:2}, {x:1,y:1}, {x:2,y:1}],
				[{x:0,y:2}, {x:2,y:3}, {x:2,y:2}, {x:1,y:2}],
				[{x:0,y:3}, {x:1,y:3}, {x:1,y:2}, {x:1,y:1}]
			],
			[
				[{x:2,y:2}, {x:1,y:2}, {x:0,y:2}, {x:2,y:1}],
				[{x:2,y:3}, {x:1,y:3}, {x:1,y:2}, {x:1,y:1}],
				[{x:0,y:3}, {x:0,y:2}, {x:1,y:2}, {x:2,y:2}],
				[{x:1,y:3}, {x:1,y:2}, {x:1,y:1}, {x:0,y:1}]

			],
			[
				[{x:0,y:2}, {x:1,y:2}, {x:1,y:1}, {x:2,y:1}],
				[{x:0,y:1}, {x:0,y:0}, {x:1,y:2}, {x:1,y:1}]
			],
			[
				[{x:1,y:2}, {x:2,y:2}, {x:0,y:1}, {x:1,y:1}],
				[{x:2,y:1}, {x:2,y:0}, {x:1,y:2}, {x:1,y:1}]
			]
		]


		this.change = function(){
			type = nextType;
			nextType= Math.random()*7>>0;
			g('next').style.backgroundPosition = (-nextType*80)+'px 0';
			rotated=0;
			y=16;
			sprite.fillStyle = ['#F00', '#0F0','#00F','#FF0','#F0F','#0FF','#DDD'][type];
			if (type==1) theta-=0.25;
			if (type>=2) theta-=0.5;
			block=blockData[type][0];
			draw();
		}

		var shadowBlock = [[3,3]];
		
		function solveShadow(){
			for (var j=0; j<20; j++) {
				for (i=0; i<4; i++) {
					if (y-block[i].y-j<0 || field[((x+block[i].x)%15+15)%15][y-block[i].y-j]) break;
				}
				if (i<4) break;
			}

			for (i=0; i<4; i++) {
				shadowBlock[i] = [((x+block[i].x)%15+15)%15, y-block[i].y-j+1];
			}

		}
		
		function draw(){
			
			sprite.clearRect(-100,-150,200,400);

			if (ghost) {

				solveShadow();
			
				if (innerRadius == 0) innerRadius = 41;
			
				sprite.globalAlpha = 0.4;
				// draw our shadows
				var j;
				for (i=0; i<shadowBlock.length; i++) {
					for (j=0; j<4; j++) if(shadowBlock[i][0] == ((x+block[j].x)%15+15)%15 && shadowBlock[i][1] == y-block[j].y) break;
					if (j==4) {
						sprite.drawFront(shadowBlock[i][0], shadowBlock[i][1]);
						sprite.drawTop(shadowBlock[i][0], shadowBlock[i][1]);
						sprite.drawSide(shadowBlock[i][0], shadowBlock[i][1]);
						sprite.drawSide(shadowBlock[i][0]+1, shadowBlock[i][1]);
					}
				}
				sprite.globalAlpha = 1;
			
				if (innerRadius == 41) innerRadius = 0;
			}
		


			// draw our cubes
			for (var i=0,j; i<4; i++) {
				sprite.drawFront(x+block[i].x, y-block[i].y, false);
				//drawSide
				if (block[i].x==0 && !field[((x+block[i].x+1)%15+15)%15][y-block[i].y]) {
					for (j=0; j<4; j++) if (block[j].x==1 && block[j].y==block[i].y) break;
					if (j==4) sprite.drawSide(x+block[i].x+1, y-block[i].y);
				}
				//drawSide2
				if (block[i].x>=2 && !field[((x+block[i].x-1)%15+15)%15][y-block[i].y]) {
					for (j=0; j<4; j++) if (block[j].x==block[i].x-1 && block[j].y==block[i].y) break;
					if (j==4) sprite.drawSide(x+block[i].x, y-block[i].y);
				}
				//drawTop
				if (!field[((x+block[i].x)%15+15)%15][y-block[i].y+1]) {
					for (j=0; j<4; j++) if (block[j].x==block[i].x && block[j].y+1==block[i].y) break;
					if (j==4) sprite.drawTop(x+block[i].x, y-block[i].y);
				}	
			
			}


			sprite.globalCompositeOperation='destination-out';
			//chop out cubes where overlap
			for (i=0; i<4; i++) {
				if (field[((x+block[i].x)%15+15)%15][y-block[i].y+1]) {
					sprite.drawFront(x+block[i].x, y-block[i].y+1);
				}
			}
			sprite.globalCompositeOperation='source-over';
		}
		
		function place(){
			for (var i=0; i<4; i++) field[((x+block[i].x)%15+15)%15][y-block[i].y]=type+1;
			var cleared = 0;
			var lowest = 0; 
			for (var j=0; j<15; j++) {
				for (i=0; i<15; i++) if (!field[i][j]) break;
				if (i==15) {
					for (i=0; i<15; i++)
                    {
                        for (var k=j; k+1<15; k++)
                        {
                            field[i][k] = field[i][k+1];
                        }
                        field[i][k] = null;
                    }
					j--;
					lines++;
					cleared++;
				}
			}
			if (cleared==4) lines++;
			if (game_mode==3) {
				for (j=14; j>2; j--) {
					for (i=0; i<15; i++) if (field[i][j]) break;
					if (i<15) break;
				}
				g('score').innerHTML = '+'+(j-2);
				if (j==2) {
					tetra.change();
					drawCylinder();
					gameOver(true);
					if (type>=2) theta+=0.5;
					if (type==1) theta+=0.25;
					return;
				}
			}
			else {
				g('score').innerHTML=lines.toLength(3);
			}
			if (type>=2) theta+=0.5;
			if (type==1) theta+=0.25;
			tetra.change();
			drawCylinder( cleared > 0);
			if (overlaps()) gameOver();
            
		}
		
		this.prepare = function(){
			x=-2;
			this.change();
		}
		
		function overlaps(){
			var X,Y;
			for (var i=0; i<4; i++) {
				X = ((x+block[i].x)%15+15)%15;
				Y = y-block[i].y;
				if (Y<0 || field[X][Y]) return true;
			}
			return false;
		}
		
	
		this.move = function(xDir, yDir){
			for (var i=0; i<4; i++) {
				if (y-block[i].y+yDir<0 || field[((x+block[i].x+xDir)%15+15)%15][y-block[i].y+yDir]) {
					if (yDir<0) {
						place();
						if (dropping) {
							clearInterval(dropping);
							dropping = 0;
						}
					}
					return false;
				}
			}

			
			if (xDir) {
				theta+=xDir;
				theta=(theta%15+15)%15;
				x+=xDir;
				draw.wait(true);
				drawCylinder.wait();
			}
			else {
				y+=yDir;
				draw();
			}
			
			return true;
		}

		this.rotate = function(dir, idle){
			if (type==0) return;
			rotated = (rotated+dir+4)%[0,2,4,4,4,2,2][type];//how many times can rotate
			block=blockData[type][rotated];
			
			if (idle) return false; //just be obliging will ya!
			
			if (overlaps()){
				if (this.move(1,0) || this.move(-1,0)) {
					return true;
				}
				else {
					this.rotate(-dir, true);
					
					return false;
				}
			}
			
			draw();
			return true;
		}
		
		return true;
	});
	
	function gameOver(complete){
		secondWait = false;
		clearTimeout(secondRef);
	
		sprite.clearRect(-100,-150, 200, 450);
		paused = true;
		clearTimeout(timoutRef);

		if (complete===false) return;

		g('panel').style.display='none';
		
		var message = 'Your score of '+lines+' did not achieve a high score.';
		
		
		var hasWon = false;
		if (game_mode==1) {
			if (lines>best[0][2][0]) hasWon = true;
		}
		if (game_mode==2) {
			if (time==181) {
				if (lines>best[1][2][0]) hasWon = true;
			} else {
				message = 'Failure. You must survive for 3 minutes to qualify for a high score in <I>Time Attack</I>.';
			}
		}
		if (game_mode==3) {
			if (!complete) message = 'Failure. You must clear all but three rows to qualify for a high score in <I>Garbage</I>.';
			else if (time < best[2][2][0]) hasWon = true;
			else message = 'Your time of '+niceTime(time)+' did not achieve a high score.';
		}
		g('winner').style.display = hasWon ? 'block' : 'none';
		g('newgame').style.display = hasWon ? 'none' : 'block';
		g('sorryText').innerHTML = hasWon ? "" : message;
		g('gameover').style.display='block';
	}
	
	
	var paused = false;
	
	function pauseGame(){
		if (dropping) {
			clearInterval(dropping);
			dropping = 0;
		}
	
		paused = !paused;
		if (paused) {
			ctx.canvas.style.display='none';
			sprite.canvas.style.display='none';
			g('paused').style.display='block';
		}
		else {
			ctx.canvas.style.display='block';
			sprite.canvas.style.display='block';		
			g('paused').style.display='none';
			if (secondWait) {
				secondWait = false;
				addSecond()
			}
		}
	}
	
	g('but_pause').onclick = pauseGame;
	g('but_resume').onclick = pauseGame;
	g('but_restart').onclick = function(){
		pauseGame();
		gameOver(false);
		playingMode(game_mode)
		beginGame(game_mode);
	}
	g('but_restart2').onclick = function(){
		gameOver(false);
		playingMode(game_mode);
		beginGame(game_mode);
	}
	g('but_quit').onclick = function(){
		pauseGame();
		g('panel').style.display='none';
		gameOver(false);
		menuMode();
	}
	
	window.onblur = function(){if (!paused && !active_menu) pauseGame();};
	
	var dropping = 0;
	
	document.onkeyup = function(e){
        e = e || window.event;
		if (dropping && (e.keyCode==40 || e.keyCode==83)) {
			clearInterval(dropping);
			dropping = 0;
		}
	}
	
	document.onkeydown = function(e){
        e = e || window.event;
		if (paused) return;
		switch(e.keyCode){
		
			case 65 : case 37 : tetra.move(-1, 0); break; //left
			case 68 : case 39 : tetra.move(+1, 0); break; //right
			case 87 : case 38 : tetra.rotate(+1); break; //up
			case 32 : tetra.rotate(-1); break; //space;
			case 83 : case 40 :
                if (!dropping)
                {
                    tetra.move(0, -1);
                    dropping = setInterval(function(){
                        tetra.move(0, -1);
                    },40);
                }
				break;
		}
	}
	
	var timoutRef;

	function loopy(){
		if (!paused) tetra.move(0,-1);
		var delay;
		if (game_mode==3) delay = 1000;
		else delay = (20+980*Math.exp(-lines/40))>>0;
		timoutRef = setTimeout(loopy, delay);
	}

	//####################################################################################################
	//
	//####################################################################################################


	var quotes = [
		'"If you love someone, put their name in a <B>circle</B>; because hearts can be broken, but <B>circles</B> never end."<BR><SPAN>- Brian Littrell</SPAN>',
		'"I made a <B>circle</B> with a smile for a mouth on yellow paper, because it was sunshiny and bright."<BR><SPAN>- Harvey Ball</SPAN>',
		'"A <B>circle</B> may be small, yet it may be as mathematically beautiful and perfect as a large one."<BR><SPAN>- Isaac Disraeli</SPAN>',
		'"When the tribe first sat down in a <B>circle</B> and agreed to allow only one person to speak at a time - that was the longest step forward in the history of law"<BR><SPAN>- Judge Curtis Bok</SPAN>',
		'"The nature of God is a <B>circle</B> of which the center is everywhere and the circumference is nowhere"<BR><SPAN>- Empedocles</SPAN>',
		'"The mind petrifies if a <B>circle</B> be drawn around it, and it can hardly be that dogma draws a <B>circle</B> round the mind."<BR><SPAN>- George Moore</SPAN>',
		'"Let mathematicians and geometrician \'talk of <B>circles</B>\' and triangles\' charms, The figure I prize is a girl with bright eyes, And the <B>circle</B> that\'s formed by her arms"<BR><SPAN>- Anonymous</SPAN>',
		'"Round, like a <B>circle</B> in a spiral<BR>Like a wheel within a wheel."<BR><SPAN>- Sting</SPAN>'
	];
	
	g('quote').innerHTML = quotes[(Math.random()*quotes.length) >>0];
	
	g('but_play').onclick = function(){
		if (active_menu) scrollMenu(321,0,'x');
	}
	g('but_settings').onclick = function(){
		if (active_menu) scrollMenu(157,314,'y');
	}
	g('but_high').onclick = function(){
		if (active_menu) scrollMenu(321,642,'x');
		displayGold = true;
		drawCylinder();
	}
	g('but_help').onclick = function(){
		if (active_menu) scrollMenu(157,0,'y',function(){g('helpBox').style.display='block';});
	}
	g('but_main0').onclick = function(){
		if (active_menu) {
			g('helpBox').style.display='none';
			scrollMenu(0,157,'y');
		}
	}
	g('but_main1').onclick = function(){
		if (active_menu) scrollMenu(0,321,'x');
	}
	g('but_main2').onclick = function(){
		if (active_menu) scrollMenu(642,321,'x');
		displayGold = false;
		drawCylinder();
	}
	g('but_main3').onclick = function(){
		if (active_menu) scrollMenu(314,157,'y');
	}

	
	var active_menu = true;
	
	function scrollMenu(x0, x1, dir, funct) {
		active_menu = false;
		var x;
		var i = 0;
		var dist;
		if (dir=='x') dir = 'scrollLeft';
		if (dir=='y') dir = 'scrollTop';
		var loopy = setInterval(function(){
			i++;
			dist = (1-Math.cos(i*Math.PI/20))/2;
			dist = i==20 ? x1 : (x0*(1-dist) + x1*dist);
			g('menu_area')[dir] =  dist>>0;
			if (i==20) {
				active_menu = true;
				clearInterval(loopy);
				if (funct) funct();		
			}	
		}, 30);
	}
	
	var n;
	
	function applyBase(n){
		var str = 'url(images/base'+n+'.png)';
		g('playing').style.backgroundImage = str;
	}
	n = Number(getCookie('base')||0)||0;
	g('set_base').options.selectedIndex = n;
	applyBase(n);

	
	function applyBlocks(n){
		innerRadius = [56,40,0][n];
		drawCylinder();
	}
	var n = getCookie('blocks');
	n = n==null ? 1 : (Number(n||0)||0);
	g('set_blocks').options.selectedIndex = n;
	applyBlocks(n);
	
	g('set_base').onchange = function(){
		n = this.options.selectedIndex;
		applyBase(n);
		setCookie('base', n);
	}
	g('set_blocks').onchange = function(){
		n = this.options.selectedIndex;
		applyBlocks(n);;
		setCookie('blocks', n);
	}
	g('set_ghost').onclick = function(){
		ghost = this.checked;
		setCookie('ghost', (ghost ? 1 : 0));
	}
	g('go1').onclick = function(){
		playingMode(1)
		beginGame(1);
	}
	g('go2').onclick = function(){
		playingMode(2)
		beginGame(2);
	}
	g('go3').onclick = function(){
		playingMode(3)
		beginGame(3);
	}
	
	function menuMode(){
		g('menu').style.display = 'block';
		g('menu_area').scrollLeft = 321;
		g('menu_area').scrollTop = 157;
		active_menu = true;
		g('gameover').style.display = 'none';
		game_mode = 1;
		clearField();

		drawCylinder();
	}
	menuMode();
	
	g('but_main4').onclick = function(){
		gameOver(false);
		menuMode();
	}
	
	function playingMode(mode){
		active_menu = false;
		g('menu').style.display = 'none';	
		g('gameover').style.display = 'none';
		for (var i=1; i<=3; i++) g('title'+i).style.display = (i==mode ? 'block' : 'none');
		g('panel').style.display='block';

		var x,y;
		if (mode==1) x=328, y=202;
		if (mode==2) x=328, y=197;
		if (mode==3) x=330, y=170;
	}
	
	function niceTime(t){
		return ((t/60)>>0)+':'+(t%60).toLength(2)
	}
	
	var time;
	var secondWait;
	var secondRef;
	function addSecond(){
		if (paused) {
			secondWait = true;
			return;
		}
		time++;
		if (time>3599) time = 3599;
		if (game_mode==2 && time==181) {
			gameOver();
		}
		else {
			var t = game_mode == 2 ? (180-time) : time;
			g('time').innerHTML = niceTime(t);			
			secondRef = setTimeout(addSecond,1000);
		}
	}
	
	function beginGame(mode){
		game_mode = mode;
		clearField();
		nextType = (Math.random()*7)>>0;
		tetra.prepare();
		if (paused) pauseGame();
		timoutRef = setTimeout(loopy, 1000);
		drawCylinder();
		time = -1;
		secondWait = false;
		addSecond();
	}
	
	g('high_form').onsubmit = function(){
		var str = g('high_name').value;
		
		if (!str) return;
	
		g('winner').style.display = 'none';
		g('newgame').style.display = 'block';
		
		var score = game_mode<3 ? lines : time;
		
		for (var i=2; i>=0; i--) {
			if (game_mode<3 && score > best[game_mode-1][i][0] || game_mode==3 && score < best[2][i][0]) {
				if (i<2) {
					best[game_mode-1][i+1][0] = best[game_mode-1][i][0];
					best[game_mode-1][i+1][1] = best[game_mode-1][i][1];
				}
			}
			else break;
		}
		i++;
		best[game_mode-1][i][0] = score;
		best[game_mode-1][i][1] = str;
		
		storeBest();
		displayBest();
		
		g('sorryText').innerHTML = '<DIV style="padding-left:60px;">'+getBestStr(game_mode-1)+'</DIV>';
		
		
		return false;
	}

	document.getElementsByTagName('BODY')[0].style.visibility = 'visible';
	
}
