var sLayer="";
var iWait=0;
var map;
var lat=437411.756493507
var lon=87896.6527196653
Proj4js.defs["EPSG:28992"] = "+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.999908 +x_0=155000 +y_0=463000 +ellps=bessel +towgs84=565.2369,50.0087,465.658,-0.406857330322398,0.350732676542563,-1.8703473836068,4.0812 +units=m +no_defs";

var File;
var MilieuZone;
var aFeatureSelects=Array();
var RDprojection
var borderfound=0;
var tt;
var RoadDetours;
var selectedFeature=0;
var optionsKML="";


$(document).ready(function(){

	setEventHandlers();
	
});

function setEventHandlersRechterdeel() {
	$("#rechterdeel").sortable({
		handle : '.topregel_groot, .topregel_klein',
		update: function() {
			saveSequence();
		},
		start: function() {
			$("#blok_informatie_portlet").css("display","none");	
		},
		opacity: 0.7,
		accept:"movable",
		helperclass: "sort_placeholder"
	});
	
	// sidekick buttons
	$(".sidekick_button_kruis").click(function () {
		// uncheck checkbox in toevoegen-onderdelen-form voor deze sidekick
		iDivObjId=$(this).parent().parent().parent().attr("id");
		iDivObjId=iDivObjId.substr(iDivObjId.indexOf("_")+1);
		try {
			eval("document.frmBlokVoegtoe.checkbox_" + iDivObjId).checked=false;
			
			oToDelete=$(this).parent().parent().parent().parent().parent();
			oToDelete.hide("slow");
			oToDelete.remove();
			saveSequence();
		} catch(e) {
			// sst...
		}
		
	});
	$(".sidekick_button_minus").click(function () {
		minifyMe($(this).attr("id"));
	});
	
	// "voeg onderdeel toe" en "herstel pagina" knoppen boven sidekicks
	$("#blok_voegtoe").click(function() {
		$("#blok_voegtoe_selectie").show();
	});
	
	$("#blok_herstel").click(function() {
		if (confirm('Weet u zeker dat u de site in de standaard weergave wilt openen?')) {
			setLayersToStandard(); // feitelijk; klap alle layers in.
			saveSequenceStandard(); // zet blokken terug op standaard volgorde en modus
		}
	});	
}

function setEventHandlers() {
	
	// layer buttons
	$(".hoofd_knop").click(function() {
		sId=this.id;
		sId=sId.substr(10);
		// $(".select_all_checkbox").hide();
		
		oButtonContainer=$(this).closest(".button_container");
		
		oButtonSubKnoppen=oButtonContainer.find(".button_sub_knoppen");
		if (oButtonSubKnoppen.css("display")=="none") {
			oButtonSubKnoppen.parent().animate({width: (oButtonSubKnoppen.width() + 33) + "px"},'fast');
			oButtonSubKnoppen.show("slow",function() {
				
			});
			$(this).siblings(".select_all_checkbox").css("display","block");
			$.ajax({
				url:"main.php?name=portlet&friendly_url=" + escape(sId + "_informatie_tekst"),
				success:function(data) {
					$("#blok_informatie_portlet_content").html(data);
					$("#blok_informatie_portlet").show(1000);
				}
			});
			
		} else {			
			oButtonSubKnoppen.hide("fast", function() {
				oButtonSubKnoppen.parent().animate({width:"33px"}, "slow");
			});
			$(this).siblings(".select_all_checkbox").css("display","none");
		}
		
	}); 

	$(".select_all_checkbox").click(function() {
		sId=$(this).attr("id");
		sParentSubCheckboxesId=sId.substr(20);
		sParentSubCheckboxesId="#button_sub_knoppen_"+sParentSubCheckboxesId;
		if ($(this).attr('checked')) { // input:unchecked pakt ook checked input boxes?? daarom handmatige iteratie 
			$(sParentSubCheckboxesId).find('input').each(function() {
				if (!$(this).attr("checked")) {
					$(this).click();
				}
			});	
		} else {
			$(sParentSubCheckboxesId).find('input:checked').click();	
		}
	});

	setEventHandlersRechterdeel();
}

