function mGLog(line)
{
	
	if (typeof(console) == 'object' && console != undefined && console.log != undefined)
		console.log(new Date() + ": " + line);
	else if (!disableLoggingEntirely)
		GLog.write(line);
}

function mMax(w1, w2)
{
	if (w1 > w2)
		return w1;
	else
		return w2;
}

function mMin(w1, w2)
{
	if (w1 < w2)
		return w1;
	else
		return w2;
}

function gup( iname )
{
	var name = iname.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if ( results == null )
		return "";
	else
		return results[1];
}

function addUnloadEvent(func)
{
	var oldOnunload = window.onunload;
	if (typeof window.onunload != 'function') {
		window.onunload = func;
	}
	else {
		window.onunload = function() {
			oldOnunload();
			func();
		}
	}
}

/*function dms_to_d(d,m,s,dir)
{
	//alert( "d:"+d+" m:"+m+" s:"+s );
	d = d-0;
	m = m-0;
	var sign = ( dir=='W' || dir=='S' ) ? -1 : 1;
	return (((s/60+m)/60)+d)*sign;
}*/

function createMarkerIcons(adtId)
{
	// var iconBlueH = new GIcon(G_DEFAULT_ICON);
	// iconBlueH.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
	// iconBlueH.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
	// iconBlueH.iconSize = new GSize(12, 20);
	// iconBlueH.shadowSize = new GSize(22, 20);
	// iconBlueH.iconAnchor = new GPoint(6, 20);
	// iconBlueH.infoWindowAnchor = new GPoint(5, 1);
	// var iconRedH = new GIcon(G_DEFAULT_ICON);
	// iconRedH.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
	// iconRedH.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
	// iconRedH.iconSize = new GSize(12, 20);
	// iconRedH.shadowSize = new GSize(22, 20);
	// iconRedH.iconAnchor = new GPoint(6, 20);
	// iconRedH.infoWindowAnchor = new GPoint(5, 1);
	// var iconYellowH = new GIcon(G_DEFAULT_ICON);
	// iconYellowH.image = 'http://labs.google.com/ridefinder/images/mm_20_yellow.png';
	// iconYellowH.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
	// iconYellowH.iconSize = new GSize(12, 20);
	// iconYellowH.shadowSize = new GSize(22, 20);
	// iconYellowH.iconAnchor = new GPoint(6, 20);
	// iconYellowH.infoWindowAnchor = new GPoint(5, 1);
	// var iconGreenH = new GIcon(G_DEFAULT_ICON);
	// iconGreenH.image = 'http://labs.google.com/ridefinder/images/mm_20_green.png';
	// iconGreenH.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
	// iconGreenH.iconSize = new GSize(12, 20);
	// iconGreenH.shadowSize = new GSize(22, 20);
	// iconGreenH.iconAnchor = new GPoint(6, 20);
	// iconGreenH.infoWindowAnchor = new GPoint(5, 1);
	// customIcons["icon_type1h"] = iconBlueH;
	// customIcons["icon_type2h"] = iconRedH;
	// customIcons["icon_type3h"] = iconYellowH;
	// customIcons["icon_type4h"] = iconGreenH;

	var iconBlue = new GIcon(G_DEFAULT_ICON);
	iconBlue.image = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/type1.gif';
	iconBlue.shadow = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/schaduw.png';
	iconBlue.iconSize = new GSize(21, 25);
	iconBlue.shadowSize = new GSize(34, 25);
	iconBlue.iconAnchor = new GPoint(11, 25);
	iconBlue.infoWindowAnchor = new GPoint(5, 1);
	var iconRed = new GIcon(G_DEFAULT_ICON);
	iconRed.image = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/type2.gif';
	iconRed.shadow = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/schaduw.png';
	iconRed.iconSize = new GSize(21, 25);
	iconRed.shadowSize = new GSize(34, 25);
	iconRed.iconAnchor = new GPoint(11, 25);
	iconRed.infoWindowAnchor = new GPoint(5, 1);
	var iconYellow = new GIcon(G_DEFAULT_ICON);
	iconYellow.image = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/type3.gif';
	iconYellow.shadow = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/schaduw.png';
	iconYellow.iconSize = new GSize(21, 25);
	iconYellow.shadowSize = new GSize(34, 25);
	iconYellow.iconAnchor = new GPoint(11, 25);
	iconYellow.infoWindowAnchor = new GPoint(5, 1);
	var iconGreen = new GIcon(G_DEFAULT_ICON);
	iconGreen.image = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/type4.gif';
	iconGreen.shadow = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/schaduw.png';
	iconGreen.iconSize = new GSize(21, 25);
	iconGreen.shadowSize = new GSize(34, 25);
	iconGreen.iconAnchor = new GPoint(11, 25);
	iconGreen.infoWindowAnchor = new GPoint(5, 1);
	customIcons["icon_type1"] = iconBlue;
	customIcons["icon_type2"] = iconRed;
	customIcons["icon_type3"] = iconYellow;
	customIcons["icon_type4"] = iconGreen;

	var iconBlueH = new GIcon(G_DEFAULT_ICON);
	iconBlueH.image = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/type1h.gif';
	iconBlueH.shadow = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/schaduw.png';
	iconBlueH.iconSize = new GSize(21, 25);
	iconBlueH.shadowSize = new GSize(34, 25);
	iconBlueH.iconAnchor = new GPoint(11, 25);
	iconBlueH.infoWindowAnchor = new GPoint(5, 1);
	var iconRedH = new GIcon(G_DEFAULT_ICON);
	iconRedH.image = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/type2h.gif';
	iconRedH.shadow = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/schaduw.png';
	iconRedH.iconSize = new GSize(21, 25);
	iconRedH.shadowSize = new GSize(34, 25);
	iconRedH.iconAnchor = new GPoint(11, 25);
	iconRedH.infoWindowAnchor = new GPoint(5, 1);
	var iconYellowH = new GIcon(G_DEFAULT_ICON);
	iconYellowH.image = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/type3h.gif';
	iconYellowH.shadow = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/schaduw.png';
	iconYellowH.iconSize = new GSize(21, 25);
	iconYellowH.shadowSize = new GSize(34, 25);
	iconYellowH.iconAnchor = new GPoint(11, 25);
	iconYellowH.infoWindowAnchor = new GPoint(5, 1);
	var iconGreenH = new GIcon(G_DEFAULT_ICON);
	iconGreenH.image = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/type4.gif';	// hier is geen highlight van
	iconGreenH.shadow = 'http://files.archieven.nl/' + adtId + '/mi_files/images/markers/schaduw.png';
	iconGreenH.iconSize = new GSize(21, 25);
	iconGreenH.shadowSize = new GSize(34, 25);
	iconGreenH.iconAnchor = new GPoint(11, 25);
	iconGreenH.infoWindowAnchor = new GPoint(5, 1);
	customIcons["icon_type1h"] = iconBlueH;
	customIcons["icon_type2h"] = iconRedH;
	customIcons["icon_type3h"] = iconYellowH;
	customIcons["icon_type4h"] = iconGreenH;
}

