// layout constants

var SECTION_W = 100;
var SECTION_H = 100;
var BOARD_LEFT = 50;
var BOARD_TOP = 10 + SECTION_H;
var CHIP_WH = 50;
var NUM_ROWS = 8;
var NUM_COLS = 9; // in the row with the greater amt (make sure this number is odd)
var PEG_SIZE = 25;

// increment constants
var LEFT = -1;
var RIGHT = 1;
var LEFT_ODD = -1;
var RIGHT_ODD = 0;
var LEFT_EVEN = 0;
var RIGHT_EVEN = 1;

// border constants
var BORDER_W = 40;
var BORDER_H = SECTION_H * (NUM_ROWS + 1);
// (got rid of the border bottom, but keep these for spacing)
var BORDER_BOTTOM_T = BOARD_TOP + (SECTION_H * (NUM_ROWS + 1));
var BORDER_BOTTOM_L = BOARD_LEFT - BORDER_W;
var BORDER_BOTTOM_W = (NUM_COLS * SECTION_W) + (2*BORDER_W);
var BORDER_BOTTOM_H = 10;

// board total height is from top of screen (plus border bottom, plus the last row)
var BOARD_TOTAL_HEIGHT = BORDER_BOTTOM_T + BORDER_BOTTOM_H + SECTION_H;

// border color
var winRowColor = "#aacccc";

// to keep track of position
var rowOdd = true;
var currentPosR=0;
var currentPosC=0;

// bouncing
var STEPS_UP = 1; 
var STEPS_DOWN = 4;
var PAUSE_START = 200;
var PAUSE = 100;
var DISTANCE_X = (SECTION_W / 2);
var DISTANCE_Y = SECTION_H;
var direction;
var xPos;
var yPos;
var bounceCount;
var bouncingUp = true;
var endpointX;
var endpointY;
var adjustmentY = SECTION_H / (4+3+2);

// game information
var WELCOME_MSG = "Welcome. Press a button above to play.";
var NUM_CHIPS = 5;
var WINNINGS_PREFIX = "Points: ";
var WINNINGS_SUFFIX = "<br />Press a button above to play again.";
var gameTotalWinnings = 0;
var winningsText = WINNINGS_PREFIX + gameTotalWinnings + WINNINGS_SUFFIX;
var numChipsCount = 0;
var readyToPlay = false;
var GAME_OVER = "<b>Game Over</b><br />"

function setupLayout()
{
	// buttons
	for (var i=0; i<NUM_COLS; i++)
	{
		writeButtons(i);
		makeSectionC("play"+ i, -1, i, true, '#ffffff', false);
	}
	
	rowOdd = true;
	// pegs
	for (var r=0; r<NUM_ROWS; r++)
	{
		var COLS = (rowOdd) ? NUM_COLS : NUM_COLS - 1;
		for (var c=0; c<COLS; c++)
		{ 
			var section = "r" + r + "c" + c;
			writePegs(section);
			makeSection(section,r,c,rowOdd);
		}
		rowOdd = !rowOdd;
	}
	
	// last row - payout
	for (var c=0; c<NUM_COLS; c++)
	{
		var winningAmt = getWinningAmt(c);
		var winningAmtImage = findPicForAmt(winningAmt);
	
		var lastrow = "payout" + c;
		writeLastRow(winningAmtImage, SECTION_W, SECTION_H, lastrow);
		makeSectionC(lastrow, NUM_ROWS, c, true, winRowColor, false);
	}
	
	// chip
	writeChip();
	setChipProperties();
	
	// borders
	writeBorders();
	setBordersProperties();
	
	// results
	writeResultLabels();
	setResultLabelsProperties();
	
	// messages
	writeMessageLabel();
	setMessageLabelProperties();
}

function readyToGo()
{
	var startB = document.getElementById('startButton');
	startB.style.display = 'none';
	setupLayout();
	readyToPlay = true;
	showMessageLabel(true, WELCOME_MSG);
	updateInfo();
}

