var map;
var GICONS;

var conHighlighters = {};
var hlObject = null;
var curObject = null;

function onPageLoad() {

	if (window.videoToShow) {
		showVideo(window.videoToShow);
		window.videoToShow = null;
		// delete(window.videoToShow);
	}
	if (typeof(GBrowserIsCompatible) == 'undefined' || !GBrowserIsCompatible())
		return;

	GSmartRoute.createClass();

	map = new GMap2(document.getElementById("googlemap"));
	map.addControl(new GLargeMapControl());
	map.setCenter(new GLatLng(52.4827802221, 13.447265625), 4);

	GICONS = new GIcons();
	GICONS.addIcon('no', 'no.png');
	GICONS.addIcon('hl', 'hl.png');
	GICONS.addIcon('se', 'se.png');

	if (route)
		$('map_mode_div').style.display="block";
	setMapMode(0);

	window.pageLoaded = true;
}

var mapMode = -1;
function setMapMode(mode) {
	if (mode == mapMode)
		return;
	switch (mode) {
		case 0:
			$('map_mode_0').className = 'highlight';
			$('map_mode_1').className = 'normal';
			mapMode = mode;
			updateInfo(route_page_id);
			collapseBottom();
			break;
		case 1:
			$('map_mode_1').className = 'highlight';
			$('map_mode_0').className = 'normal';
			mapMode = mode;
			break;
	}
	rebuildMap();
}

var autopos = false;
function rebuildMap() {
	map.clearOverlays();
	if (! autopos) {
		autopos = true;
		// calculate bounds and zoom
		var bounds = new GLatLngBounds();
		function extendBounds(route) {
			for (var i = 0; i < route.length; i++) {
				var obj = route[i];
				if (i % 2 == 0) {
					bounds.extend(new GLatLng(obj.lat, obj.lng));
				} else {
					if (obj.points) {
						for (var j = 0; j < obj.points.length; j++) {
							var p = obj.points[j];
							bounds.extend(new GLatLng(p.lat, p.lng));
						}
					}
				}
			}
		}
		if (allRoutes) {
			var r;
			for (r in routes)
				extendBounds(routes[r]);
		} else {
			extendBounds(route);
		}
		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
	}

	if (mapMode == 0) { // display only polyline
		function drawRoutePoly(route) {
			var coords = [];
			for (var i = 0; i < route.length; i++) {
				var obj = route[i];
				if (i % 2 == 0) {
					coords.push(new GLatLng(obj.lat, obj.lng));
					if (obj.branches) {
						for (var j = 0; j < obj.branches.length; j++)
							drawRoutePoly(obj.branches[j]);
					}
				} else {
					if (obj.points) {
						for (var j = 0; j < obj.points.length; j++) {
							var p = obj.points[j];
							coords.push(new GLatLng(p.lat, p.lng));
						}
					}
				}
			}
			var poly = new GPolyline(coords, '#338800', polyWeight, polyOpacity);
			map.addOverlay(poly);
		}
		if (allRoutes) {
			var r;
			for (r in routes)
				drawRoutePoly(routes[r]);
		} else {
			drawRoutePoly(route);
		}
	} else { // display everything - markers, connections, mouseovers, etc
		conHighlighters = {};
		hlObject = null;
		curObject = null;

		// drawing points
		function drawRoutePoints(route) {
			for (var i = 0; i < route.length; i+=2) {
				var obj = route[i];
				if (! obj.hidden)
					addMarker(obj);
				if (obj.branches) {
					for (var j = 0; j < obj.branches.length; j++)
						drawRoutePoints(obj.branches[j]);
				}
			}
		}
		drawRoutePoints(route);

		// adding smart route (image map with links along connections)
		var routeOverlay = new GSmartRoute(route);
		map.addOverlay(routeOverlay);
	}
}

function navToRoute(pid) {
 	allRoutes = false;
	$('map_mode_div').style.display="block";
	if ($('rtlink'+route_page_id))
		$('rtlink'+route_page_id).className = 'normal';
	route = routes[pid];
	mapMode = -1;
	autopos = false;
	route_page_id = pid;
	bottomPid = pid;
	if ($('rtlink'+route_page_id))
		$('rtlink'+route_page_id).className = 'current';
	setMapMode(0);
	updateInfo(pid);
}

