var numVerts = 12;
var verts = new Array(numVerts);
var width = 0;
var height = 0;
var offset = 0;
var distance = 1;
var vertIndex = 0;
var speed = 2;

var dY = 0;
var maxDY = 5;
var gravity = 0.18;
var thrust = 0;
var x = 1;
var y = 4;

var cavepng = new Image();
cavepng.src = "cave.png";
var maxSlope = maxDY * 2 / 3;
var maxSlopeDy = maxDY *2 ;/// 3;
var slope = 0;
var caveY = 50;
var caveHeight = 50;
var caveOff = 0;

var wormypng = new Image();
wormypng.src = "worm1.png";
var tailLength = x * 5;
var tail = new Array(tailLength);

var score = 0;
var mode = "main";

var wallpng = new Image();
wallpng.src = "paddles.png";
var wallX = 0;
var wallY = 0;
var walls = false;

function setLevel() {
	if (score >= 2000) {
		maxSlopeDy =maxDY * 12;
	} else if (score >= 1500) {
		speed = 8;
		maxSlopeDy =maxDY * 9;
	} else if (score >= 1200) {
		speed = 7;
		maxSlopeDy =maxDY * 7;
	} else if (score >= 700) {
		speed = 5;
		maxSlopeDy =maxDY * 5;
	} else if (score >= 450) {
		walls = true;
		maxSlopeDy =maxDY * 4;
	} else if (score >= 200) {
//		caveHeight = height / 4;
		maxSlopeDy =maxDY * 3;

	} else {
		walls = false;
		maxSlope = maxDY * 2 ;
		maxSlopeDy = maxDY * 2;
//		caveHeight = height / 3;
		speed = 4;
	}
}


function showHelp() {
	var help = document.getElementById('help');
	var main = document.getElementById('main');
	help.style.display = "block";
	main.style.display = "none";
}

function hideHelp() {
	var help = document.getElementById('help');
	var main = document.getElementById('main');
	help.style.display = "none";
	main.style.display = "block";
}

function activate() {
	if (mode == "main") {
		resetGame();
		mode = "play";
		thrust = 1;
		document.getElementById('push').innerHTML = "Up";
		document.getElementById('push').style.height = 60;
		document.getElementById('helpButton').style.display = "none";
	} else {
		thrust = 1;
		dY -= 2;
	}
}

function deactivate() {
	thrust = 0;
}

function moveWormy(newY) {
	for (i =0; i < tailLength-1; i++) {
		tail[i] = tail[i+1];
	}
	tail[i] = newY;
	y = newY;
}

function getContext() {
	var canvas = document.getElementById('cave');
	if (canvas.getContext) {
		return canvas.getContext('2d');
	} else {
		return false;
	}
}

function clearBoard(ctx) {
	ctx.fillStyle = "000";
	ctx.beginPath();
	ctx.moveTo(0,0);
	ctx.lineTo(0,height);
	ctx.lineTo(width,height);
	ctx.lineTo(width,0);
	ctx.closePath();
	ctx.stroke();
	ctx.fill();
}

function createVert() {
	slope += (Math.random() * maxSlopeDy * 2) - maxSlopeDy;

	if (slope < -maxSlope) {
		slope = -maxSlope;
	} else if (slope > maxSlope) {
		slope = maxSlope;
	}

	caveY += slope;

	if (caveY <= 0) {
		slope = 0;
		caveY = 0;
	} else if (caveY + caveHeight >= height) {
		slope = 0;
		caveY = height - caveHeight;
	}
	
	return caveY;
}

function moveBoard() {
	verts[vertIndex] = createVert();
	vertIndex = (vertIndex + 1) % numVerts;
}

function drawBoard() {
	var ctx = getContext();

//	clearBoard(ctx);	
	var wide = 184;
	caveOff = caveOff % (wide * 2);

	xScale = 2;
	x2 =  0 - caveOff / xScale;
	xOrig = wide - x2;
	xWide = (wide-x2) * xScale;

	ctx.drawImage(cavepng, x2, 0, 
				xOrig, 122, 
				0, -50,
				xWide, height);

	ctx.drawImage(cavepng, x2, 0, 
				xOrig, 122, 
				0, 100,
				xWide, height);
	
	if ((wide- xOrig) >= 1 ) {
		ctx.drawImage(cavepng, 0, 0, 
					wide-xOrig, 122, 
					xWide, -50,
					xScale*(wide-xOrig), height);
		ctx.drawImage(cavepng, 0, 0, 
					wide-xOrig, 122, 
					xWide, 100,
					xScale*(wide-xOrig), height);
	}
	// Set up the context settings
	ctx.fillStyle = "#00F";

	ctx.beginPath();
	ctx.moveTo(offset, verts[vertIndex]);
	for (j=0, i=vertIndex; j < numVerts ; i = (i+1) % numVerts, j++ ) {
		ctx.lineTo(offset + distance * j, verts[i]);
	}

	for (j=numVerts, i = vertIndex; j >= 0 ; i = (i-1) % numVerts, j-- ) {
		if (i == -1) { i += numVerts; }
		ctx.lineTo(offset + distance * j, verts[i] + caveHeight);
	}
	ctx.closePath();
	ctx.stroke();
	ctx.fill();

	if (walls) {
		ctx.drawImage(wallpng, 0, 1, 
					3, 13, 
					wallX, wallY,
					6, 16);
	}
}

function drawWormy() {
	var wheight = 5;
	var ctx = getContext();
	ctx.fillStyle = "#bba";
	for (j=0, i = tailLength-5; i < tailLength; j++, i+=1) {
		ctx.beginPath();
		ctx.arc(j*8, tail[i] + 9, wheight, 0, 0.000000000000001, 1);
		ctx.closePath();
		ctx.fill();
	}
	ctx.drawImage(wormypng, 0, 3, 
				10, 9, 
				x*distance, y,
				20, 14);
}