function findPicForAmt(amt)
{
	var picForAmt;
	if (amt==0)
	{
		picForAmt = "../images/plinko0.gif";
	}
	else if (amt==100)
	{
		picForAmt = "../images/plinko100.gif";
	}
	else if (amt==500)
	{
		picForAmt = "../images/plinko500.gif";
	}
	else if (amt==1000)
	{
		picForAmt = "../images/plinko1000.gif";
	}
	else if (amt==5000)
	{
		picForAmt = "../images/plinko5000.gif";
	}
	return picForAmt;
}

function makeSection(section, r, c, rOdd)
{	
	makeSectionC(section, r, c, rOdd, '#cccccc', true);
}

/*
 * makeSectionC
 * param section - name of object
 * param r - row number
 * param c - column number
 * param rOdd - if the row is odd (as opposed to even)
 * param clr - color
 * param isPeg - if this is a peg (the pegs and sections both use this function)
 */
function makeSectionC(section, r, c, rOdd, clr, isPeg)
{
	var rowOfEvenAdj = (rOdd) ? 0 : SECTION_W / 2;

	var baseLeft = BOARD_LEFT + (c * SECTION_W) + rowOfEvenAdj;
	var baseTop = BOARD_TOP + (r * SECTION_H);

	setSectionCProperties(section, baseLeft, baseTop, clr, isPeg);
}

// * * * * * * * * * 
// action logic

function play(col)
{
	if (!readyToPlay)
	{
		return;
	}
	readyToPlay = false;

	showMessageLabel(false, "");

	nextChip();

	currentPosC = col;
	currentPosR = 0;
	var chipLeft = BOARD_LEFT + ((SECTION_W / 2) - (CHIP_WH / 2)) + (currentPosC * SECTION_W);
	var chipTop = BOARD_TOP - CHIP_WH;

	setChipLeft(chipLeft);
	setChipTop(chipTop);

	rowOdd = true; // starting point is a line with five columns

	bouncingUP = true;
	bounceCount = STEPS_UP;

	var pauseS = setTimeout("startDropping()", PAUSE_START);
}

function nextChip()
{
	numChipsCount++;
	updateInfo();
}

function updateInfo()
{
	winningsText = WINNINGS_PREFIX + gameTotalWinnings + WINNINGS_SUFFIX;
	setWinningsText();

	var chipsPic = "";
	for (var i=0; i<(NUM_CHIPS-numChipsCount); i++)
	{
		chipsPic += "* ";
	}

	setChipsRemainingText(chipsPic);
}

function startDropping()
{
	// initial little drop
	moveChipTop(CHIP_WH);

	startOfGame = false;

	var pauseSD = setTimeout("animation()", PAUSE);
}

function animation()
{
	incrY = (bouncingUp) ? (-bounceCount * adjustmentY) : (bounceCount * adjustmentY);

	if (bouncingUp)
	{
		if (bounceCount==STEPS_UP) // first step, need to pick x direction and go to next level
		{
			nextLevel();
		}
		bounceCount--;
	}
	else
	{
		bounceCount++;
	}

	
	if ((!bouncingUp) && (bounceCount >= STEPS_DOWN)) // move to next level
	{
		bouncingUp = true;
		bounceCount = STEPS_UP;

		setChipLeft(endpointX);
		setChipTop(endpointY);

		if (currentPosR >= NUM_ROWS) // done
		{
			gameTotalWinnings += getWinningAmt(currentPosC);
			
			if (numChipsCount+1 > NUM_CHIPS)
			{
				numChipsCount = 0;
				updateInfo(); // update before showing message, to get latest winningsText
				showMessageLabel(true, GAME_OVER + winningsText);
				gameTotalWinnings = 0;
			}
			else
			{
				updateInfo();
			}
			readyToPlay = true;
			return;
		}
	}
	else
	{
		moveChipLeft(incrX);
		moveChipTop(incrY);

		if (bounceCount <= 0)
		{
			bouncingUp = false;
		}
	}

	var pauseAnim = setTimeout("animation()", PAUSE);
}

