var	lastX1;
var lastY1;
var lastX2;
var lastY2;
var numBoxes=6.0;
var dotoffset=2.0;
var dotsize=4.0;
var offset;
var boxSize;
var lineLength;
var lineArray=new Array();
var yPositions=new Array();
var xPositions=new Array();
var whoseTurn=0;
var	xAbsStart;
var	yAbsStart;
var	xAbsEnd;
var	yAbsEnd;
var	xGridStart;
var	xGridEnd;
var	yGridStart;
var	yGridEnd;
var currentVLine=-99;
var currentHLine=-99;
var row=-99;
var col=-99;
var player1score;
var player0score;
var winner=-99;
var gameOver=false;
var arrow1on=false;
var arrow0on=false;
var computerTurn;
var level=1;
var savedLevel=1;
var gameinprogress;
var modeSet=false;
var gameCount=0;
//var computerGoAgain=false;
//var badmove=false;

function initLineArrays(){
	for (var y=0; y<((numBoxes*2)+1); y++){
		lineArray[y]=new Array(numBoxes+1);
		for (var z=0; z<(numBoxes+1); z++){
			lineArrayFalse(y,z);
		}
	}
}

function setWinner(){
	if (player1score > player0score){
		winner = 1;
	}
	else if (player0score > player1score){
		winner = 0;
	}
	else{
		winner = 2;
	}
}

function checkGameOver(){
	if ((player1score+player0score)===36){
		setWinner();
		gameOver=true;
		return true;
	}
	return false;
}

function lineArrayFalse(row, col){
	lineArray[row][col]=0;
}

function lineArrayTrue(row, col){
	lineArray[row][col]=1;
}

function tagCompleteBoxLine(row, col){
	lineArray[row][col]=2;
}

function updateScore(){
    var player0 = document.getElementById("player0");
	player0.innerHTML=""+player0score;
    var player1 = document.getElementById("player1");
	player1.innerHTML=""+player1score;
}

function drawCenter(a, b, c, d){
    var canvas = document.getElementById("dotgame-board");
    var ctx = canvas.getContext('2d');
	var ballImg = new Image();
	if (whoseTurn === 1){
		ballImg.src= "images/greenball.png";
		player1score++;
	}
	else{
		ballImg.src= "images/blueball.png";
		player0score++;
	}
	ctx.drawImage(ballImg, a, b, c, d);
	ctx.closePath();
	updateScore();
}

function drawPlayer0Arrow(){
	arrow0on=true;
	document.getElementById("arrow0").src="./images/arrow.png";
}

function clearPlayer0Arrow(){
	arrow0on=false;
	document.getElementById("arrow0").src="./images/blank.png";
}

function drawPlayer1Arrow(){
	arrow1on=true;
	document.getElementById("arrow1").src="./images/arrow.png";
}

function clearPlayer1Arrow(){
	arrow1on=false;
	document.getElementById("arrow1").src="./images/blank.png";
}

function switchTurns(){
	if (whoseTurn===1){
		whoseTurn=0;
		drawPlayer0Arrow();
		clearPlayer1Arrow();
	}
	else{
		whoseTurn=1;
		drawPlayer1Arrow();
		clearPlayer0Arrow();
	}
}

function drawBoard(){
    var canvas = document.getElementById("dotgame-board");
    var ctx = canvas.getContext('2d');
	ctx.beginPath();
    ctx.clearRect(0, 0, canvas.width, canvas.height);
	ctx.strokeRect(0, 0, canvas.width, canvas.height);
	boxSize=Math.round( (canvas.width / numBoxes)-2.0);
	lineLength=boxSize-6;
	offset=dotoffset+(dotsize/2);
    // at 320 width the boxSize is 50 ((318 / 6) - 2)
    // 6 boxes * 50 = 300, 316-300 = 16 so offset the centers by 8
    // the rect is 4x4 so its origin is 2 less than the 7 offset
    for(var x = 0; x < numBoxes+1; x++) {
		xPositions[x]=(x*boxSize) + offset;
		for(var y = 0; y < numBoxes+1; y++) {
			ctx.fillRect(x * boxSize + dotoffset, y * boxSize + dotoffset, 4, 4);
			yPositions[y]=(y*boxSize) + offset;
		}
    }
	initLineArrays();
	ctx.closePath();
}