function createMarker(obj)
{
	// http://econym.org.uk/gmap/example_zindex.htm
	function onTop(marker, b)
	{
        return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance * 1000000;
	}
	var point = new GLatLng(parseFloat(obj.lat), parseFloat(obj.lng));
	var marker = new GMarker(point
								, {
									zIndexProcess: onTop
									, draggable: debugOn
									, title: ((balloonShowEvent == "click") ? ((obj.kmt == 1) ? obj.naam1 : obj.pls) : "")
									, icon: customIcons["icon_type" + obj.kmt + ((obj.hl == "true") ? "h" : "")]
								}
		);
	marker.importance = obj.hl == "true" ? 2 : 1;
// http://code.google.com/apis/maps/documentation/reference.html#GMarker.mouseover
	// GEvent.addListener(marker, "mouseover", function(latLngCoord) {
		// var mbd = document.createElement("div");
		// mbd.class = "miniballoon";
		// mbd.id = "miniballoon";
		// mbd.innerHTML = (obj.naam1 == undefined) ? obj.pls : obj.naam1;
		// document.getElementById("map_canvas").parentNode.appendChild(mbd);
	// });
	// GEvent.addListener(marker, "mouseout", function(latLngCoord) {
		// var elem = document.getElementById("miniballoon");
		// elem.parentNode.removeChild(elem);
	// });
/**	var el = GEvent.addListener(marker, balloonShowEvent, function() {
			// vullen van ballon is allemaal naar extern verhuisd
			var html = getInfoWindowHtml(obj, balloonShowEvent);
	//		marker.openInfoWindowHtml(html);
			if (html != undefined)	// er wordt bv een redirect gegeven en er moet dus geen HTML worden getoond
			{
				openInfoWindowHtml(marker, html);
			}
		});*/
	GEvent.addListener(marker, "click", function() {
			var html = getInfoWindowHtml(obj, "click");
			if (html != undefined)
			{
				clickOpened = true;
				openInfoWindowHtml(marker, html, "click");
			}
		});
	GEvent.addListener(marker, "mouseover", function() {
			if (!clickOpened)
			{
				var html = getInfoWindowHtml(obj, "mouseover");
				if (html != undefined)
				{
					openInfoWindowHtml(marker, html, "mouseover");
				}
			}
		});
	GEvent.addListener(marker, "mouseout", function() {
			if (!clickOpened)
				removeMarkerBalloon();
		});
	GEvent.addListener(marker, "mouseover", function() {
			marker.setImage(customIcons["icon_type" + obj.kmt + "h"].image);
		});
	GEvent.addListener(marker, "mouseout", function() {
			marker.setImage(customIcons["icon_type" + obj.kmt].image);
		});

	if (obj.hl == "true")
		_highlightedMarker = marker;
	return marker;
}

function getInfoWindowHtml(obj, event)
{
	var html = evalFunction("customInfoWindowHtml", obj, event);
	if (html == "")	// functie was niet gevonden
	{
		html = "";
		for (key in obj)
		{
			if (html.length > 0)
			{
				html += "<br/>\n";
			}
			html += key + ": " + obj[key];
		}
	}

	if (html != undefined)
		return "<div class='balloon'>" + html + "</div>";
	else
		return html;
}

function expandBalloonText()
{
	var wd = document.getElementById('balloonScrollArea');
	if (wd.style.maxHeight == '')
		wd.style.maxHeight = '100px';
	else
		wd.style.maxHeight = '';
}

// http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible
function elementInViewport(el)
{
	var top = el.offsetTop;
	var left = el.offsetLeft;
	var width = el.offsetWidth;
	var height = el.offsetHeight;

	while (el.offsetParent) {
		el = el.offsetParent;
		top += el.offsetTop;
		left += el.offsetLeft;
	}

/*	return (
		top >= window.pageYOffset &&
		left >= window.pageXOffset &&
		(top + height) <= (window.pageYOffset + window.innerHeight) &&
		(left + width) <= (window.pageXOffset + window.innerWidth)
	);*/
	var pXYoffset = getScrollYX();
	var _pageYOffset = pXYoffset['y'];
	var _pageXOffset = pXYoffset['x'];
	var pVPdim = getViewportDimensions();
	var _innerHeight = pVPdim.height;
	var _innerWidth = pVPdim.width;
	return (
		top >= _pageYOffset &&
		left >= _pageXOffset &&
		(top + height) <= (_pageYOffset + _innerHeight) &&
		(left + width) <= (_pageXOffset + _innerWidth)
	);
}

// http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	if ( typeof( window.pageYOffset ) == 'number' ) {
	//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if ( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
	//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if ( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
	//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	var ret = new Array();
	ret['x'] = scrOfX;
	ret['y'] = scrOfY;
	return ret;
}

// http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
function getViewportDimensions()
{
	var viewportwidth;
	var viewportheight;

	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

	if (typeof window.innerWidth != 'undefined')
	{
		viewportwidth = window.innerWidth;
		viewportheight = window.innerHeight;
	}

	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

	else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
	{
		viewportwidth = document.documentElement.clientWidth;
		viewportheight = document.documentElement.clientHeight;
	}

	// older versions of IE

	else
	{
		viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
		viewportheight = document.getElementsByTagName('body')[0].clientHeight;
	}
	//document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');
	var a = new Array();
	a['height'] = viewportheight;
	a['width'] = viewportwidth;
	return a;
}