function nextLevel()
{
	// pick way to move (left or right) for x,y positioning
	var wtm = wayToMove(currentPosC, rowOdd);
	incrX = wtm * (DISTANCE_X / (STEPS_DOWN+STEPS_UP));

	endpointX = getChipLeft() + (wtm * SECTION_W / 2);
	endpointY = getChipTop() + SECTION_H;

	incrY = (-bounceCount * adjustmentY); // starting pt for a bounce, so direction is negative

	currentPosC += direction;
	currentPosR++;

	rowOdd = !rowOdd;
}

function wayToMove(c, rOdd)
{
	if (rOdd)
	{
		if (c<=0)
		{
			direction = RIGHT_ODD;
			return (RIGHT);
		}
		else if (c>=4)
		{
			direction = LEFT_ODD;
			return (LEFT);
		}
	}
	var rand = getRandom(2);

	direction = (rand) ? ((rOdd) ? LEFT_ODD : LEFT_EVEN) : ((rOdd) ? RIGHT_ODD : RIGHT_EVEN);

	var dirMove = (rand) ? LEFT : RIGHT;
	return (dirMove);
}

function getRandom(upperRange)
{
	var rand = Math.random();
	return (Math.floor(rand*(upperRange)));
}

function getWinningAmt(columnX)
{
	// the calculation for the amount to win is optimized for 9 columns
	var refPt = Math.floor(NUM_COLS / 2);
	var winAmt = 0;

	if (columnX==refPt) {	winAmt = 5000; winRowColor = "#FF0000"; }
	else if (columnX==refPt-1 || columnX==refPt+1) { winAmt = 0; winRowColor = "#900000"; }
	else if (columnX==refPt-2 || columnX==refPt+2) { winAmt = 1000; winRowColor = "#FF0000"; }
	else if (columnX==refPt-3 || columnX==refPt+3) { winAmt = 500; winRowColor = "#900000"; }
	else if (columnX==refPt-4 || columnX==refPt+4) { winAmt = 100; winRowColor = "#FF5A13"; }

	return (winAmt);
}

// * * * * * * * * *
// LAYOUT

function writeButtons(i)
{
	var mainDiv = document.getElementById('putStuffHere');
	var buttonDiv = document.createElement('div');
	buttonDiv.setAttribute('align', 'center');
	buttonDiv.setAttribute('style', 'position:absolute');
	buttonDiv.setAttribute('id', 'play' + i);
	var buttonEl = document.createElement('input');
	buttonEl.setAttribute('type', 'button');
	buttonEl.setAttribute('value', '-X-');
	buttonEl.setAttribute('onclick', 'play(' + i + ')');
	buttonEl.style.width = '100';
	buttonDiv.appendChild(buttonEl);
	document.body.appendChild(buttonDiv);
}

function writePegs(section)
{
	var pegDiv = document.createElement('div');
	pegDiv.setAttribute('style', 'position:absolute');
	pegDiv.setAttribute('id', section);
	var imgEl = document.createElement('img');
	imgEl.setAttribute('src', '../images/pixel.gif');
	imgEl.setAttribute('width', '1');
	imgEl.setAttribute('height', '1');
	pegDiv.appendChild(imgEl);
	document.body.appendChild(pegDiv);
}

function writeLastRow(winningAmtImg, width, height, lastrow)
{
	var winningAmt = "<img src='" + winningAmtImg + "' width=" + width + " height=" + height + " border=0>";

	var lastrowDiv = document.createElement('div');
	lastrowDiv.setAttribute('style', 'position:absolute');
	lastrowDiv.setAttribute('id', lastrow);
	var lastrowImage = document.createElement('img');
	lastrowImage.setAttribute('src', winningAmtImg);
	lastrowImage.setAttribute('width', width);
	lastrowImage.setAttribute('height', height);
	lastrowImage.setAttribute('border', '0');
	lastrowDiv.appendChild(lastrowImage);
	document.body.appendChild(lastrowDiv);
}