function addMarker(obj) {
	var marker = new GMarker(new GLatLng(obj.lat, obj.lng), GICONS.getIcon('no'), mapMode == 0);
	if (mapMode == 1) {
		GEvent.addListener(marker, "click", function () {
			if (curObject !== marker)
				updateInfo(obj.pid);
			objectClick(marker);
		});
		GEvent.addListener(marker, "mouseover", function () {
			objectOver(marker);
		});
		GEvent.addListener(marker, "mouseout", function () {
			objectOut(marker);
		});
		marker.highlight = function(flag) {
			var key;
			switch (flag) {
				case 0: key = 'no'; break;
				case 1: key = 'hl'; break;
				case 2: key = 'se'; break;
			}
			this.setImage(GICONS.getIcon(key).image);
		}
	}
	map.addOverlay(marker);
}

function insertLoading(id) {
	var img = document.createElement('img');
	img.className = 'loading';
	img.src = 'fileadmin/images/loading.gif';
	$(id).insert(img);
}

function updateInfo(pid) {
	insertLoading('content_left');
	var url = 'index.php?id='+pid+'&L='+language_uid+'&ajax=left&slt='+ Math.random();
	bottomPid = pid;
	new Ajax.Request(url, {
		method:'get',
		onSuccess: function(transport) {
			var response = transport.responseText || "no response text";
			$('content_left').update(response);
			collapseBottom();
		},
		onFailure: function(){ alert('Unable to fetch content') }
	});
}

function toggleBottom() {
	if (bottomExpanded) {
		collapseBottom();
	}
	else {
		insertLoading('content_bottom');
		var url = 'index.php?id='+bottomPid+'&L='+language_uid+'&ajax=bottom&slt='+ Math.random();
		new Ajax.Request(url, {
			method:'get',
			onSuccess: function(transport) {
				var response = transport.responseText || "no response text";
				$('content_bottom').update(response);
				$('content_bottom').style.display = 'block';
				// new Effect.SlideDown($('content_bottom'))

				bottomExpanded = true;
			},
			onFailure: function(){ alert('Unable to fetch content') }
		});
	}
}

function collapseBottom() {
	if (! bottomExpanded)
		return;
	// new Effect.SlideUp($('content_bottom'))
	$('content_bottom').update('');
	$('content_bottom').style.display = 'none';
	bottomExpanded = false;
}

function objectOver(obj) {
	if (obj === hlObject || obj === curObject)
		return;
	obj.highlight(1);
	hlObject = obj;
}
function objectOut(obj) {
	if (obj === curObject)
		return;
	obj.highlight(0);
	hlObject = null;
}
function objectClick(obj) {
	if (obj === curObject)
		return;
	if (curObject)
		curObject.highlight(0);
	obj.highlight(2);
	curObject = obj;
}

function connectionOver(conpid) {
	if (mapMode == 0)
		return;
	objectOver(conHighlighters[conpid]);
}
function connectionOut(conpid) {
	if (mapMode == 0)
		return;
	objectOut(conHighlighters[conpid]);
}
function connectionClick(conpid) {
	if (mapMode == 0)
		return;
	if (conHighlighters[conpid] !== curObject) {
		updateInfo(conpid);
		objectClick(conHighlighters[conpid]);
	}
}

function ConnectionHighlighter(pid, points) {
	this.pid = pid;
	if (points)
		this.points = points;
	this.flag = -1;
	this.ovls = {};
}
ConnectionHighlighter.prototype.highlight = function(flag) {
	if (flag == this.flag)
		return;
	var color;
	switch (flag) {
		case 0: color = '#338800'; break;
		case 1: color = '#38d654'; break;
		case 2: color = '#FF0000'; break;
	}

	var coords = [];
	for (var i = 0; i < this.points.length; i++) {
		var p = this.points[i];
		coords.push(new GLatLng(p.lat, p.lng));
	}
	if (! this.ovls[flag]) {
		this.ovls[flag] = new GPolyline(coords, color, polyWeight, polyOpacity);
		map.addOverlay(this.ovls[flag]);
	}
	this.ovls[flag].show();
	if (this.ovls[this.flag]) {
		this.ovls[this.flag].hide();
	}
	this.flag = flag;
}

function GSmartRoute(route) {
	this.route = route;
}