function setLevel(){
	var image;
	if (level===0){
		image = document.getElementById("levelImage");
		image.setAttribute("src", "images/level0.png");
	}
	if (level===1){
		image = document.getElementById("levelImage");
		image.setAttribute("src", "images/level1.png");
	}
	else if (level===2){
		image = document.getElementById("levelImage");
		image.setAttribute("src", "images/level2.png");
	}
	else if (level===3){
		image = document.getElementById("levelImage");
		image.setAttribute("src", "images/level3.png");
	}
}

function updateStatusText(string){
	document.getElementById("text").innerHTML=""+string;
}

function newgame(){
	if (!gameinprogress && modeSet){
		return;
	}
	if (gameinprogress && !gameOver){
		if (!confirm("Are you sure you want to start a new game?")){
			return;
		}
	}
    if(0 === (gameCount % 5)) {
		support();
    }
	gameCount++;
	updateStatusText("Set Player Mode--->");
	clearPlayer0Arrow();
	clearPlayer1Arrow();
	modeSet=false;
	gameinprogress=false;
	savedLevel=level;
	level=0;
	setLevel();
	player0score=0;
	player1score=0;
	updateScore();
	gameOver=false;
	drawBoard();
}

//for debugging purposes
/*
function printLineArray(){
	string="";
	for (var y=0; y<((numBoxes*2)+1); y++){
		string=""+string+y;
		for (var z=0; z<(numBoxes+1); z++){
			string=""+string+lineArray[y][z]+",";
		}
	}
	alert(string);
}
*/
function setGameSettings(){
	if (arrow1on && arrow0on){
		playComputer=false;
		whoseTurn = 0;
	}
	else if (arrow1on){
		playComputer=true;
		computerTurn=0;
		whoseTurn = 1;	//person always goes first, not the computer
	}
	else if (arrow0on){
		playComputer=true;
		computerTurn=1;
		whoseTurn = 0;
	}
}

function checkLineArray(row, col){
//this function checks if there is a line already drawn in a particular spot
	if (lineArray[row][col] === 0){
		//line does not exist, so go ahead and draw it
		return 1;
	}
	else if (lineArray[row][col] === 1){
		//line already exists in this spot
		return 0;
	}
	else if (playComputer && lineArray[row][col]===2){
		if (level>=2 && whoseTurn===computerTurn){
			return 2;
		}
		else{
			return 1;
		}
	}
}

function checkBoxCompleted(){
	if (row === -99 || col === -99){
		return false;
	}
	var box1Drawn=false;
	var box2Drawn=false;
	var a = row;	//0-12
	var b = col;	//0-6
	
	//if vertical line, row will be odd
	if (a%2!==0){
		if (a>0 && a<12){
			if (b<6){
				//box to right of vertical line
				box1Drawn = checkRightVertical();
			}
			if (b>0){
				//box to left of vertical line
				box2Drawn = checkLeftVertical();
			}
		}
	}
	//else if horizontal line, row will be even
	else {
		if (b>0){
			if (a>1){
				//box to top of horizontal line
				box1Drawn = checkTopHorizontal();
			}
			if (a<11){
				//box to bottom of horizontal line
				box2Drawn = checkBottomHorizontal();
			}
		}
	}
	if (box1Drawn || box2Drawn){
		return true;
	}
	return false;
}