function openInfoWindowHtml(marker, html, event)
{
	if (event == undefined)
		event = balloonShowEvent;
	// http://marcgrabanski.com/article/jquery-google-maps-tutorial-basics
	var panePixel = map.fromLatLngToContainerPixel(marker.getPoint());

	// if (gmap == undefined)
	// {
		// gmap = map;
		// ew = new EWindow(map, E_STYLE_7);      
		// map.addOverlay(ew);
		// el = GEvent.addListener(map, "click", function(overlay,point) {
			// if (!overlay) {
				// ew.hide();
			// }
		// });
		// GEvent.addListener(ew, "click", el);
	// }
	
/*	var markerOffset = new Point(
		panePixel.x - map.getContainer().offsetLeft
		, panePixel.y - map.getContainer().offsetTop
	);*/

	var wd = document.getElementById("markerBalloon");
	if (wd == undefined || wd == null)
	{
		wd = document.createElement("div");
		wd.id = "markerBalloon";

		{
			var h = "";
			h += "<div id='geo_alldiv'>";
			h += "<table border='0' cellspacing='0' cellpadding='0'>";
			h += "<tr><td id='geo_topldiv'></td><td id='geo_topmdiv'></td><td id='geo_toprdiv'></td></tr>";
			h += "<tr>";
				h += "<td id='geo_midldiv'></td>";
				h += "<td id='geo_midmdiv'>";
					h += "<div id='balloonKruisje' class='kruisje' onclick='removeMarkerBalloon()'></div>";
					//h += "<div id='balloonExpand' class='expander' onclick='expandBalloonText()'>^^^</div>";
					h += "<div id='markerBalloonInner'>";
						h += "<div id='markerBalloonInnerText'></div>";
						if (summarizeBalloonContent)
							h += "<div id='markerBalloonMoreText'>" + IkaLang.translate('CLICK_FOR_MORE') + "</div>";
					h += "</div>";
				h += "</td>";
				h += "<td id='geo_midrdiv'></td>";
			h += "</tr>";
			h += "<tr><td id='geo_botldiv'></td><td id='geo_botmdiv'></td><td id='geo_botrdiv'></td></tr>";
			h += "</table>";
			h += "</div>";
			wd.innerHTML = h;
		}

		var elem = document.getElementById("map_canvas");
		elem.appendChild(wd);
		//var el =
		GEvent.addListener(map, "movestart", function () {
				removeMarkerBalloon();
			});
		//GEvent.addListener(map, "click", el);
	}
	// html +=  "<div>Pix:" + panePixel + "</div>";

	var wdi = document.getElementById("markerBalloonInnerText");
	wdi.innerHTML = html;

	document.getElementById('balloonKruisje').style.display = (event == 'mouseover' ? 'none' : '');
	{
		var wd2 = document.getElementById('balloonScrollArea');
		if (wd2 != null)
		{
			var d = getViewportDimensions();
			wd2.style.maxHeight = mMax(200, mMin(600, d['height'] / 2)) + "px";
		}
	}
	if (summarizeBalloonContent)
	{
		document.getElementById('markerBalloonMoreText').style.display = (event == 'mouseover' ? '' : 'none');
	}

	var y = (wd.clientHeight * -0.5) + panePixel.y - map.getContainer().offsetTop;
	var x = panePixel.x - map.getContainer().offsetLeft + (document.getElementById('map_canvas').offsetLeft);
	if (!((x + wd.clientWidth) < wd.parentNode.clientWidth))
		x -= (wd.clientWidth + 20);	// 20 zijnde de 2 x 10px padding
	else
		x += 10;

	// wd.style.top = y + "px";
	wd.style.left = x + "px";
	{
		var el = wd;
		var top = y;//el.offsetTop;
		var height = el.offsetHeight;

		while (el.offsetParent) {
			el = el.offsetParent;
			top += el.offsetTop;
		}

		el = map.getContainer();
		var mapOffset = el.offsetTop - 10;
		while (el.offsetParent) {
			el = el.offsetParent;
			mapOffset += el.offsetTop;
		}
		var _innerHeight = getViewportDimensions()['height'];
		var _pageYOffset = getScrollXY()['y']; // window.pageYOffset
		mGLog('window: innerheight: ' + _innerHeight);
		mGLog('window: pageYOffset: ' + _pageYOffset);
		mGLog('elemHeight: ' + height);
		mGLog('elemTop: ' + top);
		mGLog('map offset: ' + mapOffset);
		if (top < _pageYOffset)
		{
	mGLog("step: 6");
//			mGLog('weg 1');
			top = _pageYOffset - mapOffset;
		}
		else if (top > (_pageYOffset + _innerHeight - height))
		{
	mGLog("step: 7");
//			mGLog('weg 2');
//			top = _pageYOffset + 0 /*document.getElementById("map_canvas").clientHeight*/ /*480*/ - mapOffset - height + _innerHeight - 10;
			top = _pageYOffset - mapOffset - height + _innerHeight - 10;
		}
		else
		{
	mGLog("step: 8");
//			mGLog('weg 3');
			top = y;
		}
	mGLog("step: 9");
		mGLog("Topnew: " + top);
		wd.style.top = top + "px";
	}

/*	setTimeout(function()
	{
		document.getElementById("geo_topmdiv").style.width = document.getElementById("geo_midmdiv").clientWidth + "px";
		// alert(document.getElementById("geo_midmdiv").clientWidth + "px");
		document.getElementById("geo_botmdiv").style.width = document.getElementById("geo_midmdiv").clientWidth + "px";
	}, 500);*/
	// if (!((y + wd.clientHeight / 2) < wd.parentNode.clientHeight))
	// {
		// map.panBy(new GSize(0, wd.clientHeight));
	// }
	// else if (!((y + wd.clientHeight / 2) > 0))
	// {
		// map.panBy(new GSize(0, -wd.clientHeight));
	// }

	// ew.openOnMarker(marker, "<div id='markerBalloon'>" + html + "</div>");

	//marker.openInfoWindowHtml(html);
}

function removeMarkerBalloon()
{
/*	var wd = document.getElementById("markerBalloon");
	if (wd != undefined)
	{
		wd.parentNode.removeChild(wd);
	}*/
	clickOpened = false;
	var wd = document.getElementById("markerBalloon");
	if (wd != undefined && wd != null)
		wd.parentNode.removeChild(wd);
	else if (debugOn)
		mGLog('element markerBalloon = null !!');
}

var _ika_lang_cache; //= new Array();
var IkaLang = {
	//_cache : new Array(),
	translate : function translate(label) {
		//if (IkaLang._cache.length == 0) {
		//if (_ika_lang_cache.length == 0) {
		if (_ika_lang_cache == null) {
			IkaLang._initTranslations();
		}
		var lang = IkaLang.getLanguage();
		//var msg = IkaLang._cache[lang][label];
		var msg = _ika_lang_cache[lang][label];
		if (lang != 'nl' && (msg == null || msg == undefined || msg == ""))
			//msg = IkaLang._cache['nl'][label];
			msg = _ika_lang_cache['nl'][label];
		if (debugOn && (msg == null || msg == undefined || msg == ""))
			msg = label;
		return msg;
	},
	getLanguage : function () {
		var lang = readCookie("jfcookie[lang]");
		if (lang == null || lang == undefined || lang == "")
			lang = 'nl';
		if (lang != 'nl' && lang != 'en')
			lang = 'nl';
		return lang;
	},
	_initTranslations : function() {
		var _cache = new Array();
		_cache['en'] = new Array();
		_cache['en']['FULL_SCREEN'] = 'Full screen';
		_cache['en']['RESTORE_SCREEN'] = 'Return to website';
		_cache['en']['PREVIOUS_MAP'] = 'Previous map';
		_cache['en']['TOP_MAP'] = 'Overview';
		_cache['en']['OPTIONS'] = 'Options';
		_cache['en']['SELECTION'] = 'Selection';
		_cache['en']['LEGEND'] = 'Legend';
		_cache['en']['DRAG_HINT'] = 'Drag to position legend';
		_cache['en']['CLICK_TOGGLE_HINT'] = 'Click to show/hide legend';
		_cache['en']['TOON_KAART'] = 'Display Google map';
		_cache['en']['HIDE_KAART'] = 'Hide Google map';
		_cache['en']['CLICK_FOR_MORE'] = '(click the icon to show more information)';
		_cache['nl'] = new Array();
		_cache['nl']['FULL_SCREEN'] = 'Volledig beeld';
		_cache['nl']['RESTORE_SCREEN'] = 'Terug naar website';
		_cache['nl']['PREVIOUS_MAP'] = 'Vorige kaart';
		_cache['nl']['TOP_MAP'] = 'Overzichtskaart';
		_cache['nl']['OPTIONS'] = 'Opties';
		_cache['nl']['SELECTION'] = 'Selectie';
		_cache['nl']['LEGEND'] = 'Legenda';
		_cache['nl']['DRAG_HINT'] = 'Sleep hiermee de legenda';
		_cache['nl']['CLICK_TOGGLE_HINT'] = 'Klik om open/dicht te vouwen';
		_cache['nl']['TOON_KAART'] = 'Toon Google-kaart';
		_cache['nl']['HIDE_KAART'] = 'Verberg Google-kaart';
		_cache['nl']['CLICK_FOR_MORE'] = '(klik op het ikoontje voor meer informatie)';

		var overWValues = evalFunction("customLangInit");
		mGLog("Load Custom language prompts");
		// mGLog(overWValues);
		//if (RealTypeOf(overWValues) == 'array')
		{
			//var array = new Object(); //this is safe only if you can assure object has not been extended.
			//use the below if Object has been extended
			//var array;

			//everything below here works fine regardless of the two above cases

			for ( keyVar in overWValues ) {
				for (kv in overWValues[keyVar]) {
					_cache[keyVar][kv] = overWValues[keyVar][kv];
				}
			}
		}

		//IkaLang._cache = _cache;
		_ika_lang_cache = _cache;
	}
};

