var spotlight1
var doc = new GLGE.Document();

/*
 * Executed when brain.xml is loaded, at the end of this file
 */
doc.onLoad = function() { 
	spotlight1 = doc.getElement("mainlight");
	this.invisible = doc.getElement("mat-clear");

	//create the renderer
	var gameRenderer = new GLGE.Renderer(document.getElementById('canvas'));
	gameScene = new GLGE.Scene();
	gameScene = doc.getElement("mainscene");
	gameRenderer.setScene(gameScene);

	// initialize orbiting parameters	(repeated below!)
	doc.gazeHeight = 8.0;
	doc.dist = 35.0;
	doc.zenith = 1.56;	// angle relative to pole
	doc.azimuth = 1.56; // rotation around pole

	gameScene.camera.setLookat([0,0,doc.gazeHeight]);	// when enabled, defaults to locked gaze
	doc.showInstructions();

	var mouse = new GLGE.MouseInput(document.getElementById('canvas'));
	var keys = new GLGE.KeyInput();
	var mouseovercanvas;

	/*
	 * Support looking around with the mouse 
	 */
	function mouselook(){
		if(!mouseovercanvas) return;

		var camera = gameScene.camera;
		var target = camera.getLookat();

		if (!target) {		// normal walking around
			var mousepos = mouse.getMousePosition();
			mousepos.x = mousepos.x-document.getElementById("container").offsetLeft;
			mousepos.y = mousepos.y-document.getElementById("container").offsetTop;
				
			var camera = gameScene.camera;
			camerarot = camera.getRotation();
			inc = (mousepos.y-(document.getElementById('canvas').offsetHeight/2))/500;

			var trans = GLGE.mulMat4Vec4(camera.getRotMatrix(),[0,0,-1,1]);
			var mag = Math.pow(Math.pow(trans[0],2)+Math.pow(trans[1],2),0.5);
			trans[0] = trans[0]/mag;
			trans[1] = trans[1]/mag;

			camera.setRotX(1.56-trans[1]*inc);
			camera.setRotZ(-trans[0]*inc);
			var width = document.getElementById('canvas').offsetWidth;

			if(mousepos.x<width*0.3){
				var turn = Math.pow((mousepos.x-width*0.3)/(width*0.3),2)*0.05;
				camera.setRotY(camerarot.y+turn);
			}

			if(mousepos.x>width*0.7){
				var turn = Math.pow((mousepos.x-width*0.7)/(width*0.3),2)*0.05;
				camera.setRotY(camerarot.y-turn);
			}
		}
	}

	/*
	 * Check which keys are currently down and act on them.
	 * This is the lookat version.
	 */
	function checkkeys() {
		var camera = gameScene.camera;

		if(keys.isKeyPressed(GLGE.KI_R)) {
			doc.gazeHeight = 8.0;
			doc.dist = 35.0;
			doc.zenith = 1.56;	// angle relative to pole
			doc.azimuth = 1.56; // rotation around pole
			camera.setLookat([0,0,doc.gazeHeight]);
			doc.showInstructions();
		}
			
		var camerapos = camera.getPosition();

		if(keys.isKeyPressed(GLGE.KI_V)) {
			camera.setLookat([0,0,doc.gazeHeight]);
			doc.showInstructions();
		} 

		if(keys.isKeyPressed(GLGE.KI_X)) {
			camera.setLookat('');
			doc.showInstructions();
		}

		var xinc = 0;
		var yinc = 0;
		var zinc = 0;
		var ginc = 0;

		var target = camera.getLookat();
		if (!target) {		// normal walking around
			var camerarot = camera.getRotation();
			var mat = camera.getRotMatrix();
			var trans = GLGE.mulMat4Vec4(mat,[0,0,-1,1]);
			var mag = Math.pow(Math.pow(trans[0],2)+Math.pow(trans[1],2),0.5);
			trans[0] = trans[0]/mag;
			trans[1] = trans[1]/mag;

			if(keys.isKeyPressed(GLGE.KI_W) || keys.isKeyPressed(GLGE.KI_UP_ARROW)) {
				yinc = yinc + parseFloat(trans[1]);
				xinc = xinc + parseFloat(trans[0]);
			}
			if(keys.isKeyPressed(GLGE.KI_S) || keys.isKeyPressed(GLGE.KI_DOWN_ARROW)) {
				yinc = yinc - parseFloat(trans[1]);
				xinc = xinc - parseFloat(trans[0]);
			}
			if(keys.isKeyPressed(GLGE.KI_A) || keys.isKeyPressed(GLGE.KI_LEFT_ARROW)) {
				yinc = yinc + parseFloat(trans[0]);
				xinc = xinc - parseFloat(trans[1]);
			}
			if(keys.isKeyPressed(GLGE.KI_D) || keys.isKeyPressed(GLGE.KI_RIGHT_ARROW)) {
				yinc = yinc - parseFloat(trans[0]);
				xinc = xinc + parseFloat(trans[1]);
			}

			if(levelmap.getHeightAt(camerapos.x+xinc,camerapos.y)>30) xinc = 0;
			if(levelmap.getHeightAt(camerapos.x,camerapos.y+yinc)>30) yinc = 0;

			if(levelmap.getHeightAt(camerapos.x+xinc,camerapos.y+yinc)>30){
				yinc = 0;
				xinc=0;
			} else{
				camera.setLocZ(levelmap.getHeightAt(camerapos.x+xinc,camerapos.y+yinc)+8);
			}

			if(xinc != 0 || yinc != 0){
				camera.setLocY(camerapos.y+yinc);camera.setLocX(camerapos.x+xinc);
			}
		} else {		// orbiting pole
			var epsilon = 0.1;

			if(keys.isKeyPressed(GLGE.KI_W) || keys.isKeyPressed(GLGE.KI_UP_ARROW)) {
				yinc += epsilon;
			}
			if(keys.isKeyPressed(GLGE.KI_S) || keys.isKeyPressed(GLGE.KI_DOWN_ARROW)) {
				yinc -= epsilon;
			}
			if(keys.isKeyPressed(GLGE.KI_A) || keys.isKeyPressed(GLGE.KI_LEFT_ARROW)) {
				xinc -= epsilon;
			}
			if(keys.isKeyPressed(GLGE.KI_D) || keys.isKeyPressed(GLGE.KI_RIGHT_ARROW)) {
				xinc += epsilon;
			}
			if(keys.isKeyPressed(GLGE.KI_Q)) {
				zinc -= epsilon;
			}
			if(keys.isKeyPressed(GLGE.KI_Z)) {
				zinc += epsilon;
			}
			if(keys.isKeyPressed(GLGE.KI_E)) {
				ginc += epsilon;
			}
			if(keys.isKeyPressed(GLGE.KI_C)) {
				ginc -= epsilon;
			}

			var x = target[0];
			var y = target[1];
			var z = target[2];

			doc.dist -= yinc;
			if(doc.dist < 0.0001) doc.dist = 0.0001;

			doc.azimuth += xinc/4;

			doc.zenith += zinc/10;
			if(doc.zenith < 0) doc.zenith = 0.00001;
			if(doc.zenith > 3.14159) doc.zenith = 3.14159;


			doc.gazeHeight += ginc;
			if(doc.gazeHeight < 0) doc.gazeHeight = 0;
			
			x += doc.dist * Math.sin(doc.zenith) * Math.cos(doc.azimuth);
			y += doc.dist * Math.sin(doc.zenith) * Math.sin(doc.azimuth);
			z += doc.dist * Math.cos(doc.zenith);

			doc.dbstr = "x: " + x + " y: " + y + " z: " + z + " gz: " + doc.gazeHeight;

			camera.setLocX(x);
			camera.setLocY(y);
			camera.setLocZ(z);
			camera.setLookat([0,0,doc.gazeHeight]);
		}
	}


	levelmap = new GLGE.HeightMap("images/map2.png",120,120,-50,50,-50,50,0,50);


	var lasttime = 0;
	var frameratebuffer = 60;
	start = parseInt(new Date().getTime());
	var cnt = 0;

	/* 
	 * Render one frame
	 */
	function render() {
		var now = parseInt(new Date().getTime());

		cnt = (cnt+1)%10;
		if(cnt == 0){
			frameratebuffer = Math.round(((frameratebuffer*9)+1000/(now-lasttime))/10);
			document.getElementById("debug").innerHTML = "Frame Rate:"+frameratebuffer;
			 	// +"<br>r: "+doc.dist+" zenith: "+doc.zenith+" azimuth: "+doc.azimuth +
				// " " + doc.dbstr;
		}


		mouselook();
		checkkeys();
		gameRenderer.render();
		lasttime = now;
	}

	/* Start the rendering */
	setInterval(render,1);
	var inc = 0.2;
	document.getElementById("canvas").onmousemove = function(e){mouseovercanvas=true;}
	document.getElementById("canvas").onmouseover = function(e){mouseovercanvas=true;}
	document.getElementById("canvas").onmouseout = function(e){mouseovercanvas=false;}
} 