function checkRightVertical(){
	var linesForBox=0;
	var a = row;	//0-12
	var b = col;	//0-6
	var boxDrawn=false;
	var imgsize=boxSize-10;
	var imgoffset=5;
	var tagX;
	var tagY;
	if (checkLineArray(a-1, b+1) == 0){
		linesForBox++;
	}
	else if (playComputer){
		tagX=a-1;
		tagY=b+1;
	}
	if (checkLineArray(a, b+1) == 0){
		linesForBox++;
	}
	else if (playComputer){
		tagX=a;
		tagY=b+1;
	}
	if (checkLineArray(a+1, b+1) == 0){
		linesForBox++;
	}
	else if (playComputer){
		tagX=a+1;
		tagY=b+1;
	}
	if (linesForBox == 3){
		drawCenter(xPositions[xGridStart]+imgoffset, yAbsStart+imgoffset, imgsize, imgsize);
		boxDrawn=true;
	}
	else if (linesForBox == 2 && playComputer){
		//put tag for computer info
		tagCompleteBoxLine(tagX, tagY);
	}
	return boxDrawn;
}

function checkLeftVertical(){
	var linesForBox=0;
	var a = row;	//0-12
	var b = col;	//0-6
	var boxDrawn=false;
	var imgsize=boxSize-10;
	var imgoffset=5;
	var tagX;
	var tagY;
	if (checkLineArray(a-1, b) == 0){
		linesForBox++;
	}
	else if (playComputer){
		tagX=a-1;
		tagY=b;
	}
	if (checkLineArray(a, b-1) == 0){
		linesForBox++;
	}
	else if (playComputer){
		tagX=a;
		tagY=b-1;
	}
	if (checkLineArray(a+1, b) == 0){
		linesForBox++;
	}
	else if (playComputer){
		tagX=a+1;
		tagY=b;
	}
	if (linesForBox == 3){
		//alert("drawcenter left");
		drawCenter(xPositions[(xGridStart-1)]+imgoffset, yAbsStart+imgoffset, imgsize, imgsize);
		boxDrawn=true;
	}
	else if (linesForBox == 2 && playComputer){
		//put tag for computer info
		tagCompleteBoxLine(tagX, tagY);
	}
	return boxDrawn;
}

function checkTopHorizontal(){
	var linesForBox=0;
	var a = row;	//0-12
	var b = col;	//0-6
	var boxDrawn=false;
	var imgsize=boxSize-10;
	var imgoffset=5;
	var tagX;
	var tagY;
	if (checkLineArray(a-2, b) == 0){
		linesForBox++;
	}
	else if (playComputer){
		tagX=a-2;
		tagY=b;
	}
	if (checkLineArray(a-1, b) == 0){
		linesForBox++;
	}
	else if (playComputer){
		tagX=a-1;
		tagY=b;
	}
	if (checkLineArray(a-1, b-1) == 0){
		linesForBox++;
	}
	else if (playComputer){
		tagX=a-1;
		tagY=b-1;
	}
	if (linesForBox == 3){
		drawCenter(xAbsStart+imgoffset, yPositions[yGridStart-1]+imgoffset, imgsize, imgsize);
		boxDrawn=true;
	}
	else if (linesForBox == 2 && playComputer){
		//put tag for computer info
		tagCompleteBoxLine(tagX, tagY);
	}
	return boxDrawn;
}

function checkBottomHorizontal(){
	var linesForBox=0;
	var a = row;	//0-12
	var b = col;	//0-6
	var boxDrawn=false;
	var imgsize=boxSize-10;
	var imgoffset=5;
	var tagX;
	var tagY;
	if (checkLineArray(a+1, b-1) == 0){
		linesForBox++;
	}
	else if (playComputer){
		tagX=a+1;
		tagY=b-1;
	}
	if (checkLineArray(a+1, b) == 0){
		linesForBox++;
	}
	else if (playComputer){
		tagX=a+1;
		tagY=b;
	}
	if (checkLineArray(a+2, b) == 0){
		linesForBox++;
	}
	else if (playComputer){
		tagX=a+2;
		tagY=b;
	}
	if (linesForBox == 3){
		drawCenter(xAbsStart+imgoffset, yPositions[yGridStart]+imgoffset, imgsize, imgsize);
		boxDrawn=true;
	}
	else if (linesForBox == 2 && playComputer){
		//put tag for computer info
		tagCompleteBoxLine(tagX, tagY);
	}
	return boxDrawn;
}