// http://joncom.be/code/realtypeof/
function RealTypeOf(v)
{
	if (typeof(v) == "object")
	{
		if (v === null) return "null";
		if (v.constructor == (new Array).constructor) return "array";
		if (v.constructor == (new Date).constructor) return "date";
		if (v.constructor == (new RegExp).constructor) return "regex";
		return "object";
	}
	return typeof(v);
}
 
function toggleZoom(readPositionFromCookiesFirst)
{
	var elem = document.getElementById("map_canvas");
	var elem2 = document.getElementById("ika_zoom_map");
	var elem3 = document.getElementById("ika_geo_sidebox");
	mGLog("Left: " + elem3.style.left);
	var center = map.getCenter();
	if (zoomedMap)
	{
		var width = elem.clientWidth;
		elem.style.position = "relative";//oldStyle['position'];	// was static alvorens relative
		elem.style.left = oldStyle['left'];
		elem.style.top = oldStyle['top'];
		elem.style.height = oldStyle['height'];
		elem.style.width = oldStyle['width'];
		elem.style.right = "auto";
		elem.style.bottom = "auto";
		elem.style.marginLeft = oldStyle['marginLeft'];	// deed niet mee
		elem.style.zIndex = "11";//oldStyle['zIndex'];
//		elem.style.height = "500px";
		document.getElementById('toggleZoomLink').innerHTML = IkaLang.translate('FULL_SCREEN');//"Volledig beeld";
		elem3.style.position = "absolute";
		if (parseInt(elem3.style.left) > (width / 2))
			elem3.style.left = mMax(0, (parseInt(elem3.style.left) - (width - oldStyle['width']))) + "px";
		
		if (map.getZoom() > oldStyle['zoom'])
			map.setCenter(center, oldStyle['zoom']);
		mGLog("Left2: " + elem3.style.left);
	}
	else
	{
		oldStyle['left'] = elem.style.left;
		oldStyle['top'] = elem.style.top;
		oldStyle['height'] = elem.style.height;
		oldStyle['width'] = elem.style.width;
		oldStyle['zIndex'] = elem.style.zIndex;
		oldStyle['center'] = center;
		oldStyle['zoom'] = map.getZoom();
		oldStyle['width'] = elem.clientWidth;
		oldStyle['position'] = elem.style.position;
		oldStyle['marginLeft'] = elem.style.marginLeft;
		elem.style.position = "fixed";
		elem.style.left = "0";
		elem.style.top = "0";
		elem.style.right = "0";
		elem.style.bottom = "0";
		elem.style.marginLeft = '0';	// deed niet mee
		elem.style.zIndex = "100";
		elem.style.height = "100%";
		elem.style.width = "100%";
		document.getElementById('toggleZoomLink').innerHTML = IkaLang.translate('RESTORE_SCREEN');//"Weergave herstellen";
		elem3.style.position = "fixed";
		mGLog("box left: " + elem3.style.left);
		mGLog("box left length: " + elem3.style.left.length);
		mGLog("box left: strippped: " + elem3.style.left.substr(0, elem3.style.left.length - 2));
		mGLog("delta width: " + (elem.clientWidth - oldStyle['width']));
		mGLog("new box left: " + (parseInt(elem3.style.left.substr(0, elem3.style.left.length - 2)) + (elem.clientWidth - oldStyle['width'])) + "px");
		if (parseInt(elem3.style.left) > (oldStyle['width'] / 2))
		// if (parseInt(elem3.style.left.substr(0, elem3.style.left.length - 2)) > (oldStyle['width'] / 2))
		{
			if (readPositionFromCookiesFirst)
			{
				//readBoxPositionFromCookies();
			}
			elem3.style.left = mMin(mMax(0, (parseInt(elem3.style.left) + (elem.clientWidth - oldStyle['width']))), getWindowWidth() - elem3.clientWidth - 20) + "px";
		}
		else if (parseInt(elem3.style.left) < 5)
		{
			elem3.style.left = "5px";
		}
		mGLog("Left3: " + elem3.style.left);
	}
	zoomedMap = !zoomedMap;
	createCookie("zoomedMap", ((zoomedMap) ? 1 : 0), 1);
	map.checkResize();
	map.setCenter(center);
	//setTimeout("flickerInstructions(" + ((zoomedMap) ? 1900 : 1500) + ", new Date());", 1);
	evalFunction("zoomToggled", zoomedMap);
	
	repositionLegend();

	removeMarkerBalloon();

	return false;
}

function flickerInstructions(duration, startTime)
{
	var now = new Date();
	var elem = document.getElementById("ika_geo_sidebox");
	// if (elem.style.paddingRight != "2px")
	if (elem.style.opacity != "1")
	{
mGLog("flicker aan: " + startTime.getTime() + " - " + now.getTime());
		elem.style.opacity = "1";
		elem.style.filter = "alpha(opacity=100)";
		// elem.style.paddingRight = '2px';
		if (now.getTime() < startTime.getTime() + duration)
		{
			setTimeout("var t = new Date(); t.setTime(" + startTime.getTime() + "); flickerInstructions(" + duration + ", t);", 300);
		}
	}
	else
	{
mGLog("flicker uit: " + startTime.getTime() + " - " + now.getTime());
		// elem.style.opacity = "0.4";
		// elem.style.filter = "alpha(opacity=40)";
		elem.style.opacity = "";//"0.4";
		elem.style.filter = "";//"alpha(opacity=40)";
		// elem.style.paddingRight = "";//'3px';
		// if (now.getTime() < startTime.getTime() + duration)
		{
			setTimeout("var t = new Date(); t.setTime(" + startTime.getTime() + "); flickerInstructions(" + duration + ", t);", 300);
		}
	}
}

function initZoom()
{
	if (1 == readCookie("zoomedMap"))
	{
		toggleZoom(true);
	}
}

function readBackZoom()
{
	var m = mapName;
	var cX = readCookie("centerX" + m);
	var cY = readCookie("centerY" + m);
	var z = readCookie("zoom" + m);
	if (cX != undefined && cY != undefined && z != undefined)
	{
		var c = new GLatLng(cY, cX);
		// map.setCenter(c, z);
	}
}