/*
 * Find the given object(s) and set their visibility.
 */
doc.vis = function(objnames,vis) {
	for (n in objnames) {
		var obj = this.getElement(objnames[n]);
		this.setVisibility(obj,vis);
	}
}

/*
 * Set an object's visibility.  The first time we 
 * encounter an object we save
 * its material as its visible material.
 */
doc.setVisibility = function(obj,vis) {
	if(!obj.hasOwnProperty('visibleMaterial')) {
		obj.visibleMaterial = obj.material;
	}

	if(vis) {
		obj.setMaterial(obj.visibleMaterial);
	} else {
		obj.setMaterial(this.invisible);
	}
}

/*
 * Find the given object and look at it. If 'none'
 * is given, look at nothing.
 */
doc.lookat = function(objname) {
	var camera = gameScene.camera;

	if(objname == "none") {
		camera.setLookat('');
	} else {
		obj = this.getElement(objname);
		camera.setLookat(obj);
	}
}

/*
 * Display the correct instructions
 */
doc.showInstructions = function() {
	var target = gameScene.camera.getLookat();
	if (!target) {		// normal walking around
		document.getElementById("instruct1").innerHTML = "Use the mouse to look around";
		document.getElementById("instruct2").innerHTML = "Use the WASD/arrow keys to walk around";
		document.getElementById("instruct3").innerHTML = "V to lock onto vertical axis, R to reset";
	} else {		// orbiting pole
		document.getElementById("instruct1").innerHTML = "Use the WASD/arrow keys to orbit and approach";
		document.getElementById("instruct2").innerHTML = "Q/Z to change the zenith, E/C to raise/lower view";
		document.getElementById("instruct3").innerHTML = "X to unlock from the vertical axis, R to reset";
	}
}

/*
 * Show load count (hacked into glge.js).  The "please wait" instructions should be displayed
 * when this is called. NOTE: copied code directly into glge.js, this isn't called.
 */
doc.showLoadCount = function(n) {
	document.getElementById("instruct3").innerHTML = "" + n + " objects remain to be loaded";
}



doc.load("brain.xml");