function setGridXY(x1, y1, x2, y2){
	xGridStart = x1;
	yGridStart = y1;
	xGridEnd = x2;
	yGridEnd = y2;
}

function setAbsoluteXY(x1, y1, x2,  y2){
	xAbsStart = xPositions[x1];
	yAbsStart = yPositions[y1];
	xAbsEnd = xPositions[x2];
	yAbsEnd = yPositions[y2];
}

function findLine(){
	var compare1;
	var compare2;
	var direction;
	var theXGrid=-99;
	var theYGrid=-99;
	var xClick = window.event.clientX-10;
	var yClick = window.event.clientY-10;
	
	if (xClick<0){
		xClick=0;
	}
	else if (xClick>304){
		xClick=304;
	}
	if (yClick<0){
		yClick=0;
	}
	else if (yClick>304){
		yClick=304;
	}
	
	var x1=-99;
	var x2=-99;
	for (var x=0; x<=numBoxes; x++){
		var closestX = xPositions[x];
		if (Math.abs(xClick-closestX)<=boxSize){
			if (x1===-99){
				x1=x;
			}
			else if (x2===-99){
				x2=x;
			}
		}
	}
	var y1=-99;
	var y2=-99;
	for (var y=0; y<=numBoxes; y++){
		var closestY = yPositions[y];
		if (Math.abs(yClick-closestY)<=boxSize){
			if (y1===-99){
				y1=y;
			}
			else if (y2===-99){
				y2=y;
			}
		}
	}
	if (x2!==-99 && y2!==-99){
		var a1=Math.abs(xClick-xPositions[x1]);
		var a2=Math.abs(xClick-xPositions[x2]);
		var b1=Math.abs(yClick-yPositions[y1]);
		var b2=Math.abs(yClick-yPositions[y2]);
		var tolerance = boxSize/4;

		if (a1<tolerance){
			theXGrid = x1;
			compare1 = a1;
		}
		else if (a2<tolerance){
			theXGrid = x2;
			compare1 = a2;
		}
		if (b1<tolerance){
			theYGrid = y1;
			compare2 = b1;
		}
		else if (b2<tolerance){
			theYGrid = y2;
			compare2 = b2;
		}
		if (theXGrid === -99 && theYGrid === -99){
			return false;
		}
		else if (theXGrid !== -99 && theYGrid !== -99){
			//clicked close to the dot, need to decide which way to go
			if (compare1<compare2){
				theYGrid = -99;
			}
			else{
				theXGrid = -99;
			}
		}
	}
	else if (x2===-99){
		x2=x1;
		theXGrid=x1;
		//must be a vertical line
	}
	else if (y2===-99){
		y2=y1;
		theYGrid=y1;
		//must be a horizontal line
	}
	if (theXGrid !== -99 || x1===x2){
		//vertical line
		if (y1===y2){
			y2=y1+1;
		}
		setAbsoluteXY(theXGrid, y1, theXGrid, y2);
		setGridXY(theXGrid, y1, theXGrid, y2);
		direction = 1;
	}
	else if (theYGrid !== -99 || y1===y2){
		//horizontal line
		if (x1===x2){
			x2=x1+1;
		}
		setAbsoluteXY(x1, theYGrid, x2,  theYGrid);
		setGridXY(x1, theYGrid, x2, theYGrid);
		direction = 0;
	}
	return setLineArray(direction);
}

function matrixToAbsolute(row, col){
	var gridx1;
	var gridx2;
	var gridy2;
	var gridy1;
	var direction;
//opposite of setlinearray
	if (row%2 !== 0){
		//vertical line
		gridx1=col;
		gridx2=col;
		gridy2=(row+1)/2;
		gridy1=gridy2-1;
		direction = 1;
	}
	else{
		//horizontal line
		gridx2=col;
		gridx1=gridx2-1;
		gridy1=row/2;
		gridy2=row/2;
		direction = 0;
	}
	setAbsoluteXY(gridx1, gridy1, gridx2, gridy2);
	setGridXY(gridx1, gridy1, gridx2, gridy2);
	return direction;
}

