document.getElementById('canvas').onmousedown = mouseDown;
document.onmousemove = mouseMove;
document.onmouseup = mouseUp;
document.onkeypress = keyPress;

var dragging = 0;

var oldx;
var oldy;
var oldz;

var start_x = 0;
var start_y = 0;
var start_z = 0;

movecounter = 0;

var cameraxtranslate = 0;
var cameraytranslate = 0;

var avatarzrotate = 0;

var screenPos;

function mouseDown(ev){
	if (ev == null) buttonpress = window.event.button;
	else buttonpress = ev.which;
	ev           = ev || window.event;
	var mousePos = mouseCoords(ev);
	screenPos = screenCoords(ev);
	if (buttonpress == 1) {
		var displayinfo = 0;
		var isediting = 0;
		for (var i=0;i<polygonList.length;i++) {
			isediting += polygonList[i].editable;
		}
		if (isediting == 0) {
			for (var i=0;i<polygonList.length;i++) {
				displayinfo += polygonList[i].checkpoint(mousePos.x,mousePos.y,0);
			}
			for (var j=0;j<userslist.length;j++) {
				displayinfo += userslist[j].checkpoint(mousePos.x,mousePos.y,1);
			}
		} else {
			if (handling) checkhandles(mousePos.x,mousePos.y);
			polygonList[editing].checkpoint(mousePos.x,mousePos.y);
			globalvertex = vertexindex;
			oldxyz = Array(polygonList[editing].vertices[globalvertex][0],polygonList[editing].vertices[globalvertex][1],polygonList[editing].vertices[globalvertex][2]);
		}
		if (displayinfo) {
			$('hoverbox').style.display = 'block';
		} else $('hoverbox').style.display = 'none';
	} else {
		dragging = 1;
		start_x = mousePos.x-250;
		start_y = mousePos.y-250;
		startdistance = Math.sqrt((start_x*start_x)+(start_y*start_y));
		if (((250*250)-(start_x*start_x)-(start_y*start_y))<0) {
			start_z = 0;
			start_x = start_x*250/startdistance;
			start_y = start_y*250/startdistance;
		}
		else
			start_z = Math.sqrt((250*250)-(start_x*start_x)-(start_y*start_y));
	}
}

var globalvertex;
var handling = 0;
var axishandle = 0;
var moving = 0;
function checkhandles(x,y) {
	axishandle = 0;
	if (Math.sqrt((x-handles[1][0])*(x-handles[1][0])+(y-handles[1][1])*(y-handles[1][1])) < 10)
		axishandle = 1;
	if (Math.sqrt((x-handles[2][0])*(x-handles[2][0])+(y-handles[2][1])*(y-handles[2][1])) < 10)
		axishandle = 2;
	if (Math.sqrt((x-handles[3][0])*(x-handles[3][0])+(y-handles[3][1])*(y-handles[3][1])) < 10)
		axishandle = 3;
}

function moveagain() {
	moving = 0;
}