function ika_sdbh_click()
{
	var visible;
	var elem = document.getElementById("ika_sdb_body");
	if (elem.style.display == 'none')
	{
		document.getElementById("ika_sdb_header").style.minWidth = "0";
		elem.style.display = 'block';
		elem.style.visibility = 'visible';
		/*changecss('div.kruisje', 'background', 'http://files.archieven.nl/963/mi_files/images/maximalize.gif');
		changecss('div#balloonKruisje', 'background', 'http://files.archieven.nl/963/mi_files/images/maximalize.gif');
		changecss('div.kruisje:hover', 'background', 'http://files.archieven.nl/963/mi_files/images/maximalize_over.gif');
		changecss('div#balloonKruisje:hover', 'background', 'http://files.archieven.nl/963/mi_files/images/maximalize_over.gif');*/
		visible = true;
	}
	else
	{
		var w = document.getElementById("ika_sdb_header").clientWidth;
		w -= 6;
		w = mMax(0, w);
		document.getElementById("ika_sdb_header").style.minWidth = w + "px";
		elem.style.display = 'none';
		elem.style.visibility = 'hidden';

		/*changecss('div.kruisje', 'background', 'http://files.archieven.nl/963/mi_files/images/minimalize.gif');
		changecss('div#balloonKruisje', 'background', 'http://files.archieven.nl/963/mi_files/images/minimalize.gif');
		changecss('div.kruisje:hover', 'background', 'http://files.archieven.nl/963/mi_files/images/minimalize_over.gif');
		changecss('div#balloonKruisje:hover', 'background', 'http://files.archieven.nl/963/mi_files/images/minimalize_over.gif');*/
		visible = false;
	}

	repositionLegend();	// bij het openen van de map in zoomed modus resetten we met deze aanroep de legenda in beeld

	evalFunction("ika_sdbh_click_performed", visible);
}

function repositionLegend()
{
//	var elem = document.getElementById("ika_sdb_body");
//	var visible = elem.style.display != 'none';
	var sidebox = document.getElementById('ika_geo_sidebox');
	var pos = getElementAbsolutePos(sidebox);
	if (zoomedMap)
	{
		if (pos.y < 10)
			sidebox.style.top = "10px";
	}
	else
	{
		if (sidebox.style.top == "10px")
		//if (pos.y == 10)
			sidebox.style.top = legendPositionY + "px";
	}
}

function getLegenda(adtId, level)
{
	return evalFunction("getLegenda" + adtId, adtId, level);
}

function getBaseMapUrl(adtId)
{
	var url = evalFunction("getBaseMapUrl" + adtId);
	if (url == "")
		url = "/topomap";
	return url;
}

function installInstructionsDiv(stepBackZoomOutURL, adtId, level)
{
	globalMapLevel = level;
	var instructions = document.createElement("div");
	// instructions.style.width = "110px";
	instructions.style.left = legendPositionX + "px";//"-200px";//"550px";
	mGLog("Left4: " + instructions.style.left);
	instructions.style.top = legendPositionY + "px";//"0";//"10px";
	instructions.style.relative = "10px";
	instructions.id = "ika_geo_sidebox";

	var text = "<div id='ika_sdb_header' title='" + IkaLang.translate('DRAG_HINT') + "'>";
	text += "<div onclick='ika_sdbh_click();' title='" + IkaLang.translate('CLICK_TOGGLE_HINT') + "' class='minnetje' id='legendMinnetje'></div>";
	text += "<div id='ika_sdb_dragger'>" + mapName + "&nbsp;</div>";
	text += "</div>";
	text += "<div id='ika_sdb_body'>";
	text += getLegenda(adtId, level);
	text += "<h1>" + IkaLang.translate('OPTIONS') + "</h1>";
	if (level > 1)
		text += "<div class='optiesOpsomming' class='ika_zoom_out'><div class='icon'><img alt='' class='icon' src='http://files.archieven.nl/" + adtId + "/mi_files/images/overzichtskaart.png'/></div><div class='blok'><a class='' href=\"" + getBaseMapUrl(adtId) + "\">" + IkaLang.translate('TOP_MAP') + "&nbsp;</a></div></div>";
	if (stepBackZoomOutURL)
		text += "<div class='optiesOpsomming' id='ika_zoom_out'><div class='icon'><img alt='' class='icon' src='http://files.archieven.nl/" + adtId + "/mi_files/images/omhoog.gif'/></div><div class='blok'><a class='' href=\"" + (stepBackZoomOutURL) + "\">" + IkaLang.translate('PREVIOUS_MAP') + "&nbsp;</a></div></div>";
	text += "<div class='optiesOpsomming' id='ika_zoom_map'><div class='icon'><img alt='' src='http://files.archieven.nl/" + adtId + "/mi_files/images/max2.png'/></div><div class='blok'><a id='toggleZoomLink' class='' href='javascript:void(0)' onclick='return toggleZoom(false);'>" + IkaLang.translate('FULL_SCREEN') + "&nbsp;</a></div></div>";
	if (googleKaartVisible || gup('gmap'))
		text += "<div class='optiesOpsomming' id='ika_toggle_map'><a id='tokLink' class='blok' href='javascript:void(0)' onclick='return toggleOverlayKaart();'>" + IkaLang.translate('TOON_KAART') + "</a></div>";
	text += "</div>";
	instructions.innerHTML = text;

	document.getElementById("map_canvas").appendChild(instructions);

	var theHandle = document.getElementById("ika_sdb_dragger");
	var theRoot = document.getElementById("ika_geo_sidebox");
	if (typeof Drag != "undefined")
	{
		Drag.init(theHandle, theRoot);
	}

	readBoxPositionFromCookies();
}

function getWindowWidth() {
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
  return myWidth;
}

function getWindowHeight() {
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }
  return myHeight;
}

function readBoxPositionFromCookies()
{
	var instructions = document.getElementById("ika_geo_sidebox");
	var l = readCookie("igsb_left");
	mGLog("read from cookie: left = " + l);
	if (l != null && l != undefined)
	{
		var pos = getElementAbsolutePos(document.getElementById("map_canvas"));
/*		mGLog(parseInt(l));
		mGLog(instructions.clientWidth);
		mGLog(parseInt(l) + instructions.clientWidth);
		mGLog(getWindowWidth());
		mGLog(pos);
		mGLog(pos.x);
		mGLog(pos.y);
		mGLog(getWindowWidth() - pos.x);*/
		if (parseInt(l) + instructions.clientWidth < (getWindowWidth() - pos.x) && parseInt(l) > -pos.x)
		//if (parseInt(l) + instructions.clientWidth < (document.getElementById("map_canvas").clientWidth /*getWindowWidth() - parseInt(document.getElementById("map_canvas").style.left)*/) && parseInt(l) > 0)
		{
			instructions.style.left = l;
			mGLog("applied from cookie: left = " + l);
		}
	}
	var t = readCookie("igsb_top");
	mGLog("read from cookie: top = " + t);
	if (t != null && t != undefined)
	{
		if (parseInt(t) + instructions.clientHeight < (getWindowHeight() - pos.y) && parseInt(t) > -pos.y)
		//if (parseInt(t) + instructions.clientHeight < (document.getElementById("map_canvas").clientHeight /*getWindowHeight() - parseInt(document.getElementById("map_canvas").style.top)*/) && parseInt(t) > 0)
		{
			instructions.style.top = t;
			mGLog("applied from cookie: top = " + t);
		}
	}
}

function toggleOverlayKaart()
{
	if (overlayKaartVisible)
	{
		overlayKaartVisible = false;
		map.removeOverlay(oldmap);
		document.getElementById("tokLink").innerHTML = IkaLang.translate('HIDE_KAART');
	}
	else
	{
		overlayKaartVisible = true;
		map.addOverlay(oldmap);
		document.getElementById("tokLink").innerHTML = IkaLang.translate('TOON_KAART');
	}
}

function overlayAdded(overlay)
{
	// mGLog('added: ' + overlay);
	document.getElementById('div_timer').style.visibility = 'hidden';
}