function minifyMe(sId) {
	oPortlet=$("#"+sId).closest(".div_render"); // zoek voor de content die binnen deze content container te vinden is.
	oPortletContent=oPortlet.find(".portlet_content");
	sDivId=oPortlet.attr("id").substr(12);
	if ($("#"+sId).attr("src").indexOf("dicht")>0) { // portlet is geminimaliseerd, maximaliseer
		$("#"+sId).attr("src","images/client/stadsregio25/icoon_blokje_open01.png");
		// alert(oPortletContent.height());
		oPortlet.animate({height:(oPortletContent.height() + 23) + 'px'},1000);
		setModeCookie(sDivId,"max");
	} else { // portlet is gemaximaliseerd, minimaliseer
		$("#"+sId).attr("src","images/client/stadsregio25/icoon_blokje_dicht01.png");
		// alert(oPortlet.attr("id"));
		oPortlet.animate({height:HEIGHT_MIN_PORTLET + 'px'},50);
		setModeCookie(sDivId,"min");
	}
}

function hideMe(sId) { // wrapper om $.hide heen
	$(sId).hide()
}

window.onresize=function () {
	iWait++;
}
	
function resizeCheck() {
	if (iWait>0) {
		iWait=0;
		setMapCorners();
	}
	setTimeout("resizeCheck()",1500);
}

function saveSequence() {
	var sSequence="";
	$("#rechterdeel .movable").each(function(iIndex) {
		sId=$(this).children()[0].id;
		if (sId.indexOf("div_element_")>-1) {
			sSequence=sSequence + sId.substr(12) + ";";
		}
	}
	);
	
	setSequenceCookie(sSequence);
}

function saveSequenceFromForm() {
	var sSequence="";
	for (i = 0; i < document.frmBlokVoegtoe.length; i++) {
		if (document.frmBlokVoegtoe[i].checked) {
			sSequence=sSequence + document.frmBlokVoegtoe[i].name.substr(9) + ";";
		}
	}
	
	setSequenceCookie(sSequence);
	
	// reload rechterbalk
	$.ajax({
		url:'main.php?name=rechterdeel',
		success: function (data) {
			$("#rechterdeel").html(data);
			// setEventHandlers();
			setEventHandlersRechterdeel();
		}
	});
	// window.location.href='main.php'; // refresh
	
}

function saveSequenceStandard() {
	var sSequence="";
	
	$(".checkbox_startpagina_standaard").each(function () {
		sSequence=sSequence + $(this).attr("id").substr(9) + ";";
		setModeCookie($(this).attr("id").substr(9),"max"); // klap items uit
	}); 
	setSequenceCookie(sSequence);
	
	window.location.href='main.php'; // refresh
}

function setSequenceCookie(sSequence) {
	var dExpire = new Date();
	dExpire.setDate(dExpire.getDate() + 90); // add 90 days
	
	sCookieString = "sequence=" + escape( sSequence ) +
		";expires=" + dExpire.toGMTString() +
		";path=/" +
		";domain="+sDomain;
	
	document.cookie=sCookieString;
}

function setModeCookie(sElement,sMode) {
	
	var dExpire = new Date();
	dExpire.setDate(dExpire.getDate() + 90); // add 90 days
	
	sCookieString = "element_"+sElement+"=" + escape( sMode ) +
		";expires=" + dExpire.toGMTString() +
		";path=/" +
		";domain="+sDomain;
	
	document.cookie=sCookieString;
}

function setLayersToStandard() {
	$(".button_sub_knoppen input").each(function() {
		if ((this.name=="waw_hinder_4") || (this.name=="file")) {
			$(this).attr("checked",true);
		} else {
			$(this).attr("checked",false);
		}
	});
	addLayersToCookie();
}