GSmartRoute.createClass = function() {
	if (!GOverlay) return;
	GSmartRoute.prototype = new GOverlay();

	GSmartRoute.prototype.initialize = function(map) {
		this.map = map;
		this.initRoute(this.route);
	}

	// initialize route with branches recursively
	GSmartRoute.prototype.initRoute = function(route) {
		// creating hidden polyline segment highlights
		for (var i = 0; i < route.length; i+=2) {
			if (i < route.length - 2) {
				var points = [];
				points.push(route[i]);
				var con = route[i+1];
				if (con.points)
					for (var j = 0; j < con.points.length; j++)
						points.push(con.points[j]);
				points.push(route[i+2]);
				conHighlighters[con.pid] = new ConnectionHighlighter(con.pid, points);
				conHighlighters[con.pid].highlight(0);
			}
			if (route[i].branches) {
				var branches = route[i].branches;
				for (var j = 0; j < branches.length; j++)
					this.initRoute(branches[j]);
			}
		}
	}

	/* some point coordinates from latLng are negative.
	   Image map coordinates may not be negative thus we need own origin
	   for image map */
	GSmartRoute.prototype.calculateCoords = function() {
		var c = {
			minX : 1000000000,
			minY : 1000000000,
			maxX : -1000000000,
			maxY : -1000000000
		}
		this.calculateRouteCoords(c, this.route);
		this.fullWidth = c.maxX - c.minX + 10;
		this.fullHeight = c.maxY - c.minY + 10;
		this.correction = {x : -c.minX, y : -c.minY};
		/*
			- coordinates of the image map must be (left:-correction.x, top:-correction.y)
			- correction must be ADDED to ALL x/y coordinates of the image map's areas
			- size of the image map image must be fullWidth/fullHeight
		*/
	}
	GSmartRoute.prototype.calculateRouteCoords = function(c, route) {
		for (var i = 0; i < route.length; i+=2) {
			var obj = route[i];
			var p = this.map.fromLatLngToDivPixel(new GLatLng(obj.lat, obj.lng));
			if (p.x < c.minX)
				c.minX = p.x;
			if (p.y < c.minY)
				c.minY = p.y;
			if (p.x > c.maxX)
				c.maxX = p.x;
			if (p.y > c.maxY)
				c.maxY = p.y;
			// process branches recursively
			if (obj.branches) {
				for (var br = 0; br < obj.branches.length; br++)
					this.calculateRouteCoords(c, obj.branches[br]);
			}
		}
	}

	GSmartRoute.prototype.remove = function() {
		if (! this.div)
			return;
		dbg('removing '+ this.div.id);
		this.div.parentNode.removeChild(this.div);
		this.div = null;
	}

	// Copy our data to a new GCluster
	GSmartRoute.prototype.copy = function() {
	  return new GSmartRoute(this.x, this.y);
	}

	// Redraw the rectangle based on the current projection and zoom level
	GSmartRoute.prototype.redraw = function(force) {
		// We only need to redraw if the coordinate system has changed
		if (!force || mapMode == 0)
			return;

		this.remove();

		this.calculateCoords();

		var cor = this.correction;

		var div = document.createElement("div");
		if (! window.torture) window.torture = 0;
		div.id = 'po'+(window.torture++)

		div.style.position = 'absolute';
		div.style.left = (-this.correction.x)+'px';
		div.style.top = (-this.correction.y)+'px';
		div.style.width = this.fullWidth+'px';
		div.style.height = this.fullHeight+'px';
		div.style.zIndex = 100000000;

		var mapId = 'conmap';
		var html = [];
		html.push('<map name="'+mapId+'">\n');

		var proj = G_NORMAL_MAP.getProjection();

		function addArea(from, to, pid, title) {
			var pFrom = map.fromLatLngToDivPixel(new GLatLng(from.lat, from.lng));
			var pTo = map.fromLatLngToDivPixel(new GLatLng(to.lat, to.lng));
			var w = pTo.x - pFrom.x;
			var h = pTo.y - pFrom.y;

			var fact = 1 / Math.sqrt(w * w + h * h) * polyOverWeight / 2;
			var v = {x : Math.round(h * fact), y : Math.round(-w * fact)};

			var poly = [];
			poly.push([pFrom.x + v.x + cor.x, pFrom.y + v.y + cor.y]);
			poly.push([pTo.x + v.x + cor.x, pTo.y + v.y + cor.y]);
			poly.push([pTo.x - v.x + cor.x, pTo.y - v.y + cor.y]);
			poly.push([pFrom.x - v.x + cor.x, pFrom.y - v.y + cor.y]);

			var polyStr = '';
			for (var i = 0; i < poly.length; i++) {
				if (i > 0)
					polyStr += ' ';
				polyStr += poly[i][0] +','+ poly[i][1];
			}
			html.push('  <area style="cursor:pointer" shape="poly" coords="'+polyStr+'" onclick="connectionClick('+pid+'); return false" onmouseover="connectionOver('+pid+')" onmouseout="connectionOut('+pid+')" alt="'+title+'" title="'+title+'" />');
		}

		function addRoute(route) {
			for (var index = 0; index < route.length; index+=2) {
				if (index < route.length - 2) {
					var con = route[index+1];
					if (! con.points) { // no intermediate points in connection
						var from = route[index];
						var to = route[index+2];
						var pid = route[index+1].pid;
						var title = route[index+1].title;
						addArea(from, to, pid, title);
					} else { // have intermediate points in connection
						var pid = route[index+1].pid;
						var title = route[index+1].title;
		
						var from;
						var to;
		
						// add area between marker and first intermediate point
						from = route[index];
						to = con.points[0];
						addArea(from, to, pid, title);
		
						// add areas between intermediate points if there are more than one
						for (var i = 1; i < con.points.length; i++) {
							from = to;
							to = con.points[i];
							addArea(from, to, pid, title);
						}
		
						// add area between last intermediate point and next marker
						from = to;
						to = route[index+2];
						addArea(from, to, pid, title);
					}
				}
				// adding branches recursively
				if (route[index].branches) {
					var branches = route[index].branches;
					for (var br = 0; br < branches.length; br++)
						addRoute(branches[br]);
				}
			}
		}

		addRoute(this.route);

		html.push('</map>');
		html.push('<img src="clear.gif" style="border:0px; width:'+this.fullWidth+'px; height:'+this.fullHeight+'px;" usemap="#'+mapId+'" />');
		html = html.join('\n');
		div.innerHTML = html;

		var pane = G_MAP_MARKER_SHADOW_PANE;
		/*
		G_MAP_FLOAT_PANE
		G_MAP_MAP_PANE
		G_MAP_FLOAT_SHADOW_PANE
		G_MAP_MARKER_SHADOW_PANE
		*/
		map.getPane(pane).appendChild(div);
		this.div = div;
	}
}

