GeoTest = window.GeoTest || {};

GeoTest.MAP;
GeoTest.MAP_CSS;
GeoTest.MAP_HACK;
GeoTest.map = {
	ORIGINAL_STYLE: "",
	loaded: false,
	onLoadFocus: false,
	currentPos: [0, 0],
	ANIM_LENGTH: 1.5, // In seconds
	FPS: 60,
	setup: function () {
		var iframe = document.createElement("iframe");
		iframe.src = "worldmap.svg";
		iframe.setAttribute("class", "map")
		iframe.onload = function () {
			GeoTest.map.finishSetup();
		}
		
		GeoTest.MAP = iframe;
		
		var hack = document.createElement("div");
		hack.setAttribute("class", "map-hack");
		
		GeoTest.MAP_HACK = hack;
		
		$("body")[0].appendChild(iframe);
		$("body")[0].appendChild(hack);
	},
	showLatLon: function (lat, lon) {
		return false;
		
		var x = (lon + 180) / 360 * this.viewport[2] - (this.viewport[2] / 2)
		var y = (lat + 90) / 90  * this.viewport[3] - (this.viewport[3] / 2)

		var v = (this.viewport[0] + x) + " " +
		        (this.viewport[1] + y) + " " +
		        (this.viewport[2])     + " " +
		        (this.viewport[3]);
		
		this.currentPos = [lat, lon];
		
		GeoTest.MAP.contentDocument.documentElement.setAttribute("viewBox", v);
	},
	setFocus: function (c, anim) {
		if (this.loaded) {
			var lat = c["lat"];
			var lon = c["lon"];
			
			this.showLatLon(lat, lon);
			
			var css = this.ORIGINAL_STYLE + "." + c["code"] + "{fill:#900}";

			GeoTest.MAP_CSS.firstChild.nodeValue = css;
		} else {
			this.onLoadFocus = c;
		}
	},
	countryChanged: function (country) {
		this.setFocus(country, true);
	},
	finishSetup: function () {
		var iframe = GeoTest.MAP;
		var doc = iframe.contentDocument;
		var body = doc.documentElement;
		this.viewport = body.getAttribute("viewBox").split(" ");
		
		for (var i in GeoTest.map.viewport) {
			this.viewport[i] = parseFloat(this.viewport[i]);
		}
		
		GeoTest.MAP_CSS = doc.getElementById("style_css_sheet");
		this.ORIGINAL_STYLE = GeoTest.MAP_CSS.firstChild.nodeValue;
		
		this.loaded = true;
		if (this.onLoadFocus) this.setFocus(this.onLoadFocus);
	},
	tearDown: function () {
		$(GeoTest.MAP).remove();
		$(GeoTest.MAP_HACK).remove();
	}
}

$(function () {
	if (!GeoTest.data.pref("disableMap")) { GeoTest.map.setup(); }
})

$(function () {
	var toggleLink = document.createElement("a");
	toggleLink.setAttribute("class", "toggle-map");
	toggleLink.appendChild(document.createTextNode("toggle map"));
	
	toggleLink.onclick = function () {
		if (GeoTest.data.pref("disableMap")) {
			GeoTest.data.setPref("disableMap", false);
			GeoTest.map.setup();
		} else {
			GeoTest.data.setPref("disableMap", true);
			GeoTest.map.tearDown();
		}
	}
	
	$("body").append($(toggleLink));
})