function computerLevel1(){
	var computerRow = Math.round(Math.random() * 12);
	var computerCol = Math.round(Math.random() * 6);
	
	//odd row #s do not have a column #0
	if (computerRow%2 === 0){
		while (computerCol === 0){
			computerCol = Math.round(Math.random() * 6);
		}
	}
	
	//need to find a row & col combination that doesn't have a line already drawn
	while(checkLineArray(computerRow, computerCol) == 0){
		computerRow = Math.round(Math.random() * 12);
		computerCol = Math.round(Math.random() * 6);
		//odd row #s do not have a column #0
		if (computerRow%2 === 0){
			while (computerCol === 0){
				computerCol = Math.round(Math.random() * 6);
			}
		}
	}
	var direction = matrixToAbsolute(computerRow, computerCol);
/*	if (level == 3 && (whoseTurn == computerTurn)){
		var x = checkBoxCompleted();
		if (badmove){
			alert("bad move");
			badmove=false;
			computerLevel1();
		}
	}*/
	setLineArray(direction);
	drawAndCleanup();
}

function computerLevel2(){
	var lineDrawn = false;
	for (var x=0; x<((numBoxes*2)+1); x++){
		for (var y=0; y<(numBoxes+1); y++){
			if (checkLineArray(x,y)===2){
				var direction = matrixToAbsolute(x, y);
				setLineArray(direction);
				drawAndCleanup();
				lineDrawn = true;
			}
		}
	}
	if (!lineDrawn){
		computerLevel1();
	}
}

function computerLevel3(){
	computerLevel2();
}

function computerMove(){
	if (level===1){
		computerLevel1();
	}
	else if (level===2){
		computerLevel2();
	}
	else if (level===3){
		computerLevel3();
	}
}

function findALine(){
//	if (gameOver || !modeSet || computerGoAgain){
	if (gameOver || !modeSet){
		return;
	}
	if (!findLine()){
		return;
	}
	drawAndCleanup();
}

function drawAndCleanup(){
	drawLine();
	if (checkBoxCompleted()){
		row=-99;
		col=-99;
		if(checkGameOver()){
			gameOverCleanup();
			return;
		}
		//if (playComputer && (whoseTurn===computerTurn)){
		//	computerGoAgain=true;
		//}
		updateStatusText("Go Again");
	}
	else{
		//computerGoAgain=false;
		gameinprogress=true;
		switchTurns();
	}
	if (playComputer && (whoseTurn===computerTurn)){
		//if (computerGoAgain){
		//	setTimeout('computerMove()', 250);
		//}
		//else{
			computerMove();
		//}
	}
}

function drawLine() {
	updateStatusText("");
    var canvas = document.getElementById("dotgame-board");
    var ctx = canvas.getContext('2d');
	if (whoseTurn === 1){
		ctx.strokeStyle="green";
	}
	else{
		ctx.strokeStyle="blue";
	}

/*	
	//for testing, draws the dot where you click
	var x=window.event.clientX;
	var y=window.event.clientY;
	ctx.fillRect(x-10, y-10, 4, 4);
*/

	ctx.beginPath();
	ctx.moveTo(xAbsStart, yAbsStart);
	ctx.lineTo(xAbsEnd, yAbsEnd);
	ctx.stroke();
	ctx.closePath();
}

function gameOverCleanup(){
	if (winner !== 2){
		if (winner === 0){
			drawPlayer0Arrow();
			clearPlayer1Arrow();
		}
		else{
			drawPlayer1Arrow();
			clearPlayer0Arrow();
		}
		updateStatusText("Game Over");
	}
	else {
		updateStatusText("Game Over - Tie");
		drawPlayer0Arrow();
		drawPlayer1Arrow();
	}
}

