<html>
	<head>
		<meta name="viewport" content="width=device-width, initial-scale=1">
  		<title>That's Life</title>
		<style>
			body { margin: 0;
					background-color: #f0f0f0;
			}
			canvas { width: 100%; height: 100% }

			#ex1Slider .slider-selection { 
				background: #009900;
			}
			#ex1Slider {
				margin-left: 10px;
				margin-right: 10px;
			}
			.modal-header, h4, .close {
				background-color: #5cb85c;
				color:white !important;
				text-align: center;
				font-size: 30px;
			}
			.modal-footer {
				background-color: #f9f9f9;
			}
			#myModal {
				margin-top: 75px;
			}
			div.game {
				overflow: hidden;
			}
			#control-panel {
				padding-top: 20px;
				padding-bottom: 5px;
				background-color: #bbbbbb;

			}
			#animate-button.active {
				background-color: #009900
			}
			body {
			}
			body, html { height: 100%; }

		</style>
		<!-- Latest compiled and minified CSS -->
		<link rel="stylesheet" href="css/bootstrap.min.css">
		<!-- Optional theme -->
		<link rel="stylesheet" href="css/bootstrap-theme.min.css">
	    <link rel="stylesheet" href="css/bootstrap-slider.css">
	</head>
	<body>
		<script src="js/jquery.min.js"></script>
		<script src="js/bootstrap.min.js"></script>
		<script src="js/bootstrap-slider.min.js"></script>
		
		<div class="game">
			<div id="control-panel">
				<p class="text-center">
					<button id="step-button" type="button" title="Step one generation" class="btn btn-default" aria-label="Left Align">
					  <span class="glyphicon glyphicon-step-forward" aria-hidden="true"></span>
					</button>
					<button id="play-button" type="button" title="Play/Pause" class="btn btn-default" aria-label="Left Align">
					  <span id="play-button-glyph" class="glyphicon glyphicon-play" aria-hidden="true"></span>
					</button>
					<button id="animate-button" type="button" title="Toggle rendering while playing" class="btn btn-default active" aria-label="Left Align">
					  <span id="animate-button-glyph" class="glyphicon glyphicon-facetime-video" aria-hidden="true"></span>
					</button>
					<button id="clear-button" type="button" title="Clear board" class="btn btn-default" aria-label="Left Align">
					  <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
					</button>
					<button id="reset-button" data-toggle="button" type="button" title="Reset board to default configuration" class="btn btn-default" aria-label="Left Align">
					  <span class="glyphicon glyphicon-repeat" aria-hidden="true"></span>
					</button>
					<!--
					<button type="button" class="btn btn-default" title="Compress Memory" aria-label="Left Align" onclick="compressBoard()">
		                <span id="compress-button" class="glyphicon glyphicon-compressed" aria-hidden="true"></span>
		            </button>
		            -->
					<span id="render-kind" class="btn-group btn-group-sm" role="group" aria-label="...">
					  <button title="Choose WebGL renderer - faster, but less stable" id="render-kind-webgl" type="button" class="btn btn-default">WebGL</button>
					  <button title="Choose Canvas renderer - slower, but more stable" id="render-kind-canvas" type="button" class="btn btn-default active">Canvas</button>
					</span>
		            <span title="Play Speed">
						<input id="ex1" data-slider-id='ex1Slider' type="text" data-slider-min="-1000" data-slider-max="0" data-slider-step="50" data-slider-value="0"/>
					</span>
					<button id="help-button" type="button" title="Help" class="btn btn-default" aria-label="Left Align">
					  <span class="glyphicon glyphicon-question-sign" aria-hidden="true"></span>
					</button>
					<button id="test-button" type="button" title="Test" class="btn btn-default" aria-label="Left Align">
					  <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
					</button>
		   		</p>
				<p id='status-field' class="text-center">Status</p>
				<p class="text-center"><small><a href="https://github.com/esscbee/thats-life" target="github">That's Life!</a></small></p>
			</div>
			<input style="display:none;" id="fileDialog" type="file" accept=".life,text/plain;charset=utf-8"/>
			<script src="js/three.min.js"></script>
			<script src="js/CanvasRenderer.js"></script>
			<script src="js/Projector.js"></script>
			<script src="js/OrbitControls.js"></script>
			<script src="LIFE.js"></script>
			<script src="ThreeDBoard.js"></script>
			<script src="BoardModel.js"></script>
			<script src="js/test-results.js"></script>
			<script>
				var BOARD_SIZE_Y = 200;
				var BOARD_SIZE_X = 200;
				var board;
				var boardModel;

				var render = function() {
					if(board && boardModel)
						board.render();
					// console.log('render!');
				}
				var speedSlider = $('#ex1');
				speedSlider.slider({
					formatter: function(value) {
						if(boardModel) {
							boardModel.setSpeed(-value);
						}
					}
				});
				function isWebGL() {
					var webGL = true;
					var active = $("#render-kind .active");
					if(active.length > 0) {
						webGL = active[0].id == 'render-kind-webgl';
					}
					return webGL;
				}
				function isAnimate() {
					var v = $("#animate-button");
					var ret = true;
					if(v)
						ret = v.hasClass("active");
					return ret;
				}
				function updateAnimate(doAnimate) {
					var anim_button = $("#animate-button");
					if(doAnimate == undefined)
						doAnimate = isAnimate();
					else {
						if(doAnimate) {
							anim_button.addClass("active");
						} else {
							anim_button.removeClass("active");
						}
					}
				}
				function createBoard() {
					var height = $("#control-panel").outerHeight() + 10 ;
					return new LIFE.ThreeDBoard(BOARD_SIZE_X, BOARD_SIZE_Y, window, document, isWebGL(), height);
				}
				function resetBoardModel(reinit) {
					setPlayButtonState(false);
					if(board) {
						var d = board;
						board = undefined;
						d.dispose();
					}
					if(boardModel) {
						var d = boardModel;
						boardModel = undefined;
						d.dispose();
					}
					if(reinit) {
						board = createBoard();
						boardModel = new LIFE.BoardModel(BOARD_SIZE_X, BOARD_SIZE_Y, board, updateStatus);
						boardModel.setSpeed(-speedSlider.slider('getValue'));
						boardModel.updateStatus();
						board.ready();
						boardModel.animate(true);
						play(true);
					}
				}
				function changeRenderer() {
					if(board) {
						var d = board;
						board = undefined;
						d.dispose();
					}
					board = createBoard();
					boardModel.setBoard(board);
					updateAnimate();
					boardModel.updateStatus();
					board.ready();
				}
				function populateBoardModel() {
					var dj = Math.floor(BOARD_SIZE_X * 1.5);
					populateBoardModelN(dj);
				}
				function populateBoardModelN(dj) {
					var startJ = Math.floor((BOARD_SIZE_X - dj) / 2);
					var theI = Math.floor(BOARD_SIZE_Y / 2);
					for(var j = startJ; j < (startJ + dj); j++) {
						boardModel.setCell(j, theI, 1, false);
					}
					boardModel.updateStatus();
				}
				function resetAndPopulateBoardModel() {
					resetBoardModel(true);
					populateBoardModel(true);
				}

				function processKeyEvent(event, turnOn) {
					if(board) {
						board.processKeyEvent(event, turnOn);
					}
				}
				$(window).keydown(function(event){
					processKeyEvent(event, true);
				});
				$(window).keyup(function(event){
					processKeyEvent(event, false);
				});
				

	// window.onresize = function(event) {
				// 	//camera.aspect = window.innerWidth / window.innerHeight;
				// 	//camera.updateProjectionMatrix();
				// 	renderer.setSize( window.innerWidth, window.innerHeight );
				// 	console.log('resize: ' + window.innerWidth + ', ' + window.innerHeight);
				// }
				function displayHelp() {
					alert('help');
				}
				function updateStatus(contents, growth, turnOn) {
					if(growth == undefined) {
						// here have setting to toggle - bit of a hack
						if(contents == 'play') {
							setPlayButtonState(turnOn);
							return;
						}
					}
					var color = 'black';
					if(growth > 0)
						color = 'green';
					else if(growth < 0)
						color = 'red';

					if(contents == undefined)
						contents = '';
					var status = document.getElementById('status-field');
					status.innerHTML = contents;
					status.style.color = color;
				}
				function setPlayButtonState(isPlay) {
					var playButton = document.getElementById("play-button-glyph");
					if(!isPlay) {
						playButton.className = 'glyphicon glyphicon-play';
					} else {
						playButton.className = 'glyphicon glyphicon-pause';
					}

				}
				function play(state, stopGen) {
					if(!board || !boardModel)
						return;
					var newState = !boardModel.playing;
					if(state != undefined)
						newState = state;
					boardModel.play(window, newState, stopGen);
					setPlayButtonState(newState);
					var doAnimate = !newState || isAnimate();
					boardModel.animate(doAnimate);
				}
				function doStep() {
					if(!board || !boardModel)
						return;
					if(boardModel.playing) {
						play(false);
						return;
					}
					boardModel.generate(true);
				}
				// function editNavToggle(setting) {
				// 	if(!board)
				// 		return;
				// 	var navEditButton = document.getElementById("edit-nav-button");
				// 	if(!board.navEditToggle(setting)) {
				// 		navEditButton.className = 'glyphicon glyphicon-screenshot';
				// 	} else {
				// 		navEditButton.className = 'glyphicon glyphicon-pencil';
				// 	}
				// }
				function compressBoard() {
					if(!boardModel) {
						boardModel.compressBoard();
					}
				}
				$(document).ready(function() {
					resetAndPopulateBoardModel();
				    if(board) {
				    	board.ready();
				    }
					$("#help-button").click(function() {
						$("#myModal").modal();
						$("#myModal").on('hidden.bs.modal', function () {
					    });
					});
					$("#reset-button").click(function() {
						resetAndPopulateBoardModel(true);
					});

					$("#step-button").click(function() {
						doStep();
					});
					$("#play-button").click(function() {
						play();
					});
					$("#clear-button").click(function() {
						resetBoardModel(true);
					});
					$("#render-kind .btn").click(function(event) {
						console.log(event.currentTarget.id);
						$("#render-kind .btn").removeClass('active');
						$(event.currentTarget).addClass('active');
						changeRenderer();

					});
					$("#animate-button").click(function(event) {
						if(!This)
							return;
						var a = !isAnimate();
						updateAnimate(a);
						if(boardModel.playing)
							boardModel.animate(a);
						else
							boardModel.animate(true);
					});
					$("#test-button").click(function(event) {
						initializeTests();
						resetBoardModel(true);
						populateBoardModelN(200);
						updateAnimate(true);
						var processedOuter = false;
						play(true, function(gen) {
							var testNum = 0;
							var results;
							var errors = "";
							if(gen <= 10 || processedOuter)
								return;
							processedOuter = true;
							// play(false);
							results = boardModel.getState();
							var theseErrors = checkResults(testNum, results);
							if(theseErrors && theseErrors.length) {
								errors = 'Test: ' + testNum + ' failed:\n' + theseErrors;
							}
							results = board.getState();
							theseErrors = checkResults(++testNum, results);
							if(theseErrors && theseErrors.length) {
								if(errors.length)
									errors += '\n';
								errors = 'Test: ' + testNum + ' failed:\n' + theseErrors;
							}
							updateAnimate(false);
							
							play(true, function(gen) {
								if(gen <= 100)
									return;
								play(false);
								updateAnimate(true);
								results = boardModel.getState();
								var theseErrors = checkResults(++testNum, results);
								if(theseErrors && theseErrors.length) {
									errors = 'Test: ' + testNum + ' failed:\n' + theseErrors;
								}
								results = board.getState();
								theseErrors = checkResults(++testNum, results);
								if(theseErrors && theseErrors.length) {
									if(errors.length)
										errors += '\n';
									errors = 'Test: ' + testNum + ' failed:\n' + theseErrors;
								}
								updateAnimate(true);
								if(errors.length) {
									console.log(errors);
								}
							});
						});
					});


				});
			</script>
		</div>
		<div class="container">
			<!-- Modal -->
			<div class="modal fade" id="myModal" role="dialog">
				<div class="modal-dialog">

					<!-- Modal content-->
					<div class="modal-content">
						<div class="modal-header" style="padding:35px 50px;">
							<button type="button" class="close" data-dismiss="modal">&times;</button>
							<h4><span class="glyphicon glyphicon-hdd"></span> That's Life!</h4>
						</div>
						<div class="modal-body" style="padding:40px 50px;">
							<p>This is a javascript / WebGL (on 
								<a target="mrdoob" href="https://github.com/mrdoob/three.js">three.js</a>
								) / 
								<a target="bootstrap" href="http://getbootstrap.com/">bootstrap</a>
								 implementation of 
								<a target="conway" href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">Conway's Game of Life</a>.</p>

							<p>Key Controls: </p>
							<ul>
								<li>Hold down [Space] - Slide Board, mouse to move camera, mouse wheel to zoom</li>
								<li>Hold down [Control] - Turn mouse into erase cursor</li>
								<li>Otherwise use the mouse to draw living cells</li>
							</ul>
							<p><a target="_github" href="https://github.com/esscbee/thats-life">https://github.com/esscbee/thats-life</a>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-success btn-default pull-left" data-dismiss="modal"><span class="glyphicon glyphicon-ok-sign"></span> Ok</button>
						</div>
					</div>
				</div>
			</div> 
		</div>
	</body>
</html>