function addLayersToCookie() {
	
	sLayers="";
	
	$(".button_sub_knoppen input").each(function() {
		
		if (this.checked) {
			if ($(this).attr("name")!="") {
				sLayers=sLayers + $(this).attr("name") + "|";
			}
		}
	});
	
	if (sLayers!="") sLayers=sLayers.substr(0,sLayers.length-1); 
	// printInDebug("layers:" + sLayers);
	
	var dExpire = new Date();
	dExpire.setDate(dExpire.getDate() + 90); // add 90 days

	sCookieString = "layers=" + escape( sLayers ) +
		";expires=" + dExpire.toGMTString() +
		";path=/" +
		";domain="+sDomain;
	
	document.cookie=sCookieString;
}

function setMapCorners() {
	iWidthScreen = $(window).width();
	pMapWidth = iWidthScreen - 310; // 310 is max width rechterdeel
	
	pMap = $("#map").position();
	pMapLeft = pMap.left;
	pMapTop = pMap.top;
	// pMapWidth = $("#map").width();
	pMapWidth=pMapWidth - 20; // - 20 voor margins links en rechts.
	$("#linkerdeel").css({"width": pMapWidth + "px" }); 
	$("#map").css({"width": (pMapWidth - 2) + "px" }); 
	
	// pMapHeight = $("#map").height();
	pMapHeight = $(window).height() - 130; // - 130 voor button balk en marge
	$("#map").css({"height": pMapHeight + "px" });
	
	pMapRight = pMapLeft + pMapWidth - 5; // -5 voor compensatie breedte corner
	pMapBottom = pMapTop + pMapHeight - 5;
	pLineHeight = pMapHeight - 10;
	pLineWidth = pMapWidth - 10;
	
	$("#kaart_linkerbovenhoek").css({ "display":"block", "left": pMapLeft+"px", "top": pMapTop + "px" });
	$("#kaart_rechterbovenhoek").css({ "display":"block", "left": pMapRight+"px", "top": pMapTop + "px" });
	$("#kaart_linkeronderhoek").css({ "display":"block", "left": pMapLeft+"px", "top": pMapBottom + "px" });
	$("#kaart_rechteronderhoek").css({ "display":"block", "left": pMapRight+"px", "top": pMapBottom + "px" });
	
	$("#kaart_lijn_links").css({ "display":"block", "left": pMapLeft +"px", "top": (pMapTop + 5) + "px", "height": pLineHeight + "px", "width": "1px" });
	$("#kaart_lijn_top").css({ "display":"block", "left": (pMapLeft + 5) +"px", "top": pMapTop + "px", "height": "1px", "width": pLineWidth + "px" });
	$("#kaart_lijn_rechts").css({ "display":"block", "left": (pMapRight + 3) +"px", "top": (pMapTop + 5) + "px", "height": pLineHeight + "px", "width": "2px" });
	$("#kaart_lijn_onder").css({ "display":"block", "left": (pMapLeft + 5) +"px", "top": (pMapBottom + 3) + "px", "height": "2px", "width": pLineWidth + "px" });
	
	// alert($("#kaart_linkerbovenhoek"));
}