function writeChip()
{
	var chipDiv = document.createElement('div');
	chipDiv.setAttribute('style', 'position:absolute');
	chipDiv.setAttribute('id', 'chip');
	var chipImage = document.createElement('img');
	chipImage.setAttribute('src', '../images/chip.gif');
	//chipImage.setAttribute('width', '20');
	//chipImage.setAttribute('height', '20');
	chipImage.setAttribute('width', CHIP_WH);
	chipImage.setAttribute('height', CHIP_WH);
	chipDiv.appendChild(chipImage);
	document.body.appendChild(chipDiv);
}

function setChipProperties()
{
	var w = CHIP_WH;
	var h = CHIP_WH;
	var l = BOARD_LEFT + ((SECTION_W / 2) - (CHIP_WH / 2));
	var t = BOARD_TOP - CHIP_WH;

	var el = document.getElementById('chip');
	
	el.style.width = w;
	el.style.height = h;
	el.style.left = l;
	el.style.top = t;
}

function writeBorders()
{
	var bLeftDiv = document.createElement('div');
	bLeftDiv.setAttribute('style', 'position:absolute');
	bLeftDiv.setAttribute('id', 'borderLeft');
	var bLeftImg = document.createElement('img');
	bLeftImg.setAttribute('src', '../images/plinkoBorderL.gif');
	bLeftImg.setAttribute('width', BORDER_W);
	bLeftImg.setAttribute('height', BORDER_H);
	bLeftDiv.appendChild(bLeftImg);
	document.body.appendChild(bLeftDiv);
	
	var bRightDiv = document.createElement('div');
	bRightDiv.setAttribute('style', 'position:absolute');
	bRightDiv.setAttribute('id', 'borderRight');
	var bRightImg = document.createElement('img');
	bRightImg.setAttribute('src', '../images/plinkoBorderR.gif');
	bRightImg.setAttribute('width', BORDER_W);
	bRightImg.setAttribute('height', BORDER_H);
	bRightDiv.appendChild(bRightImg);
	document.body.appendChild(bRightDiv);
}

function setBordersProperties()
{
	var clr = '#cc0000';
	var wL = BORDER_W;
	var hL = SECTION_H * (NUM_ROWS + 1);
	var lL = BOARD_LEFT - BORDER_W;
	var tL = BOARD_TOP;
	var wR = BORDER_W;
	var hR = SECTION_H * (NUM_ROWS + 1);
	var lR = BOARD_LEFT + (NUM_COLS * SECTION_W);
	var tR = BOARD_TOP;

	var elL = document.getElementById('borderLeft');
	var elR = document.getElementById('borderRight');
	
	elL.style.width = wL;
	elL.style.height = hL;
	elL.style.left = lL;
	elL.style.top = tL;
	elR.style.width = wR;
	elR.style.height = hR;
	elR.style.left = lR;
	elR.style.top = tR;

}

function writeResultLabels()
{
	var chipsLeftDiv = document.createElement('div');
	chipsLeftDiv.setAttribute('style', 'position:absolute');
	chipsLeftDiv.setAttribute('id', 'chipsleft');
	var chipsLeftText = document.createTextNode(' ');
	chipsLeftDiv.appendChild(chipsLeftText);
	document.body.appendChild(chipsLeftDiv);
	
	var gwinningsDiv = document.createElement('div');
	gwinningsDiv.setAttribute('style', 'position:absolute');
	gwinningsDiv.setAttribute('id', 'gwinnings');
	var gwinningsText = document.createTextNode(' ');
	gwinningsDiv.appendChild(gwinningsText);
	document.body.appendChild(gwinningsDiv);

}