function changeLevel(){
	if (!playComputer){
		return;
	}
	level++;
	//if (level>3){
	if (level>2){
		level=1;
	}
	setLevel();
}

function restoreLevel(){
	if (level===0){
		if (savedLevel===0){
			savedLevel=1;
		}
		level=savedLevel;
	}
}

function updatePlayerStatusText(){
	if (arrow1on && arrow0on){
		playComputer=false;
		updateStatusText("2 Player Mode");
		savedLevel=level;
		level=0;
		setLevel();
		modeSet=true;
	}
	else if (!arrow1on && !arrow0on){
		playComputer=false;
		updateStatusText("Set Player Mode -->");
		savedLevel=level;
		level=0;
		setLevel();
		modeSet=false;
	}
	else{
		if (arrow1on){
			updateStatusText("Green vs. Computer");
			restoreLevel();
			setLevel();
		}
		else{
			updateStatusText("Blue vs. Computer");
			restoreLevel();
			setLevel();
		}
		playComputer=true;
		modeSet=true;
	}
}

function togglePlayer0Arrow(){
	if (gameinprogress){
		return;
	}
	if (arrow0on){
		clearPlayer0Arrow();
	}
	else{
		drawPlayer0Arrow();
	}
	setGameSettings();
	updatePlayerStatusText();
}

function togglePlayer1Arrow(){
	if (gameinprogress){
		return;
	}
	if (arrow1on){
		clearPlayer1Arrow();
	}
	else{
		drawPlayer1Arrow();
	}
	setGameSettings();
	updatePlayerStatusText();
}

function setLineArray(num){
	var whichRow;
	var whichCol;
	var drawlineOK;
	//lineArray[a][b]
	if (num===1){
		//if vertical line, 'a' is x=Math.max(yGridEnd, yGridStart), (x*2)-1, 'b' is xGridEnd
		whichRow = yGridEnd + yGridStart;
		whichCol = xGridEnd;
		drawlineOK = checkLineArray(whichRow, whichCol);
		if (drawlineOK == 1 || (drawlineOK == 2 && level>=2 && whoseTurn == computerTurn)){
			row = whichRow;
			col = whichCol;
			lineArrayTrue(whichRow, whichCol);
		}
	}
	else{
		//if horizontal line, 'a' is (yGridEnd*2), 'b' is Math.max(xGridEnd, xGridStart) 
		whichRow = (yGridEnd*2);
		whichCol = Math.max(xGridEnd, xGridStart);
		drawlineOK = checkLineArray(whichRow, whichCol);
		if (drawlineOK == 1 || (drawlineOK == 2 && level>=2 && whoseTurn == computerTurn)){
			row = whichRow;
			col = whichCol;
			lineArrayTrue(whichRow, whichCol);
		}
	}
	return drawlineOK;
}

function changeToGrid(num){
	return(Math.round((num-offset)/boxSize));
}

/*
function drawGrid(){
    var canvas = document.getElementById("dotgame-board");
    var ctx = canvas.getContext('2d');
	ctx.strokeStyle="yellow";
	ctx.beginPath();
	for (var x=0; x<=numBoxes; x++){
		var xBegin = xPositions[x];
		var yBegin = yPositions[0];
		var yEnd = yPositions[6];
		ctx.moveTo(xBegin, yBegin);
		ctx.lineTo(xBegin, yEnd);
		ctx.stroke();
		ctx.closePath();
	}
	for (var x=0; x<=numBoxes; x++){
		var yBegin = yPositions[x];
		var xBegin = xPositions[0];
		var xEnd = xPositions[6];
		ctx.moveTo(xBegin, yBegin);
		ctx.lineTo(xEnd, yBegin);
		ctx.stroke();
		ctx.closePath();
	}
}
*/

/////// GOOGLE AD, ETC. STUFF ////////

function support() {
    showAdd();
}

function closeSupport() {
    hideAdd();
	document.getElementById("container").style.visibility="visible";
}

