/*
  Eindexamen 2008
  Copyright (C) 2008 by Systemantics, Bureau for Informatics

  Lutz Issler
  Mauerstr. 10-12
  52064 Aachen
  GERMANY

  Web:    www.systemantics.net
  Email:  mail@systemantics.net

  Permission granted to use the files associated with this
  website only on your webserver.


  Many thanks to Reko Tiira, who developed the JavaScript
  of http://www.concrete.nl/. His code served as a helpful
  guidance to the Google Maps API. -- LI, 2008-05-20
*/

var zoomLevels = 6;
var maxZoom = 17;
var minZoom = 12;

var mapZoom = minZoom+1;
var regionZoom = mapZoom;
var studentZoom = maxZoom-1;

var tilesWidth = 100;
var tilesHeight = 100;

var mapWidthPx = tilesWidth*256;
var mapHeightPx = tilesHeight*256;

var map;
var mapCenter;

var currentRegion = null;
var currentStudent = null;
var uploadTarget = null;

function load() {
	if (GBrowserIsCompatible()) {
		var copyCollection = new GCopyrightCollection('');
		var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, "");
		copyCollection.addCopyright(copyright);

		var tilelayers = [new GTileLayer(copyCollection, minZoom, maxZoom)];
		tilelayers[0].getTileUrl = function(a,b) {
			var origin = Math.pow(2, b-1);
			var z = maxZoom-b;
			var w = Math.ceil(tilesWidth/Math.pow(2, z));
			var h = Math.ceil(tilesHeight/Math.pow(2, z));
			var x = a.x - origin;
			var y = a.y - origin;
			if (x<0 || y<0 || x>=w || y>=h) {
				return "tiles/black.png";
			} else {
				x %= w;
				y %= h;
				return "tiles/"+b+"_"+x+"_"+y+".png";
			}
		}

		var projection = new GMercatorProjection(maxZoom+1);
		var custommap = new GMapType(tilelayers, projection, "Test", {errorMessage:"No chart data available"});

		map = new GMap2(document.getElementById("map"));
		map.addMapType(custommap);
		map.enableScrollWheelZoom();

		var originPx = projection.fromLatLngToPixel(new GLatLng(0, 0), maxZoom);

		for (var i in mapLinks) {
			mapLinks[i]["pos"] = projection.fromPixelToLatLng(new GPoint(mapLinks[i]["posPx"].x+originPx.x, mapLinks[i]["posPx"].y+originPx.y), maxZoom);
		}

		mapCenter = projection.fromPixelToLatLng(new GPoint(originPx.x+mapWidthPx/2, originPx.y+mapHeightPx/2), maxZoom);
		map.setCenter(mapCenter, mapZoom, custommap);

		map.addControl(new GSmallMapControl(maxZoom-1));
		populateLinks();

		GEvent.addListener(map, "moveend", function() {
			var centerPx = projection.fromLatLngToPixel(map.getCenter(), maxZoom);
			centerPx.x -= originPx.x;
			centerPx.y -= originPx.y;

			// Check for a student
			$("#infobutton").hide();
			currentStudent = null;
			if (map.getZoom()==studentZoom) {
				for (var i in mapLinks) {
					if (Math.abs(mapLinks[i].posPx.x-centerPx.x)<window.innerWidth/2
						&& Math.abs(mapLinks[i].posPx.y-centerPx.y)<window.innerHeight/2) {
						currentStudent = mapLinks[i];
						$("#infobutton").show();
						break;
					}
				}
			}

			centerPx.x -= mapWidthPx/2;
			centerPx.y -= mapHeightPx/2;
			var phi = Math.atan(centerPx.y/centerPx.x);
			if (centerPx.x<=0) {
				phi += Math.PI;
			}
			phi += Math.PI/2;
			var found = false;
			for (i in mapRegions) {
				if (phi>=mapRegions[i].minRad && phi<=mapRegions[i].maxRad) {
					var region = document.getElementById("region_"+i);
					if (currentRegion && currentRegion!=region) {
						$(currentRegion).removeClass("here");
					}
					currentRegion = region;
					$(region).addClass("here");
					found = true;
					break;
				}
			}
		});

		GEvent.addListener(map, "zoomend", function() {
			populateLinks();
		});

		GEvent.addListener(map, "click", function(m) {
			if (m) {
				if (map.getZoom()!=studentZoom) {
					map.setZoom(studentZoom);
				}
				panToStudent(m.link);
			}
		});
	}

	initFileUploads();
}