function setFullMessage(msg, timeout)
{
	// http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
	if (timeout > 0)
	{
		setTimeout("clearFullMessage();", timeout);
	}
	var body = document.getElementsByTagName("body")[0];
	var elem = document.createElement("div");
	elem.id = "fullMessageZweverBackground";
	elem.className = "fullMessageZweverBackground";
	body.appendChild(elem);

	elem = document.createElement("div");
	elem.id = "fullMessageZwever";
	elem.className = "fullMessageZwever";
	body.appendChild(elem);

	var elemI1 = document.createElement("div");
	elemI1.className = "fullMessageZweverInner1";
	elem.appendChild(elemI1);

	var elemI2 = document.createElement("div");
	elemI2.className = "fullMessageZweverInner2";
	elemI1.appendChild(elemI2);

	elemI2.innerHTML = msg;
}

function clearFullMessage()
{
	var elem = document.getElementById("fullMessageZweverBackground");
	if (elem != null)
	{
		elem.parentNode.removeChild(elem);
	}
	elem = document.getElementById("fullMessageZwever");
	if (elem != null)
	{
		elem.parentNode.removeChild(elem);
	}
}

function setPanBounds(sw2, ne2)
{
	// Add a move listener to restrict the bounds range
	GEvent.addListener(map, "move", function() {
		checkBounds();
	});

	// The allowed region which the whole map must be within
	var allowedBounds = new GLatLngBounds (sw2, ne2)
						//new GLatLngBounds(new GLatLng(sw.lat() + 4, sw.lng() + 4), new GLatLng(ne.lat() - 4, ne.lng() - 4));
	mGLog("Allowed panbounds: " + allowedBounds);

	// If the map position is out of range, move it back
	function checkBounds() {
		// Perform the check and return if OK
		if (allowedBounds.contains(map.getCenter())) {
			return;
		}
		// It`s not OK, so find the nearest allowed point and move there
		var C = map.getCenter();
		var X = C.lng();
		var Y = C.lat();

		var AmaxX = allowedBounds.getNorthEast().lng();
		var AmaxY = allowedBounds.getNorthEast().lat();
		var AminX = allowedBounds.getSouthWest().lng();
		var AminY = allowedBounds.getSouthWest().lat();

		if (X < AminX) {X = AminX;}
		if (X > AmaxX) {X = AmaxX;}
		if (Y < AminY) {Y = AminY;}
		if (Y > AmaxY) {Y = AmaxY;}
		// alert ("Restricting "+Y+" "+X);
		map.setCenter(new GLatLng(Y,X));

		// var B = map.getBounds();

		// if (allowedBounds.contains(b.getNorthEast()) && allowedBounds.contains(b.getSouthWest())) {
			// return;
		// }

		// var AmaxX = ne2.lng();
		// var AmaxY = ne2.lat();
		// var AminX = sw2.lng();
		// var AminY = sw2.lat();

		// var VmaxX = B.getNorthEast().lng();
		// var VmaxY = B.getNorthEast().lat();
		// var VminX = B.getSouthWest().lng();
		// var VminY = B.getSouthWest().lat();

		// if (VminX < AminX) {VminX = AminX; VmaxX = AmaxX;}
		// if (VmaxX > AmaxX) {VmaxX = AmaxX; VminX = AminX;}
		// if (VminY < AminY) {VminY = AminY; VmaxY = AmaxY;}
		// if (VmaxY > AmaxY) {VmaxY = AmaxY; VminY = AminY;}

		// B = new GLatLngBounds(new GLatLng(VminY, VminX), new GLatLng(VmaxY, VmaxX));
		// map.setCenter(B.getCenter());
	}
}

function setupNavControl(adtId)
{
	map.enableContinuousZoom();
//	map.enableScrollWheelZoom();
//	map.addControl(new GOverviewMapControl());	// voor als we de layers hebben
	map.addControl(new GSmallMapControl()); // deze wordt middels JavaScript van een andere achtergrond voorzien
//	map.addControl(new GLargeMapControl());
//	map.addControl(new GMapTypeControl());
	setupNavControl2(adtId, false);
}

function setupNavControl2(adtId, alreadyInited)
{
	var navControl = document.getElementById("smc");
	if (navControl != undefined)
	{
		navControl = navControl.firstChild;
		navControl.src = "http://files.archieven.nl/" + adtId + "/mi_files/images/smc_ika.png";
		if (!alreadyInited)
		{
			setTimeout("setupNavControl2(" + adtId + ", true);", 5000);
		}
	}
	else
	{
		setTimeout("setupNavControl2(" + adtId + ", false);", 1000);
	}
}