function setResultLabelsProperties()
{
	var clr = '#ffffff';
	var wL = BORDER_BOTTOM_W / 2;
	var lL = BORDER_BOTTOM_L;
	var tL = BORDER_BOTTOM_T + BORDER_BOTTOM_H;
	var wG = BORDER_BOTTOM_W / 2;
	var lG = BORDER_BOTTOM_L + (BORDER_BOTTOM_W / 2);
	var tG = BORDER_BOTTOM_T + BORDER_BOTTOM_H;

	var elL = document.getElementById('chipsleft');
	var elG = document.getElementById('gwinnings');
	
	elL.style.width = wL;
	elL.style.backgroundColor = clr;
	elL.style.left = lL;
	elL.style.top = tL;
	elL.style.fontSize = '4em';
	elG.style.width = wG;
	elG.style.backgroundColor = clr;
	elG.style.left = lG;
	elG.style.top = tG;
	elG.style.fontSize = '4em';

}

function writeMessageLabel()
{
	var msgLabelDiv = document.createElement('div');
	msgLabelDiv.setAttribute('style', 'position:absolute');
	msgLabelDiv.setAttribute('id', 'messageLabel');
	msgLabelDiv.style.fontSize = '4em';
	msgLabelDiv.style.textAlign = 'center';
	var msgLabelText = document.createTextNode('...STILL LOADING...');
	msgLabelDiv.appendChild(msgLabelText);
	document.body.appendChild(msgLabelDiv);
}

function setMessageLabelProperties()
{
	var z = 2;
	var clr = '#ffffff';
	var w = BORDER_BOTTOM_W / 2;
	var h = BORDER_H - SECTION_H;
	var l = BORDER_BOTTOM_L + (BORDER_BOTTOM_W / 4);
	var t = BOARD_TOP;
	
	var el = document.getElementById('messageLabel');
	
	el.style.zIndex = z;
	el.style.backgroundColor = clr;
	el.style.width = w;
	el.style.height = h;
	el.style.left = l;
	el.style.top = t;
}

function setSectionCProperties(section, baseLeft, baseTop, clr, isPeg)
{
	var w = (isPeg) ? PEG_SIZE : SECTION_W;
	var h = (isPeg) ? PEG_SIZE : SECTION_H;
	var l = (isPeg) ? baseLeft + (SECTION_W / 2) : baseLeft;
	var t = (isPeg) ? baseTop + (SECTION_H / 2) : baseTop;

	var el = document.getElementById(section);
	
	el.style.width = w;
	el.style.height = h;
	el.style.left = l;
	el.style.top = t;
	el.style.backgroundColor = clr;
}

// * * * * * * * * * * * * 
// ACTION

function getChipLeft()
{
	var chipL = 0;
	var el = document.getElementById('chip');
	// left has the number and 'px' in it
	chipL = parseFloat(el.style.left);

	return chipL;
}

function getChipTop()
{
	var chipT = 0;
	var el = document.getElementById('chip');
	// top has the number and 'px' in it
	chipT = parseFloat(el.style.top);

	return chipT;
}

function setChipLeft(chipLeft)
{
	var el = document.getElementById('chip');
	el.style.left = chipLeft;
}

function setChipTop(chipTop)
{
	var el = document.getElementById('chip');
	el.style.top = chipTop;
}

function moveChipLeft(incrChipLeft)
{
	var el = document.getElementById('chip');
	// left has the number and 'px' in it
	el.style.left = parseFloat(el.style.left) + incrChipLeft;
}

function moveChipTop(incrChipTop)
{
	var el = document.getElementById('chip');
	
	// top has the number and 'px' in it
	el.style.top = parseFloat(el.style.top) + incrChipTop;
}

function setWinningsText()
{
	var newString = gameTotalWinnings;
	var el = document.getElementById('gwinnings');
	el.innerHTML = newString;

}

function setChipsRemainingText(chipsPic)
{
	var newString = chipsPic;

	var el = document.getElementById('chipsleft');
	el.innerHTML = newString;

}

function showMessageLabel(isShow, msg)
{
	var el = document.getElementById('messageLabel');
	el.innerHTML = msg;
	el.style.visibility = (isShow) ? 'visible' : 'hidden';

}