function getTileUrl(bounds) {
	/*
      var res = this.map.getResolution();
      var x = Math.round ((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
      var y = Math.round ((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
      var z = this.map.getZoom();
	 */
	
	b=this.map.getZoom() + 10;
	
	var res = this.map.getResolution();
	var ax = Math.round ((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
	var ay = Math.round ((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
	var z = this.map.getZoom();
	
	// $("#debug_coord").html($("#debug_coord").html() + 'x=' + ax + ',y=' + ay + ',b='+b + '<br />');
	
	level = 17-b+1;	// zoom 17 gm = zoom 1 falk
	tm = 307.2*Math.pow(2, level-1);
	ax = Math.round(ax*tm) - 20132659;
	ay = 20132659 - Math.round((ay+1)*tm);
	
	
	//url = "http://tileserver.tijdreizen.andes.nl/ts-gm-nl/servlet/ts?x=" + ax + "&y=" + ay + "&z=" + level ;
	url = "http://nlgmjac1.ts.andes.nl/nl-gm-current-jacana/servlet/ts?x=" + ax + "&y=" + ay + "&z=" + level ;
	// $("#debug_coord").html(url);
	return url;
}

function initMap(){
	var RDprojection = new OpenLayers.Projection("EPSG:28992");
	var options = {
		controls: [
			new OpenLayers.Control.PanZoomBar(),
			new OpenLayers.Control.Navigation()
		],
		
		projection: new OpenLayers.Projection("EPSG:900913"),
		displayProjection: new OpenLayers.Projection("EPSG:4326"),
		units: "m",
		maxResolution: 152.87405654296876,
		maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34)
	};

	optionsKML= {
		format: OpenLayers.Format.KML,
		projection: RDprojection,
		formatOptions: {
			extractStyles: true,
			extractAttributes: true
		}
	};
	map = new OpenLayers.Map('map',options);
	
	
	// falkmap = new GMapType(tilelayers, new GMercatorProjection(18), "Map",{errorMessage:"geen data beschikbaar"});
	// var Gmap = new OpenLayers.Layer.Google(falkmap,{type:falkmap,sphericalMercator:true, minZoomLevel: 10, maxZoomLevel: 17});
	var Tmap = new OpenLayers.Layer.TMS("TMap", "http://geenrelevanteurlnodig/", {
		'tileSize':new OpenLayers.Size(256,256),
		'type':'png',
		'getURL':getTileUrl ,
		'numZoomLevels':8});
	
	//Auto layers
	// File = new OpenLayers.Layer.GML("File", "main.php?name=file", optionsKML);
	// MilieuZone = new OpenLayers.Layer.GML("MilieuZone", "main.php?name=Milieuzone", optionsKML);
	// RoadDetours = new OpenLayers.Layer.GML("Detours", "main.php?name=road_detours", optionsKML);
	// AllLayers = new OpenLayers.Layer.GML("AllLayers", "main.php?name=AllLayers", optionsKML);
	Rijkswegen = new OpenLayers.Layer.GML("Rijkswegen", "static_layers/rijkswegen.kml", optionsKML);
	Mist = new OpenLayers.Layer.GML("Mist", "main.php?name=Mist", optionsKML);
	//Wawzone = new OpenLayers.Layer.GML("Mist", "main.php?name=wawzone", optionsKML);
	var Andes = new OpenLayers.Layer.Vector("Simple Geometry",
                              {attribution:"<a href='http://www.andes.nl' target='_blank'><img src='images/client/stadsregio25/andes.png' height='25px'></a>"});
	aFeatureSelects=[];
	map.addLayers([Tmap,Rijkswegen,Mist,Andes]);
	
	initMapGeneric(optionsKML);

	
	Rijkswegen.setVisibility(false);
	// RoadDetours.setVisibility(false);
	
	
	selectControl = new OpenLayers.Control.SelectFeature(aFeatureSelects, {onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});		
	map.addControl(selectControl);		
	
	selectControl.activate();
	
	map.addControl(new OpenLayers.Control.Navigation());
	map.addControl(new OpenLayers.Control.Attribution());
	
	if (map_action=='') { // in het geval er een map_action uitgevoerd wordt, zal die map_action de zoom doen
		map.zoomToMaxExtent();
		map.setCenter(new OpenLayers.LonLat(lon,lat).transform(new OpenLayers.Projection("EPSG:28992"), map.projection),1);
	}
	
	map.events.register("zoomend", map, function(){
		setVisibilityOfSupportLayers();
		setVisibilityOfFeatures();
	});
	
	Mist.setVisibility(true);
	Andes.setVisibility(true);	
}

function onPopupClose(evt) {
	selectControl.unselect(selectedFeature);
}

function portlet(iObjId) {
	$.ajax({
		url:"main.php?name=portlet&obj_id=" + escape(iObjId),
		success:function(data) {
			if (data.indexOf('class="veldwaarde"')>-1) {
				$("#blok_informatie_portlet_content").html(data);
				$("#blok_informatie_portlet").show(1000);
			}
		}
	});
}

function portletFriendlyUrl(sFriendlyUrl) {
	$("#blok_informatie_portlet").hide(1000);
	sFriendlyUrl=sFriendlyUrl.toLowerCase();
	$.ajax({
		url:'main.php?name=portlet&friendly_url=' + escape(sFriendlyUrl),
		success: function (data) {
			if (data.indexOf("warning.gif") > -1 ) {
				// mislukt!
			} else {
				$("#blok_informatie_portlet_content").html(data);
				$("#blok_informatie_portlet").show(1000);
			}
		}
	});
}

function portlet_close(){
	$("#blok_informatie_portlet").hide(100);
}

function zoomInForObj(iObjId,sMode) {
       $.ajax({url:"main.php?name=coord&obj_id="+iObjId, context:document.body, success:function(sData) {
		sX=sData.substr(0,sData.indexOf(","));
		sY=sData.substr(sData.indexOf(",")+1);
		
		// sx en sy zijn in rd, niet lon/lat
		// zoomInToRd(sX,sY); zoomin is niet meer nodig, showPopupForFeature zoomt automatisch al in op feature
		
		showPopupForFeatureTimed(iObjId);
	       
       }});
}


function zoomInToXYRd(x,y,zoom) { // x,y in RD
	map.setCenter(new OpenLayers.LonLat(x,y).transform(new OpenLayers.Projection("EPSG:28992"), map.projection),parseInt(zoom));      
}

function zoomInToXY(x,y,zoom) { // x,y in lon/lat
	map.zoomToMaxExtent();
	map.setCenter(new OpenLayers.LonLat(x,y),parseInt(zoom));
}

function showPopupForFeatureTimed(iFeatureId) {
	if (!showPopupForFeature(iFeatureId,'popmeupnow')) {
		setTimeout("showPopupForFeatureTimed('"+iFeatureId+"')",100);
	}
}

function showPopupForFeature(iFeatureId,sMode) {
	bFoundOne=false;
	var oFeature;
	// laat juiste icoonlaag en icoon ballon zien.
	// zoek feature met dit obj_id		       
	for(i=0;i<aFeatureSelects.length;i++) {
		// hier uit rollen alle layers, maar we willen alleen zoeken in actieve layers
		if (aFeatureSelects[i].activatedByMap==true) {
			/*
				verschillende modi:
				- als de pagina nog bezig is te laden, moet er op de loadend event de popup geopend worden (bijv. aanroep van obj_id in url).
				- indien de popup getoond moet worden in een al geladen pagina, dan wordt direct onFeatureSelect aangeroepen (bijv. klik op waw in container wegwerkzaamheden).
			*/
			if (sMode=="popmeuponloadend") {
				// speur layer af, nadat deze is geladen, op gewenste feature
				aFeatureSelects[i].events.register("loadend", aFeatureSelects[i], function() {
					oActiveLayer=this.features;
					for(j=0;j<oActiveLayer.length;j++) {
						oFeature=oActiveLayer[j];
						if (oFeature.attributes.featureId==iFeatureId) {
							i=aFeatureSelects.length;
							lonlat=oFeature.geometry.getBounds().getCenterLonLat();
							map.setCenter(lonlat,5);
							onFeatureSelect(oFeature); // laat popup zien voor gevonden obj
							break;
						}
					}
				});
			} else if (sMode=="popmeupnow") {
				// layer is al geladen, loop layer af om gewenste feature te vinden
				oActiveLayer=aFeatureSelects[i].features;
				for(j=0;j<oActiveLayer.length;j++) {
					oFeature=oActiveLayer[j];
					if (oFeature.attributes.featureId==iFeatureId) {
						lonlat=oFeature.geometry.getBounds().getCenterLonLat();
						
						map.setCenter(lonlat,5);
						onFeatureSelect(oFeature); // laat popup zien voor gevonden obj
						i=aFeatureSelects.length;
						bFoundOne=true;
						break;
					}
				}
			} else if (sMode=="popmeuponvisibilitychange") {
				// speur layer af, nadat deze is geladen, op gewenste feature
				aFeatureSelects[i].events.register("visibilitychanged", aFeatureSelects[i], function() {
					oActiveLayer=this.features;
					for(j=0;j<oActiveLayer.length;j++) {
						oFeature=oActiveLayer[j];
						if (oFeature.attributes.featureId==iFeatureId) {
							i=aFeatureSelects.length;
							lonlat=oFeature.geometry.getBounds().getCenterLonLat();
							map.setCenter(lonlat,5);
							onFeatureSelect(oFeature); // laat popup zien voor gevonden obj
							break;
						}
					}
				});
			}
		
		
		}
	
	}
	
	return bFoundOne;
}

function onFeatureSelect(feature) {
	if (selectedFeature) {
		if (selectedFeature.popup!=null) {
			onFeatureUnselect(selectedFeature);
		}
	}
	if (feature.attributes.hasPortlet=="true") {portlet(feature.attributes.featureId)}
	selectedFeature = feature;
	popup = new OpenLayers.Popup.FramedCloud("stadsregio",
	feature.geometry.getBounds().getCenterLonLat(),
	new OpenLayers.Size(100,100),
	"<div class='ballon_container'><h2>"+feature.attributes.name + "</h2>" + feature.attributes.description + "</div>",
	null, true, onPopupClose);
	feature.popup = popup;
	map.addPopup(popup);
}

function onFeatureUnselect(feature) {
	map.removePopup(feature.popup);
	feature.popup.destroy();
	feature.popup = null;
	
	portlet_close();
}

function showAddress(address) {
	var geocoder = new GClientGeocoder();
	if (geocoder) {
		geocoder.getLatLng(
		address + " , Rotterdam, the Netherlands",
		function(point) {
			if (!point) {
				alert(address + " werd niet gevonden");
			} else {
				var markers = new OpenLayers.Layer.Markers("Marker");
				var size = new OpenLayers.Size(27,24);
				var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
				var icon = new OpenLayers.Icon('images/client/stadsregio25/marker01.png',size,offset);
				markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(point.x,point.y).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), icon));
				map.addLayer(markers);	
				map.setCenter(new OpenLayers.LonLat(point.x,point.y).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")),6);
			}
		});
	}
}

function setVisibilityOfSupportLayers() {
	// based on the new constellation of visible layers, check if we need activate or deactive support layers.
	bWawLayersVisible=false;
	bFileLayersVisible=false;
	iResolution=Math.round(map.getResolution());
	
	if ((iResolution > 10) && (Gemeente.getVisibility())) {
		Gemeente.setVisibility(false);
	}
	
	/* deze worden aan gevinkt door setVisibilityOfFeatures()  
	for(i=0;i<map.layers.length;i++) {
		oMapLayer=map.layers[i];
		sName=oMapLayer.name;
		if ((sName.indexOf("waw_hinder_")>-1) && (oMapLayer.getVisibility())) {
			bWawLayersVisible=true;
		}
	}
	*/
	
	// indien file layer aan staat, moeten we, op basis van niveau, de file layer tonen
	if (document.frmButtons.file.checked) {
		bFileLayersVisible=true;
	} else {
		bFileLayersVisible=false;
		/*
		for(i=0;i<map.layers.length;i++) {
			oMapLayer=map.layers[i];
			sName=oMapLayer.name.toLowerCase();
			if ((sName.indexOf("file")>-1) && (oMapLayer.getVisibility())) {
				bFileLayersVisible=true;
			}
		}
		*/
	}
	File.setVisibility(false);
	FileLaag1.setVisibility(false);
	FileLaag2.setVisibility(false);
	FileLaag3.setVisibility(false);
	FileLaag4.setVisibility(false);
	FileLaag5.setVisibility(false);
	FileLaag6.setVisibility(false);
	FileLaag7.setVisibility(false);
	if (bFileLayersVisible) {
		Drips.setVisibility(true);
		FileIcon.setVisibility(true);
		if (iResolution==1) {
			FileLaag1.setVisibility(true);
		} else if (iResolution==2) {
			FileLaag2.setVisibility(true);
		} else if (iResolution==5) {
			FileLaag3.setVisibility(true);
		} else if (iResolution==10) {
			FileLaag4.setVisibility(true);
		} else if (iResolution==19) {
			FileLaag5.setVisibility(true);
		} else if (iResolution==38) {
			FileLaag6.setVisibility(true);
		} else if (iResolution==76) {
			FileLaag7.setVisibility(true);
		} else {
			File.setVisibility(true);
		}
	} else {
		Drips.setVisibility(false);
		FileIcon.setVisibility(false);
	}
	
	// printInDebug(iResolution);
	
	if (iResolution <= 10) {
		Mist.setVisibility(false);
	} else {
		Mist.setVisibility(true);
	}
	
	
}

function setRoadDetoursForSeverity(sSeverity,bVisibility) {
	
	if (sSeverity=="1") {
		RoadDetours1.setVisibility(bVisibility);
	} else if (sSeverity=="2") {
		RoadDetours2.setVisibility(bVisibility);
	} else if (sSeverity=="3") {
		RoadDetours3.setVisibility(bVisibility);
	} else if (sSeverity=="4") {
		RoadDetours4.setVisibility(bVisibility);
	}
	
	/*
	for(j=0;j<features.length;j++) {
		oFeature=features[j];
		if (oFeature.attributes.severity==sSeverity) {
			oFeature.style.fillOpacity=sOpacity;
			oFeature.style.strokeOpacity=sOpacity;
		}
	}
	*/
	
	
	/*
	features=WawArrows.features;
	for(j=0;j<features.length;j++) {
		oFeature=features[j];
		if (oFeature.attributes.severity==sSeverity) {
			if (sOpacity=='0.0') {
				oFeature.style.display='none';
			} else {
				oFeature.style.display='block';
			}
			// printInDebug('uit aan het zetten...');
		}
	}
	*/
}

function setVisibilityOfFeatures() {
	// determines which features should be active, given the current layer state
	iResolution=Math.round(map.getResolution());
	/*
	if (iResolution>10) {
		// we zijn te ver uitgezoomd, per default laat de roaddetour layer niet zien
		setRoadDetoursForSeverity("1",false);
		setRoadDetoursForSeverity("2",false);
		setRoadDetoursForSeverity("3",false);
		setRoadDetoursForSeverity("4",false);
		// WawArrows.setVisibility(false);
	} else {
		for(i=0;i<map.layers.length;i++) {
			oMapLayer=map.layers[i];
			sName=oMapLayer.name;
			if ((sName.indexOf("waw_hinder_")>-1)) {
				sSeverity=sName.substr(11,1);
				if (oMapLayer.getVisibility()) {
					setRoadDetoursForSeverity(sSeverity,true); // turn detours on
				} else {
					setRoadDetoursForSeverity(sSeverity,false); // turn detours off
				}
			}
		}
		// redraw RoadDetours:
		// RoadDetours.setVisibility(false);
		// RoadDetours.setVisibility(true);
		// WawArrows.setVisibility(false);
		// WawArrows.setVisibility(true);
	}
	*/
}

function setVisibility(oLayer,bValue) {
	oLayer.setVisibility(bValue);
	setVisibilityOfSupportLayers();
}

function toggleLayer(oLayer,oCheckbox) {
	if (oCheckbox.checked) {
		setVisibility(oLayer,true);	
		portletFriendlyUrl(oLayer.name + '_informatie');
	} else {
		setVisibility(oLayer, false)
	}
	
	addLayersToCookie();
	setVisibilityOfFeatures();
	
}

function turnLayerOn(sName, oLayer,oCheckbox) {
	
	try {
		
		oCheckbox.checked=true;
		addLayersToCookie();
		$(oCheckbox).parent().parent().show("slow");
		$(oCheckbox).parent().parent().parent().find(".select_all_checkbox").css("display","block");
		setVisibility(oLayer,true);
		// printInDebug('layer ['+oLayer.getVisibility()+']!');
		
	} catch(e) {
		// printInDebug('failed ['+sName+']!');
	}
}

function printInDebug(si) {
	$("#debug_coord").html($("#debug_coord").html() + si + '<br />');
}

function setPortletInfoForLayer(sName) {
	
}

function showCMSContent(sUrl) {
	$.unblockUI();
	$.blockUI.defaults.applyPlatformOpacityRules = false;
	$.ajax({
		url:sUrl,
		async:false,
		success: function(data) {
			$.blockUI({
				message:'<div id="cms_overlay_content_close" onclick="$.unblockUI();"><img src="images/client/stadsregio25/overlay_sluiten.jpg" /></div><div id="cms_overlay_content">' + data + '</div>',
				css:{
					textAlign:'left',
					zIndex:'9999',
					padding:'0px',
					top:'15%',
					left:'15%',
					width:'70%',
					height:'60%',
					overflow:'auto',
					borderWidth:'1px',
					marginLeft:'auto',
					marginRight:'auto',
					cursor:'pointer'
				}
			});
		}
	});
}

function closeCMSContent() {
	$.unblockUI();
}

function sConstructHref() {
	/*
	 * Verzamel huidige x,y, zoomlevel, zichtbare layers _en_ huidige popup!
	 */
	x=map.center.lon;
	y=map.center.lat;
	zoom=map.zoom;
	sSelectedFeatureId="";
	if (selectedFeature) {
		sSelectedFeatureId=selectedFeature.attributes.featureId;
	}
	sLayers="";

	$(".button_sub_knoppen input").each(function() {
		if (this.checked) {
			if ($(this).attr("name")!="") {
				sLayers=sLayers + $(this).attr("name") + "|";
			}
		}
	});
	if (sLayers!="") sLayers=sLayers.substr(0,sLayers.length-1); 
	
	sHref=base_url + "main.php?map_action=zoomtoxy&x=" + x + "&y="+ y + "&zoom=" + zoom + '&selected_feature_id='+sSelectedFeatureId+'&forced_layers=' + sLayers;
	
	return sHref;
}

function openRoutePlanner(iObjId) {
	$.unblockUI();
	$.blockUI.defaults.applyPlatformOpacityRules = false;
	$.ajax({
		url:'main.php?name=ov9292_frame&obj_id=' + iObjId,
		async:false,
		success: function(data) {
			$.blockUI({
				message:'<div id="cms_overlay_content_close" onclick="$.unblockUI();"><img src="images/client/stadsregio25/overlay_sluiten.jpg" /></div><div id="cms_overlay_content">' + data + '</div>',
				css:{
					textAlign:'left',
					zIndex:'9999',
					padding:'0px',
					top:'15%',
					left:'15%',
					width:'70%',
					height:'520px',
					overflow:'auto',
					borderWidth:'1px',
					marginLeft:'auto',
					marginRight:'auto',
					cursor:'pointer'
				}
			});
		}
	});
}

var active_road_activity_id='';

function determineCaptionForWaw(sRoadactivityId) {
	if (active_road_activity_id==sRoadactivityId) {
		$("#toon_omleiding_"+sRoadactivityId).html('Verberg omleiding');
	} else {
		$("#toon_omleiding_"+sRoadactivityId).html('Toon omleiding');
	}
}

function displayDetourForWaw(sRoadactivityId) {	
	// verwijder eerst huidige roaddetourslayer
	RoadDetoursSingle.setVisibility(false);
	
	// bepaal wat we moeten doen; alleen verbergen of ook actief maken van laag
	
	if (active_road_activity_id!=sRoadactivityId) { // ander wegwerkje, dus toon deze
		map.removeLayer(RoadDetoursSingle);
		// maak nieuwe layer aan voor detour
		RoadDetoursSingle = new OpenLayers.Layer.GML("road_detours_single", "main.php?name=road_detours_single&srr_roadactivity_id=" + escape(sRoadactivityId), optionsKML);
		map.addLayers([RoadDetoursSingle]);
		RoadDetoursSingle.setVisibility(true);
		active_road_activity_id=sRoadactivityId;
		// verander link tekst
		determineCaptionForWaw(sRoadactivityId);
	} else { // zelfde wegwerkje, is nu verbogen
		active_road_activity_id='';
		determineCaptionForWaw(sRoadactivityId);
	}
}