// http://www.iconico.com/workshop/jsSerializer/
// http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function centerMap(swK, neK, swM, neM, alreadyCentered)
{
	neT = new GLatLng(mMax(neK.lat(), neM.lat()), mMax(neK.lng(), neM.lng()));
	swT = new GLatLng(mMin(swK.lat(), swM.lat()), mMin(swK.lng(), swM.lng()));

	if (!alreadyCentered)
	{
		var boundariesK = new GLatLngBounds(swK, neK);
		var centerK = boundariesK.getCenter();
		var lvlK = map.getBoundsZoomLevel(boundariesK);
		var level = lvlK;
		mGLog("Level 1: " + level);
		map.setCenter(centerK, level);

		{	// nieuwe stijl, met extra marges om de markers-box
			var iMapBounds = new GLatLngBounds(
					map.fromContainerPixelToLatLng(new GPoint(5, document.getElementById('map_canvas').clientHeight - 3))
				,	map.fromContainerPixelToLatLng(new GPoint(document.getElementById('map_canvas').clientWidth - 5, 10))
			);
			var oMapBounds = map.getBounds();
			var marginNorth = oMapBounds.getNorthEast().lat() - iMapBounds.getNorthEast().lat();
			var marginEast = oMapBounds.getNorthEast().lng() - iMapBounds.getNorthEast().lng();
			var marginSouth = oMapBounds.getSouthWest().lat() - iMapBounds.getSouthWest().lat();
			var marginWest = oMapBounds.getSouthWest().lng() - iMapBounds.getSouthWest().lng();

			mGLog("north: " + marginNorth);
			mGLog("east: " + marginEast);
			mGLog("south: " + marginSouth);
			mGLog("west: " + marginWest);

			var boundariesM = new GLatLngBounds(new  GLatLng(swM.lat() + marginSouth, swM.lng() + marginWest), new GLatLng(neM.lat() + marginNorth, neM.lng() + marginEast));
			var centerM = boundariesM.getCenter();
			var lvlM = map.getBoundsZoomLevel(boundariesM);
			if (lvlM > lvlK)
			{
				level = lvlM;
				map.setCenter(centerK, level);
				mGLog("Level 2: " + level);
			}
		}

		/*	// oude stijl, zonder marges om de markers-box
		var boundariesM = new GLatLngBounds(swM, neM);
		var centerM = boundariesM.getCenter();
		var lvlM = map.getBoundsZoomLevel(boundariesM);
		if (lvlM > lvlK)
		{
			level = lvlM;
			map.setCenter(centerK, level);
			mGLog("Level 2: " + level);
		}*/

////////////////////////////////////////////////////////////////////////////////////////////////////////////
		var mapBounds = map.getBounds();
		var center = map.getCenter();
		var ne = mapBounds.getNorthEast();
		var sw = mapBounds.getSouthWest();

		var offsetLng = (ne.lng() + sw.lng() - neM.lng() - swM.lng()) / 2;
		var offsetLat = (ne.lat() + sw.lat() - neM.lat() - swM.lat()) / 2;
		var offsetLng2 = (ne.lng() + sw.lng() - neK.lng() - swK.lng()) / 2;
		var offsetLat2 = (ne.lat() + sw.lat() - neK.lat() - swK.lat()) / 2;

		// var offsetLng = (ne.lng() + sw.lng() - mMin(neK.lng(), neM.lng()) - mMax(swK.lng(), swM.lng())) / 2;
		// var offsetLat = (ne.lat() + sw.lat() - mMin(neK.lat(), neM.lat()) - mMax(swK.lat(), swM.lat())) / 2;

		// if (boundariesK.getNorthEast().lat() > neM.lat())
			// offsetLat += (boundariesK.getNorthEast().lat() - neM.lat());

		// mGLog(offsetLat);
		// mGLog(offsetLat2);
		// mGLog(center.lat());
		// mGLog(offsetLng);
		// mGLog(offsetLng2);
		// mGLog(center.lng());
		if (swM.lat() == neM.lat() && swM.lng() == neM.lng())	// dit is typisch het geval als er slechts één marker op de kaart staat
		{
			mGLog("hier");
			var lll = map.getBoundsZoomLevel(boundariesK);
			map.setCenter(centerK, lll + 2);
		}
		var newCenter =new GLatLng(center.lat() - offsetLat - offsetLat2, center.lng() - offsetLng - offsetLat2);
		map.setCenter(newCenter);

////////////////////////////////////////////////////////////////////////////////////////////////////////////

		mapBounds = map.getBounds();
		// mGLog("map.maxY: " + mapBounds.getNorthEast().lat());
		// mGLog("kaart.maxY: " + neT.lat());
		// mGLog("map.minY: " + mapBounds.getSouthWest().lat());
		// mGLog("kaart.minY: " + swT.lat());
		// mGLog("map.maxX: " + mapBounds.getNorthEast().lng());
		// mGLog("kaart.maxX: " + neT.lng());
		// mGLog("map.minX: " + mapBounds.getSouthWest().lng());
		// mGLog("kaart.minX: " + swT.lng());

		var offsetLng3 = 0;
		var offsetLat3 = 0;
		if (mapBounds.getNorthEast().lat() > neT.lat())
		{
			mGLog("moet omhoog");
			if (mapBounds.getSouthWest().lat() < swT.lat())
			{
				mGLog("maar moet ook omlaag, dus niets doen");
			}
			else
			{
				mGLog("hier iets doen, hij kan iets omhoog");
				offsetLat3 = mapBounds.getNorthEast().lat() - neT.lat();
			}
		}
		else if (mapBounds.getSouthWest().lat() < swT.lat())
		{
			mGLog("moet omlaag");
			if (mapBounds.getNorthEast().lat() > neT.lat())
			{
				mGLog("maar moet ook omhoog, dus niets doen");
			}
			else
			{
				mGLog("hier iets doen, hij kan iets omlaag");
				offsetLat3 = mapBounds.getSouthWest().lat() - swT.lat();
			}
		}
		else
		{
			mGLog("verticaal goed uitgelijnd");

//			var dn = neK/*mapBounds.getNorthEast()*/.lat() - neT.lat();
//			var ds = swT.lat() - swK/*mapBounds.getSouthWest()*/.lat();
//			if (dn < ds)
//			{
//				// omlaag verschuiven totdat bovenrand overlay in beeld komt
//				//offsetLat3 = mapBounds.getNorthEast().lat() - neK.lat();
//			}
//			else if (dn > ds)
//			{
//				// iets omhoog verschuiven totdat onderrand overlay in beeld komt
//				//offsetLat3 = swK.lat() - mapBounds.getSouthWest().lat();
//			}
		}
		if (mapBounds.getNorthEast().lng() > neT.lng())
		{
			mGLog("moet naar rechts");
			if (mapBounds.getSouthWest().lng() < swT.lng())
			{
				mGLog("maar moet ook naar links, dus niets doen");
			}
			else
			{
				mGLog("hier iets doen, hij kan naar rechts");
				offsetLng3 = mapBounds.getNorthEast().lng() - neT.lng();
			}
		}
		else if (mapBounds.getSouthWest().lng() < swT.lng())
		{
			mGLog("moet naar links");
			if (mapBounds.getNorthEast().lng() > neT.lng())
			{
				mGLog("maar moet ook naar rechts, dus niets doen");
			}
			else
			{
				mGLog("hier iets doen, hij kan naar links");
				offsetLng3 = mapBounds.getSouthWest().lng() - swT.lng();
			}
		}
		else
		{
			mGLog("horizontaal goed uitgelijnd");
		}

		////////

		mapBounds = map.getBounds();
		mGLog(mMin(swK.lat(), swM.lat()) + " - " + mapBounds.getSouthWest().lat());
		mGLog(mMin(swK.lng(), swM.lng()) + " - " + mapBounds.getSouthWest().lng());
		mGLog(mMax(neK.lat(), neM.lat()) + " - " + mapBounds.getNorthEast().lat());
		mGLog(mMax(neK.lng(), neM.lng()) + " - " + mapBounds.getNorthEast().lng());
		if (mMin(swK.lat(), swM.lat()) >= mapBounds.getSouthWest().lat()
			&& mMin(swK.lng(), swM.lng()) >= mapBounds.getSouthWest().lng()
			&& mMax(neK.lat(), neM.lat()) <= mapBounds.getNorthEast().lat()
			&& mMax(neK.lng(), neM.lng()) <= mapBounds.getNorthEast().lng()
		)
		{
			mGLog("center map");
			center = new GLatLng((mMax(neK.lat(), neM.lat()) + mMin(swK.lat(), swM.lat())) / 2, (mMax(neK.lng(), neM.lng()) + mMin(swK.lng(), swM.lng())) / 2);
		}
		else
		{
			mGLog("center map 2");
			// mGLog("Offset: " + offsetLng3 + " - " + offsetLat3);
			center = map.getCenter();
			center = new GLatLng(center.lat() - offsetLat3, center.lng() - offsetLng3);
			// mGLog("centreer");
		}
		map.setCenter(center);

		if (limitZoom)
		{
			level = map.getZoom();
			/*var MAX = 9 + globalMapLevel * 2;	// ja deze 9 is vrij willekeurig, maar past kennelijk goed
			if (level > MAX)
			{
				level = MAX;
				map.setZoom(MAX);
			}*/
			var mt = map.getMapTypes();
			for (var i = 0; i < mt.length; i++)
			{
				mt[i].getMinimumResolution = function() {return mMin(level - 1, lvlK);}
				mt[i].getMaximumResolution = function() {return level + 4;}
			}
		}
	}

	setPanBounds(swT, neT);
}

function ikaHighlight(marker, swK, neK)
{
	var boundaries = new GLatLngBounds(swK, neK);
	var lvl = map.getBoundsZoomLevel(boundaries);
	var center = boundaries.getCenter();
	// map.setCenter(center, lvl + 1);
	// map.panTo(marker.getLatLng());
	// map.setCenter(marker.getLatLng(), lvl);
	GEvent.trigger(marker, 'click');
}

function getCopyrightMsg(adtId)
{
	return evalFunction("getCopyrightMsg" + adtId);
}