function keyPress(e) {
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	if (code == 13 && axishandle != 0) {
		axishandle = 0;
		handling = 0;
	} else if (code == 13 && editing != 0) {
		polygonList[editing].selected = 0;
		polygonList[editing].editable = 0;
		editing = 0;
		globalvertex = 0;
		axishandle = 0;
		handling = 0;
	}
	if (code == 37 && editing == 0) {
		avatarzrotate += .2;
		polygonList[0].vertices[0] = vertexMultiply(rotatezmatrix(avatarzrotate),Array(0,-.25,0,1));
		polygonList[0].vertices[1] = vertexMultiply(rotatezmatrix(avatarzrotate),Array(.25,.25,0,1));
		polygonList[0].vertices[2] = vertexMultiply(rotatezmatrix(avatarzrotate),Array(-.25,.25,0,1));
		$('hoverbox').style.display = 'none';
		if (moving == 0) {
			moving = 1;
	   		var pars = 'worldx=' + globalx + '&worldy=' + globaly + '&username=' + username + '&password=' + password + '&zrotate=' + avatarzrotate;
	   		var reportAjax = new Ajax.Request('reportme.php',{method:'get',parameters:pars,onComplete:moveagain});
		}

	} // Left
	if (code == 38 && editing == 0) {
		movecounter++;
		cameraxtranslate = cameraxtranslate+(Math.sin(avatarzrotate));
		cameraytranslate = cameraytranslate+(Math.cos(avatarzrotate));
		worldtransMatrix = translatematrix(-cameraxtranslate,cameraytranslate,worldtransMatrix[2][3]);
		$('hoverbox').style.display = 'none';
		if (movecounter > 10) {
			loadworld();
			movecounter = 0;
		}
		if (moving == 0) {
			moving = 1;
	   		var pars = 'worldx=' + globalx + '&worldy=' + globaly + '&username=' + username + '&password=' + password + '&zrotate=' + avatarzrotate;
	   		var reportAjax = new Ajax.Request('reportme.php',{method:'get',parameters:pars,onComplete:moveagain});
		}
	} // Up
	if (code == 38 && axishandle != 0) {
		polygonList[editing].vertices[globalvertex][axishandle-1] += .1;
	}
	if (code == 39 && editing == 0) {
		avatarzrotate -= .2;
		polygonList[0].vertices[0] = vertexMultiply(rotatezmatrix(avatarzrotate),Array(0,-.25,0,1));
		polygonList[0].vertices[1] = vertexMultiply(rotatezmatrix(avatarzrotate),Array(.25,.25,0,1));
		polygonList[0].vertices[2] = vertexMultiply(rotatezmatrix(avatarzrotate),Array(-.25,.25,0,1));
		$('hoverbox').style.display = 'none';
	} // Right
	if (code == 40 && axishandle != 0) {
		polygonList[editing].vertices[globalvertex][axishandle-1] -= .1;
	} // Down
	if (code == 97) {
		var myAjax = new Ajax.Request(
			'newmap.js',
			{
				method: 'get',
				onComplete: shownResponse
			});
	}
	if (code == 122) {
		if (camheight > 25)	camheight -= 5;
		camtransMatrix = translatematrix(0,0,camheight);
	} // Z
	if (code == 120) {
		if (camheight < 75) camheight += 5;
		camtransMatrix = translatematrix(0,0,camheight);
	} // X
}

function shownResponse(originalRequest) {
	eval(originalRequest.responseText);

}

function mouseUp(ev){
	if (ev == null) buttonpress = window.event.button;
	else buttonpress = ev.which;
	if (buttonpress != 1) {
		dragging = 0;
    		oldcamrotateMatrix = camrotateMatrix;
	}
}
function mouseMove(ev){
	ev           = ev || window.event;
	var mousePos = mouseCoords(ev);
	if (dragging) {
		var cur_x = mousePos.x-canvaswidth/2;
		var cur_y = mousePos.y-canvaswidth/2;
		var curdistance = Math.sqrt((cur_x*cur_x)+(cur_y*cur_y));
		if (((canvaswidth/2*canvaswidth/2)-(cur_x*cur_x)-(cur_y*cur_y)) < 0) {
			var cur_z = 0;
			cur_x = cur_x*250/curdistance;
			cur_y = cur_y*250/curdistance;
		}
		else
			var cur_z = Math.sqrt((canvaswidth/2*canvaswidth/2)-(cur_x*cur_x)-(cur_y*cur_y));
		nc_x = Math.sqrt(cur_x*cur_x/250/250);
		nc_y = Math.sqrt(cur_y*cur_y/250/250);
		nc_z = Math.sqrt(cur_z*cur_z/250/250);
		if (cur_x < 0) nc_x *= -1;
		if (cur_y < 0) nc_y *= -1;
		cur_vector = Array(cur_x,cur_y,cur_z,1);
		ns_x = Math.sqrt(start_x*start_x/250/250);
		ns_y = Math.sqrt(start_y*start_y/250/250);
		ns_z = Math.sqrt(start_z*start_z/250/250);
		if (start_x < 0) ns_x *= -1;
		if (start_y < 0) ns_y *= -1;
		start_vector = Array(start_x,start_y,start_z,1);
		var distance = Math.sqrt(((cur_x-start_x)*(cur_x-start_x))+((cur_y-start_y)*(cur_y-start_y))+((cur_z-start_z)*(cur_z-start_z)));
		var dotrotate = Math.acos(nc_x*ns_x+nc_y*ns_y+nc_z*ns_z);
		if(axismatrix(crossproduct(cur_vector,start_vector),dotrotate) == 0) {
			start_x = cur_x;
			start_y = cur_y;
			start_z = cur_z;
		}
	}
}

function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX-(document.body.clientWidth-500)/2, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
}

function screenCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
}