function showMain() {
	// Move the board
	offset = offset - speed;
	caveOff = caveOff - speed;

	while ((distance + offset) <= 0) {
		offset += distance;
		moveBoard();
	}
	
	if (walls) {
		wallX = wallX - speed;
		if ( wallX < -10 ) {
			wallX = width;
			wallY = Math.random()*caveHeight + caveY;
		}
	}
	
	moveWormy( verts[(vertIndex + x) %numVerts] + (caveHeight / 2 - 5) );
	
	drawBoard();
	drawWormy();
}

var http_request;
function checkScores() {
	var url="high_score.js.py";
	var name = document.getElementById("username").value;
	//var parameters = "score=" + score + "&name=" + name;
	var parameters = "name=" + encodeURI(name) +
			 "&score=" + encodeURI(score);

	http_request = new XMLHttpRequest();
	http_request.onreadystatechange = gotScores;
	http_request.open('POST', url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);

	document.getElementById("enterName").style.display = "none";
	document.getElementById("main").style.display = "block";
}

function gotScores() {
	if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            eval(http_request.responseText);
	    var scoreString = "<TABLE style='color: 99ffff;'>";
	    scoreString += "<TR><TD>Place</TD><TD>Name<TD><TD>Score</TD></TR>";
	    for (i=5; i>0; i--) {
		if (name[i]) {
			scoreString += "<TR><TD width='30'>" + (place - i) + ":</TD><TD width='75'>" + name[i] + "<TD><TD width='50'>" + scores[i] + "</TD></TR>";
		}
	    }
	    scoreString += "<TR><TD>"+place+"</TD><TD><B><i>" + name[0] + "</i></B><TD><TD><B>" + scores[0] + "</B></TD></TR>";
	    scoreString += "</table>";
	    var scorePanel = document.getElementById('highScores');
	    scorePanel.innerHTML = scoreString;
	    scorePanel.style.display = "block";

         } else {
//            alert('There was a problem with the request.');
         }
      }
}

function gameDead() {
	mode = "dead";
	thrust = 0;
	document.getElementById('score').innerHTML = "Final Score: " + score;
	moveWormy( y + 6 );

	drawBoard();
	drawWormy();

	//if (tail[0] >= height) {
	if (y >= height) {
		mode = "main";
		document.getElementById('push').innerHTML = "Start";
	}
}

function gameLoop() {
	setLevel();

	// Move Wormy
	if (thrust == 0) {
		dY += gravity;
		if (dY >= maxDY) {
			dY = maxDY;
		}
	} else {
		dY -= gravity;
		if (dY <= -maxDY) {
			dY = -maxDY;
		}
	}
	
	if (walls) {
		wallX = wallX - speed;
		if ( wallX < -10 ) {
			wallX = width;
			wallY = Math.random()*caveHeight + caveY;
		}
	}

	moveWormy( y + dY );

	// Check for Limits
	if (y < 0) { y = 0;}
	else if (y > height) { y = height; }

	// Move the board
	offset = offset - speed;
	caveOff = caveOff - speed;
	while ((distance + offset) <= 0) {
		offset += distance;
		moveBoard();
	}

	if (collisionCheck()) {
		//checkScores();
		document.getElementById('helpButton').style.display = "block";
		document.getElementById("enterName").style.display = "block";
		document.getElementById("main").style.display = "none";
		gameDead();
		return;
	}
	score += speed;

	drawBoard();
	drawWormy();
	
	document.getElementById('score').innerHTML = "Score: " + score;
}

function collisionCheck() {
	if (y < verts[(vertIndex+x+1) %numVerts]) {
		return true;
	} else 	if ( (y + 10)  > (verts[(vertIndex+x+1) %numVerts] + caveHeight) ) {
		return true;
	}

	if ( ((distance*x)-wallX < distance/2) && 
		((distance*x)-wallX > 0) && 
		((y+10) > wallY) && 
		(y < (wallY+14) ) ){
		return true;
	}

	return false;
}

function resetGame() {
	dY = -1.0;
	score = 0;
	wallX = -8;
	setLevel();
	
	var scorePanel = document.getElementById('highScores');
	scorePanel.style.display = "none";
}

function startGame() {
	var canvas = document.getElementById('cave');
	height = canvas.height;
	width = canvas.width;
	distance = width / (numVerts-2);
	caveHeight = height / 3;
	caveY = height / 3;

	//tailLength = Math.round(x * distance);
	tailLength = 8;
	tail = new Array(tailLength);
	for (i = 0; i < tailLength; i++) {
		tail[i]=y;
	} 

	for (i=0; i < numVerts; i++) {
	   verts[i] = createVert();
	}

//    	setTimeout(updateLayout, 100);
	mainLoop();
}

function mainLoop() {
	if (mode == "main") {
		showMain();
	} else if (mode == "play") {
		gameLoop();
	} else if (mode == "dead") {
		gameDead();
	}

	setTimeout("mainLoop()", 75);
}


var currentWidth = 0;
 
function updateLayout()
{
    if (window.innerWidth != currentWidth)
    {
        currentWidth = window.innerWidth;
 
        if (orient = currentWidth == 320) {
		var but = document.getElementById('but');
		but.style.position = "absolute";
		but.style.left = "0px";
		but.style.bottom = "0px";

	} else {
	   //if (orient == "landscape") {
		var but = document.getElementById('but');
		but.style.position = "absolute";
		but.style.left = "350px";
		but.style.bottom = "100px";
	
		var main = document.getElementById('main');
		main.style.position = "absolute";
		main.style.right = "0px";
		main.style.bottom = "0px";
	}

    }
	setTimeout(updateLayout, 500);
}
 

