var map;
var geocoder = null;
var addressMarker;
var cluster;
var activeOrganisationType = 0;
var activeProjectType = 0;
var projectsoorten;
var markertype;

	function newMarker(markerLocation, markerId, location, streetaddress, projects, organisationtype, selectedproject) {
				
		var markerIcon = "";
		//if(!organisationtype) organisationtype = 0;
		if(projects.length>1 && selectedproject==0) {
			//for (var i = 0; i < projects.length; i++) {
			//	if(markertype==2) {
			//		if((projects[i].projecttype) == 21) var markerIcon = 'legenda2.0/21-verbetertrajectenplus.png';
			//	} else {
			//		if((projects[i].projecttype) == 21) var markerIcon = 'legenda/21-verbetertrajectenplus.png';				
			//	}
			//}
			if(markertype==2) {
				//if(markerIcon=="") var markerIcon = 'legenda2.0/00-meerprojecten.png';
				 var markerIcon = 'legenda2.0/00-meerprojecten.png';
			} else {
				//if(markerIcon=="") var markerIcon = 'legenda/00-meerprojecten.png';
				var markerIcon = 'legenda/00-meerprojecten.png';
			}
		} else if(selectedproject>0) {
				var markerIcon = 'legenda/'+projectsoorten[selectedproject-1].project_type_icoon;					
		} else if(projects.length==1) {
			//var markerIcon = 'legenda/'+projectTypeIcons[projects[0].projecttype][0];
			if(markertype==2) {
					var markerIcon = 'legenda2.0/'+projectsoorten[projects[0].projecttype-1].project_type_icoon;
			} else {
				var markerIcon = 'legenda/'+projectsoorten[projects[0].projecttype-1].project_type_icoon;		
			}
		} else if(projects.length==0) {
			if(markertype==2) {
				var markerIcon = 'images2.0/o'+organisationtype+'.png';
			} else {
				var markerIcon = 'images/o'+organisationtype+'.png';		
			}	
		} else {
			var markerIcon = 'legenda/'+projectsoorten[projects[0].projecttype-1].project_type_icoon;
		}
		
		var baseIcon = new GIcon();
		baseIcon.iconSize = new GSize(26, 26);
		baseIcon.iconAnchor = new GPoint(12, 12);
		baseIcon.infoWindowAnchor = new GPoint(12, 0);
		if(markertype==2) {
			baseIcon.shadow = "legenda2.0/o"+organisationtype+".png";
			baseIcon.shadowSize = new GSize(26, 26);
			baseIcon.infoShadowAnchor = new GPoint(18, 25);
  		}
		var customIcon = new GIcon(baseIcon);
	  	customIcon.image = markerIcon;
		markerOptions = {title:markerId, icon:customIcon };
	 	var marker=new GMarker(markerLocation, markerOptions);
	 	GEvent.addListener(marker, 'click', function() {
			var infobox = '<p><strong>'+markerId+'</strong><br/>'+streetaddress+'<br/>'+location+'</p>';
			for (var i = 0; i < projects.length; i++) {
				//var markerIcon = 'legenda/'+projectTypeIcons[projects[i].projecttype][0];
				var markerIcon = 'legenda/'+projectsoorten[projects[i].projecttype-1].project_type_icoon;					
				infobox += '<p><img src="'+markerIcon+'" width="26" height="26" style="vertical-align:middle" class="projecticon">';
				if(projects[i].url!="") {
					infobox += ' <a href="'+projects[i].url+'" target="_blank">'+projectsoorten[projects[i].projecttype-1].project_type_name+'</a>';
				} else {
					infobox += ' <a href="'+projectsoorten[projects[i].projecttype-1].project_type_url+'" target="_blank">'+projectsoorten[projects[i].projecttype-1].project_type_name+'</a>';
				}
				infobox += '</p>';
			}
	  		marker.openInfoWindowHtml(infobox);
			if(jQuery.browser.msie && jQuery.browser.version.substr(0,3)=="6.0") {
				$("img.projecticon").pngfix();
			}
		});
	 	return marker;
	}


	function parseJson (map, doc, ptype, otype) {
		var marker, markersArray=[];
		var jsonData = eval("(" + doc + ")");
		for (var i = 0; i < jsonData.markers.length; i++) {
			if (cluster) cluster.removeMarkers(); 
			if(ptype==0) {
				// toon alle soorten projecten
				if(otype==0) {
					// toon alle soorten organisaties
						marker=newMarker(new GLatLng(jsonData.markers[i].geolat,jsonData.markers[i].geolong), jsonData.markers[i].name, jsonData.markers[i].location, jsonData.markers[i].streetaddress, jsonData.markers[i].projects, jsonData.markers[i].organisationtype,0);
						markersArray.push(marker);
				} else {
					// toon alleen geselecteerde organisatietype
					if(otype== jsonData.markers[i].organisationtype) {
						marker=newMarker(new GLatLng(jsonData.markers[i].geolat,jsonData.markers[i].geolong), jsonData.markers[i].name, jsonData.markers[i].location, jsonData.markers[i].streetaddress, jsonData.markers[i].projects, jsonData.markers[i].organisationtype,0);
						markersArray.push(marker);
					}
				}
			} else {
				var hasmarker = 0;
				for (var j = 0; j < jsonData.markers[i].projects.length; j++) {
					if(ptype== jsonData.markers[i].projects[j].projecttype) {
						// toon alleen geselecteerd project
						if(otype==0) {
							// toon alle organisatietypes
								if(hasmarker == 0){
									marker=newMarker(new GLatLng(jsonData.markers[i].geolat,jsonData.markers[i].geolong), jsonData.markers[i].name, jsonData.markers[i].location, jsonData.markers[i].streetaddress, jsonData.markers[i].projects, jsonData.markers[i].organisationtype, ptype);
									markersArray.push(marker);
									hasmarker = 1;
								}
						} else {
							// toon alleen het geselecteerde organisatietype
							if(otype== jsonData.markers[i].organisationtype) {
								if(hasmarker == 0){

									marker=newMarker(new GLatLng(jsonData.markers[i].geolat,jsonData.markers[i].geolong), jsonData.markers[i].name, jsonData.markers[i].location, jsonData.markers[i].streetaddress, jsonData.markers[i].projects, jsonData.markers[i].organisationtype, ptype);
									markersArray.push(marker);
									hasmarker = 1;
								}
							}
						}
					
					}
					
				}
			}
		}
		var clusterIcon = new GIcon();
		clusterIcon.image = 'legenda/00-cluster.png';
		clusterIcon.iconSize = new GSize(35, 35);
		clusterIcon.iconAnchor = new GPoint(9, 34);
		clusterIcon.infoWindowAnchor = new GPoint(9, 2);
		cluster=new ClusterMarker(map, { markers:markersArray, clusterMarkerIcon:clusterIcon, clusterMarkerTitle:'Klik om in te zoomen en %count onderliggende locaties te tonen' } );
		cluster.refresh();
		
		var instellingen = new Array("gehandicaptenzorg-instellingen", "verpleeg- en verzorgingshuizen", "GGZ-instellingen", "thuiszorg-instellingen");	
		
		
		if(ptype==0 && otype==0) {
			status = 'Getoond worden alle instellingen die meedoen aan Zorg voor Beter.';
		} else if (ptype>0 && otype>0) {
			status = 'Getoond worden alle ' + instellingen[otype-1] + ' die meedoen aan het ZVB-project ' + projectsoorten[ptype-1].project_type_name + '.';
		} else if(ptype>0 && otype==0) {
			status = 'Getoond worden alle instellingen die meedoen aan het ZVB-project ' + projectsoorten[ptype-1].project_type_name + '.';	
		} else if(ptype==0 && otype>0) {
			status = 'Getoond worden alle ' + instellingen[otype-1] + ' die meedoen aan Zorg voor Beter.';
		}
		$("#statusbericht").html(status);
				
	}

 function hasCSS() {
	var _d = document.createElement('div');
	_d.id = 'css_test';
	$('body').append(_d);
	$('#css_test').css({width:'1px',height:'1px',display:'none'});
	var _v = ($('#css_test').width() != 1) ? false : true;
	$('#css_test').remove();
	return _v;
 }

			

 function initialize(url, mtype) {
    if (hasCSS()) {	
	
	markertype=mtype;
    if (GBrowserIsCompatible()) {
		$("#statusbericht").html('<img src="images/throbber.gif"> Locatiegegevens worden geladen...');

		$("#uitleg").html('<h4>Legenda</h4><p><a href="/kaart/" id="toonalles">Toon hele kaart</a></p><form id="addressForm" action="" method="get" onsubmit="showAddress(this.address.value+\',nl\'); return false"><fieldset style="border:none;"><label for="addressInput">Plaatsnaam</label><input type="text" size="50" id="addressInput" name="address" value="" /><input type="submit" value="Toon" id="addressSubmit" /></fieldset></form>');


		map = new GMap2(document.getElementById("map_canvas"));
		var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
		
		map.addMapType(G_PHYSICAL_MAP);
		map.addControl(new GLargeMapControl(), topRight);
		map.setCenter(new GLatLng(52.14,5.23), 8, G_PHYSICAL_MAP);
		geocoder = new GClientGeocoder();
		//var statuscount = $("#statusbericht").html();


		GDownloadUrl('./json/projectsoorten.json.php', function(pdata, responseCode) {
			psData = eval("(" + pdata + ")");
			projectsoorten = psData.projectsoorten;
		});
		
		$(".selectLocaties li").hover(
	      function () {
	        $(this).addClass('hover');
	      }, 
	      function () {
	        $(this).removeClass('hover');
	      }
	    );
	    
		GDownloadUrl(url, function(data, responseCode) {
			parseJson(map, data, 0, 0);
			$(".selectLocaties li").click(function (e) { 
				e.preventDefault();

				activeType = $(this).find('a').attr('id').substring(2);			
				if($(this).find('a').hasClass('ptype')) {
					$("#legenda.selectLocaties li").each(function(){
						$(this).removeClass('active');
					});
					activeProjectType = activeType;
				} else if($(this).find('a').hasClass('otype')) {
					$("#organisatietypes.selectLocaties li").each(function(){
						$(this).removeClass('active');
					});
					activeOrganisationType = activeType;
				}
				$(this).addClass('active');
				$("#statusbericht").html('<img src="images/throbber.gif"> Locatiegegevens worden geladen...');
				parseJson(map, data, activeProjectType, activeOrganisationType);
			});
			
			$("#toonalles").click(function (e) { 
				e.preventDefault();
				$("#legenda.selectLocaties li").removeClass('active');
				$("#organisatietypes.selectLocaties li").removeClass('active');
				$("#legenda.selectLocaties li:first").addClass('active');
				$("#organisatietypes.selectLocaties li:first").addClass('active');
				$("#statusbericht").html('<img src="images/throbber.gif"> Locatiegegevens worden geladen...');
  				showAddress('');
				parseJson(map, data, 0, 0);
			});
		});

   }
  }
 }


 function showAddress(address) {
   if (geocoder) {
     geocoder.getLatLng(address,
       function(point) {
         if (!point) {
           //alert(address + " not found");
			map.setCenter(new GLatLng(52.14,5.23), 8);

         } else {
           var bounds = map.getBounds();
           if (!bounds.contains(point)) {
             map.panTo(point);
           }
			if(map.getZoom() ==13) {
			map.panTo(point) ;
			}
			else{
			map.setCenter(point,13) ;
			}
         }
       }
     );
   }
 }

 function zoomTo(country) {
   document.getElementById("addressInput").value = countryData[country].address;
   showAddress(countryData[country].address);
 }
