﻿var xfactor = 90.3899161793616;
var xconstant = 473.651903553916;
var yfactor = -146.669480145419;
var yconstant = 7864.31901493158;

function logPosition() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function (position) {
			$.post("LogPosition.aspx", {
				longitude: position.coords.longitude,
				latitude: position.coords.latitude,
				userID: $.query.get('iam')
			},
			errorHandler);
		});
	}
	else {
		alert("browser returned null for navigator.geolocation");
	}
}

function plotPositions() {
	var drawingCanvas = document.getElementById('canvas');
	// Check the element is in the DOM and the browser supports canvas
	if (drawingCanvas.getContext) {
		// Initaliase a 2-dimensional drawing context
		var context = drawingCanvas.getContext('2d');

		context.clearRect(0, 0, drawingCanvas.width, drawingCanvas.height);

		$.get("GetPositions.aspx", function (data) {
			for (var i = 0; i < data.length; i++) {
				var user = data[i];

				context.lineWidth = 1;

				var xpos = null;
				var ypos = null;
				var drawLine = false;

				for (var j = 0; j < user.Points.length; j++) {

					if (xpos) {
						context.beginPath();
						context.moveTo(xpos, ypos);
						drawLine = true;
					}

					var point = user.Points[j];
					xpos = ((point.Longitude * xfactor) + xconstant);
					ypos = ((point.Latitude * yfactor) + yconstant);

					if (drawLine) {
						context.lineWidth = 2;
						context.strokeStyle = user.Color;
						context.lineTo(xpos, ypos);
						context.stroke();
					}

					context.lineWidth = 1;
					context.strokeStyle = "#000000";
					context.fillStyle = user.Color;
					context.beginPath();
					context.arc(xpos, ypos, 4, 0, Math.PI * 2, true);
					context.closePath();
					context.stroke();
					context.fill();
				}

				var point = user.Points[user.Points.length - 1];
				var xpos = ((point.Longitude * xfactor) + xconstant) + 6;
				var ypos = ((point.Latitude * yfactor) + yconstant);

				context.lineWidth = 2;
				context.strokeStyle = "#000000";
				context.fillStyle = user.Color;
				context.font = "bold 13px sans-serif";
				context.strokeText(user.UserID, xpos, ypos);
				context.fillText(user.UserID, xpos, ypos);
			}
		});
	}
}

function errorHandler(err) {
	plotPositions();
	if (!err || !err.code) return;
	switch (err.code) {
		case 1: alert("Error: Access is denied!"); break;
		case 2: alert("Error: Position is unavailable!"); break;
		default: alert("Error: " + err.code); break;
	}
}

$(function () {
	$('#canvas').click(function () {
		if ($.query.get('iam')) {
			logPosition();
		}
		else {
			plotPositions();
		}
		return false;
	}).click();
});