function evalFunction()
{
	//var arg;
	var msg = "";
	var e = "if (typeof " + arguments[0] /*+ arguments[1]*/ + " == 'function')";
	e += "msg = " + arguments[0] /*+ arguments[1]*/ + "(";
	for (var i = /*2*/ 1; i < arguments.length; i++)
	{
		if (i > /*2*/ 1)
			e += ",";
		//arg = "" + arguments[i];
		//e += "\"" + arg.replace("\"", "\\\"") + "\"";
		e += "arguments[" + i + "]";
	}
	e += ");";
	// mGLog(e);
	eval(e);
	return msg;
}

function topoInit(adtId)
{
	createMarkerIcons(0);

	if (adtId != undefined)
	{
		createMarkerIcons(adtId);
	}

	setTimeout("initZoom();", 1);

	addUnloadEvent(function () {
		if (savePositionsToCookie)
		{
			var c = map.getCenter();
			var z = map.getZoom();
			var m = mapName;
			createCookie("zoom" + m, z);
			if (c != undefined && c != null)
			{
				createCookie("centerX" + m, c.lng());
				createCookie("centerY" + m, c.lat());
			}
			var l = document.getElementById('ika_geo_sidebox').style.left;
			var t = document.getElementById('ika_geo_sidebox').style.top;
			if (l == null || l == undefined)
			{
				deleteCookie("igsb_left");
			}
			else
			{
				createCookie("igsb_left", l);
			}
			if (t == null || t == undefined)
			{
				deleteCookie("igsb_left");
			}
			else
			{
				createCookie("igsb_top", t);
			}
		}
		GUnload();
	});
	//setTimeout("readBackZoom();", 5000);

//		GEvent.addListener(map, "tilesloaded", gTilesLoaded);
//		GEvent.addListener(map,"addoverlay", overlayAdded);
//		GEvent.addListener(map,"tilesloaded", function () {
//			GLog.write('all tiles loaded');
//		});
//		map.addoverlay = overlayAdded;

	evalFunction("topoInit" + adtId);

	if (legendCollapsed)
		setTimeout("ika_sdbh_click();", 2000);

	return false;
}

function topoPostInit(adtId)
{
	// http://maps.charmeck.org/dev/curisa/TileMaps/GMap/1_replace_def_url.htm
	// http://code.google.com/intl/nl/apis/maps/documentation/overlays.html#Tile_Overlays

	if (!(googleKaartVisible || gup('gmap')))
	{
		G_NORMAL_MAP.getTileLayers()[0].getTileUrl = function (tile, zoom) {
			/* GLog.write('tile: ' + tile + ', zoom: ' + zoom); */
			return 'http://files.archieven.nl/' + adtId + '/mi_files/images/tile_bg.png';
		};
	}
	G_NORMAL_MAP.getTileLayers()[0].getCopyright = function (bounds, zoom) {
		return getCopyrightMsg(adtId);
	};

	GEvent.addListener(map,'zoomend',function(oldlevel, newlevel){ 
		removeMarkerBalloon();
	}); 


	// Enable the Earth map type
/*	map.addMapType(G_SATELLITE_3D_MAP);
	var mapControl = new GMapTypeControl();
	map.addControl(mapControl);
	map.setMapType(G_SATELLITE_3D_MAP);*/
}

var clickOpened = false;
var customIcons = [];
var gmap;
var zoomedMap = false;
var oldStyle = new Array();
var _highlightedMarker;
var globalMapLevel;

// Config:
var overlayKaartVisible = true;
var googleKaartVisible = false;		// een debug-vlaggetje
var debugOn = false;
var disableLoggingEntirely = true;
var balloonShowEvent = "mouseover";
var summarizeBalloonContent = false;
var savePositionsToCookie = false;
var legendCollapsed = true;
var legendPositionX = 518;//0;
var legendPositionY = -25;//-18;//-250;
var showLinksOnHover = true;
var limitZoom = true;

//include('http://files.archieven.nl/0/mi_files/js/drag2.js');	// only works in Firefox

//-------------------------------------------------------------------

// http://www.codeproject.com/KB/scripting/dom-element-abs-pos.aspx

var __isIE =  navigator.appVersion.match(/MSIE/);
var __userAgent = navigator.userAgent;
var __isFireFox = __userAgent.match(/firefox/i);
var __isFireFoxOld = __isFireFox && 
   (__userAgent.match(/firefox\/2./i) || __userAgent.match(/firefox\/1./i));
var __isFireFoxNew = __isFireFox && !__isFireFoxOld;

function __parseBorderWidth(width) {
    var res = 0;
    if (typeof(width) == "string" && width != null 
                && width != "" ) {
        var p = width.indexOf("px");
        if (p >= 0) {
            res = parseInt(width.substring(0, p));
        }
        else {
             //do not know how to calculate other 
             //values (such as 0.5em or 0.1cm) correctly now
             //so just set the width to 1 pixel
            res = 1; 
        }
    }
    return res;
}

//returns border width for some element
function __getBorderWidth(element) {
    var res = new Object();
    res.left = 0; res.top = 0; res.right = 0; res.bottom = 0;
    if (window.getComputedStyle) {
        //for Firefox
        var elStyle = window.getComputedStyle(element, null);
        res.left = parseInt(elStyle.borderLeftWidth.slice(0, -2));  
        res.top = parseInt(elStyle.borderTopWidth.slice(0, -2));  
        res.right = parseInt(elStyle.borderRightWidth.slice(0, -2));  
        res.bottom = parseInt(elStyle.borderBottomWidth.slice(0, -2));  
    }
    else {
        //for other browsers
        res.left = __parseBorderWidth(element.style.borderLeftWidth);
        res.top = __parseBorderWidth(element.style.borderTopWidth);
        res.right = __parseBorderWidth(element.style.borderRightWidth);
        res.bottom = __parseBorderWidth(element.style.borderBottomWidth);
    }
   
    return res;
}

//returns absolute position of some element within document
function getElementAbsolutePos(element) {
    var res = new Object();
    res.x = 0; res.y = 0;
    if (element !== null) {
        res.x = element.offsetLeft;
        res.y = element.offsetTop;
        
        var offsetParent = element.offsetParent;
        var parentNode = element.parentNode;
        var borderWidth = null;

        while (offsetParent != null) {
            res.x += offsetParent.offsetLeft;
            res.y += offsetParent.offsetTop;
            
            var parentTagName = offsetParent.tagName.toLowerCase();    

            if ((__isIE && parentTagName != "table") || 
                (__isFireFoxNew && parentTagName == "td")) {            
                borderWidth = __getBorderWidth(offsetParent);
                res.x += borderWidth.left;
                res.y += borderWidth.top;
            }
            
            if (offsetParent != document.body && 
                offsetParent != document.documentElement) {
                res.x -= offsetParent.scrollLeft;
                res.y -= offsetParent.scrollTop;
            }

            //next lines are necessary to support FireFox problem with offsetParent
               if (!__isIE) {
                while (offsetParent != parentNode && parentNode !== null) {
                    res.x -= parentNode.scrollLeft;
                    res.y -= parentNode.scrollTop;
                    
                    if (__isFireFoxOld) {
                        borderWidth = __getBorderWidth(parentNode);
                        res.x += borderWidth.left;
                        res.y += borderWidth.top;
                    }
                    parentNode = parentNode.parentNode;
                }    
            }

            parentNode = offsetParent.parentNode;
            offsetParent = offsetParent.offsetParent;
        }
    }
    return res;
}