function createStudentMarker(link, linkIcon) {
	var marker = new GMarker(link.pos, {icon: linkIcon});
	marker.link = link;
	GEvent.addListener(marker, "mouseover", function(a) {
		var pos = map.fromLatLngToContainerPixel(a);
		$("#student")
			.text(link.name)
			.css("left", pos.x+"px")
			.css("top", pos.y+"px")
			.show();
	});
	GEvent.addListener(marker, "mouseout", function() {
		$("#student").hide();
	});
	return marker;
}

function populateLinks() {
	map.clearOverlays();
	var z = maxZoom-map.getZoom();
	var linkIcon = new GIcon();
	linkIcon.image = "elements/link.gif";
	var infoIcon = new GIcon();
	infoIcon.image = "elements/info.gif";
	infoIcon.iconSize = new GSize(39, 18);
	for (var i in mapLinks) {
		linkIcon.iconSize = mapLinks[i].portrait
			? new GSize(600/Math.pow(2,z), 1000/Math.pow(2,z))
			: new GSize(1000/Math.pow(2,z), 600/Math.pow(2,z));
		linkIcon.iconAnchor = new GPoint(linkIcon.iconSize.width/2, linkIcon.iconSize.height/2);
		var marker = createStudentMarker(mapLinks[i], linkIcon);
		mapLinks[i]["marker"] = marker;
		map.addOverlay(marker);
	}
}

function panTo(target, smooth) {
	if (smooth) {
		var projection = map.getCurrentMapType().getProjection();
		var centerPx = projection.fromLatLngToPixel(map.getCenter(), map.getZoom());
		var targetPx = projection.fromLatLngToPixel(target, map.getZoom());
		map.panBy(new GSize(centerPx.x-targetPx.x, centerPx.y-targetPx.y));
	} else {
		map.panTo(target);
	}
}

function panToStudent(link) {
	if (map.getZoom()!=studentZoom) {
		map.setZoom(studentZoom);
	}
	panTo(link.marker.getLatLng(), false);
	hideInfo();
}

var dontHide = true;

function hideInfo() {
	if (dontHide) {
		dontHide = false;
		return;
	}
	$("#menu").show();
	$("#upload").hide();
	$("#progress").hide();
	$("#infolayer")
		.hide()
		.empty()
		.removeClass("student");
}

function showMenu(el) {
	var offset = $(el).offset();
	var parent = $(el.parentNode).offset();
	$(el).children('ul')
		.css("left", (offset.left-parent.left)+"px")
		.css("top", (offset.top-5)+"px")
		.show();
}

function hideMenu(el) {
	$(el).children('ul').hide();
}

function showStudent(link) {
	if (link!=null) {
		$("#student").hide();
		panToStudent(link);
		$("#infolayer")
			.load("student/"+link.id)
			.show();
	}
}

function showText(id) {
	$("#upload").hide();
	$("#progress").hide();
	$("#infolayer").load(id);
	document.getElementById("infolayer").scrollTop = 0;
	$("#infolayer").show();
}

function showIndependentText(id) {
	panToCenter();
	showText(id);
}

function panToRegion(id) {
	if (map.getZoom()!=regionZoom) {
		map.setZoom(regionZoom);
	}
	panTo(mapRegions[id].pos, true);
}

function panToRegionAndHide(id) {
	panToRegion(id);
	hideInfo();
}

function panToCenter() {
	panTo(mapCenter);
	if (currentRegion) {
		$(currentRegion).removeClass("here");
		currentRegion = false;
	}
}

function showUpload(id) {
	uploadTarget = id;
	document.getElementById("target").value = id;
	var file = document.getElementById("file");
	file.value = "";
	$("#upload").show();
}

function beginUpload() {
	$("#upload").hide();
	$("#progress").show();
}

function completeUpload() {
	$("#progress").hide();
	showText(uploadTarget);
}

// The following function is taken from QuirksMode.org.
// It was originally written by Peter-Paul Koch and
// slightly modified for the usage on this site.
function initFileUploads() {
	var fakeFileUpload = document.createElement('div');
	fakeFileUpload.className = 'fakefile';
	fakeFileUpload.appendChild(document.createElement('input'));
	var button = document.createElement('img');
	button.src = 'elements/browse.gif';
	fakeFileUpload.appendChild(button);
	var x = document.getElementsByTagName('input');
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].parentNode.className != 'fileinputs') continue;
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		x[i].onchange = x[i].onmouseout = function () {
			this.relatedElement.value = this.value;
		}
	}
}