GIcons = function() {
	this.initialize();
}
GIcons.prototype.prefix = 'fileadmin/images/marker/';
GIcons.prototype.initialize = function() {
	this.icons = {};
	this.baseIcon = new GIcon();

	this.baseIcon.shadow = this.prefix + 'shadow.png';
	this.baseIcon.iconSize = new GSize(22, 35);
	this.baseIcon.shadowSize = new GSize(43, 35);
	this.baseIcon.iconAnchor = new GPoint(9, 30); // offset from top left corner

	this.baseIcon.infoWindowAnchor = new GPoint(9, 5);
}

GIcons.prototype.addIcon = function(key, img) {
    var icon = new GIcon(this.baseIcon);
    icon.image = this.prefix + img;
	this.icons[key] = icon;
}
GIcons.prototype.getIcon = function(key) {
	return this.icons[key];
}

function showVideo(video, image) {
	$('video_player_parent').update('<div id="video_player" class="videobox">&nbsp;</div>');
	$('video_text_parent').className = 'video_yes';
	var flashvars = {
		width:390,
		height:200,
		file:video
	};
	if (image)
		flashvars.image = image;

	var params = {
		allowfullscreen: true
	};
	
	swfobject.embedSWF(
		"fileadmin/swf/mediaplayer.swf",
		"video_player",
		"390",
		"200",
		"9.0.0",
		"fileadmin/swf/expressInstall.swf",
		flashvars,
		params
	);
}

function hideVideo() {
	$('video_player_parent').update('');
	$('video_text_parent').className = 'video_no';
}

function drawPointPoly(poly) {
	var llp = [];
	var str = '';
	for (var i = 0; i < poly.length; i++) {
		var p = poly[i];
		var ll = map.fromDivPixelToLatLng(new GPoint(p[0], p[1]));
		llp.push(ll);
		str += p[0] + ',' + p[1] + ' ';
	}
	var polyline = new GPolyline(llp, '#FF0000', 1, 1);
	map.addOverlay(polyline);
	dbg(str);

	// drawing axis
	llp = [];
	llp.push(map.fromDivPixelToLatLng(new GPoint(0, 0)));
	llp.push(map.fromDivPixelToLatLng(new GPoint(1, 1)));
	polyline = new GPolyline(llp, '#0000FF', 10, 10);
	map.addOverlay(polyline);
}



