(function($) {
	var ver = '1.3.2';
	
	// Init Script (options en script ophalen)
	$.fn.MapMe = function(options){
		// Default options
		$.defaults = {
			addWaypointsOnClick:	false,
			animation: 				false,
			clickForElevation:		false,
			controls:				{								
										disableDoubleClickZoom:		false,
										mapTypeControl: 			false,
										mapTypeControlStyle: 		'DEFAULT', // 'DEFAULT','HORIZONTAL_BAR','DROPDOWN_MENU'
										mapTypeControlPosition: 	'DEFAULT',
										overviewMapControl:			false,
										overviewMapControlOpened:	false,
										panControl: 				false,
										panControlPosition: 		'DEFAULT',
										scaleControl: 				false,
										scaleControlPosition: 		'DEFAULT',
										scrollwheel:				true,
										streetViewControl: 			false,
										streetViewControlPosition: 	'false',
										zoomControl: 				false,
										zoomControlStyle: 			'DEFAULT', // 'DEFAULT','SMALL','LARGE'
										zoomControlPosition: 		'DEFAULT'
										// Kijk voor control posities hieronder bij $.avaiableControlPositions;
									},
			debug:					false,
			defaultCenter:			{lat:51.5688068, lng:5.074214900000015},
			directionsPanel: 		false, 		
			distancePanel: 			false, 	
			fitBounds: 				false, 
			fromAddress: 			false,
			showPanoramio:			false,
			icons: 					[],
			markers: 				[],
			markersAreDraggable:	false,
			mapType: 				'ROADMAP', 
			// Kijk voor maptypes hieronder bij $.availableMapTypes;
			routeform: 				false, 	
			setCenter: 				false,
			showRouteSteps:			false,
			toAddress: 				false, 
			travelMode: 			false,
			travelModeSelector:		false,
			travelOnLoad:			false,
			waypointSearchTimeout:	2000,
			// Kijk voor travelmodes hieronder bij $.availableTravelModes;
			zoom: 					14		
		};
		
		$.options = $.extend($.defaults, options);
		
		// AvailableTypes
		$.availableTravelModes = 		['DRIVING','WALKING']; //,'BICYCLING' -> alleen nog in de VS
		$.availableMapTypes = 			['SATELLITE','TERRAIN','HYBRID','ROADMAP','STREETVIEW'];
		$.availableControlPositions = 	['TOP_LEFT','TOP_CENTER','TOP_RIGHT','LEFT_TOP','RIGHT_TOP','LEFT_CENTER',
										 'RIGHT_CENTER','LEFT_BOTTOM','RIGHT_BOTTOM','BOTTOM_LEFT','BOTTOM_CENTER','BOTTOM_RIGHT'];
									
		// Update oudere versies naar deze versie
		$.fn.VersionFix();
		$.gmap = this;
		
		// Checken of er een formulier aanwezig is vanaf waar routes kunnen worden berekend
		$.fn.MapMe.CheckRouteForm();
		$.fn.MapMe.LoadGoogleScript();
	};
	
	// Google Script inladen
	$.fn.MapMe.LoadGoogleScript = function(){
		$.isLoaded = false;
		$.getScript("http://maps.google.com/maps/api/js?libraries=geometry&libraries=panoramio&sensor=true&language=nl&callback=$.fn.MapMe.Ready");
	}
	
	// Klaar met inladen van extern bestand
	$.fn.MapMe.Ready = function(){
	
		// Variabele die aangeeft dat het externe script van Google klaar is met laden
		$.isLoaded = true;
		
		// Variabelen aanmaken voor gebruik binnen de google maps class
		$.geocoder = new google.maps.Geocoder();
		$.infoWindow = new google.maps.InfoWindow();
		$.bounds = new google.maps.LatLngBounds();
		
		// Variabelen voor directions op de kaart
		$.directionsService = new google.maps.DirectionsService();
		$.directionsDisplay = new google.maps.DirectionsRenderer({draggable:$.options.markersAreDraggable});
		$.panoramioLayer	= new google.maps.panoramio.PanoramioLayer();
		$.elevationService 	= new google.maps.ElevationService();
		$.streetViewService;
		//$.trafficLayer 		= new google.maps.TrafficLayer(); // Wordt (denk ik) alleen ondersteund in VS $.trafficLayer.setMap($.gmap);
		
		$.fn.MapMe.SetMap();

		// Directions mode
		if($.options.travelMode && $.options.travelOnLoad){
			$.fn.MapMe.SetDirections();
			return;
		}
		
		// Markers als Array meegegeven in de options
		if($.isArray($.options.markers) && $.options.markers.length > 0){
			$.fn.MapMe.CheckForCenter();
			// Loop door alle markers en plaats ze op de kaart
			$.each($.options.markers,function(){
				var marker = $(this).get(0);
				$.fn.MapMe.AddMarker(marker);
			});
		}
		
		// Markers via XML bestand
		if(typeof($.options.markers) == 'string')
			$.fn.MapMe.LoadMarkersFromXML();
		
	}
	
	$.fn.MapMe.SetMap = function(){
		if($.gmap && !$.gmap.attr('id')) return;
		
		$.gmap = new google.maps.Map(document.getElementById($.gmap.attr('id')));
		
		$.customLatLngs = new Array();
		$.customMarkers = new Array();
		
		// Event uitvoeren als kaart geklikt wordt
		google.maps.event.addListener($.gmap, 'click', function(event) {
			var t;
			if($.options.addWaypointsOnClick){
				var m = $.fn.MapMe.GetMarkerIcon({latLng:event.latLng})
				$.customMarkers.push(m);
				$.customLatLngs.push(event.latLng);
						
				if(t) clearTimeout(t);
				t = setTimeout($.fn.MapMe.OnClickSearch,$.options.waypointSearchTimeout); 
			} else if($.options.clickForElevation){
				$.fn.MapMe.GetElevation([event.latLng]);
			}
		});
		
		$.fn.MapMe.SetZoom();
		$.fn.MapMe.SetCenter();		
		$.fn.MapMe.SetMapType();
		$.fn.MapMe.SetMapControls();
		$.fn.MapMe.TogglePanoramio();
	
	}
	
	/*******************************************
	* Formulier voor zoeken en route berekenen *
	********************************************/
	
	$.fn.MapMe.CheckRouteForm = function(){
		if(!$.options.routeForm)
		return;
		
		$.searchBtn = $($.options.routeForm).find('input[type="button"]');		
		if(!$.searchBtn){
			alert('voeg een zoekbutton toe: "<input type="button" id="search" value="zoeken"/>"');
			return;
		}
	
		// Maak dropdowns
		$.fromAddress = $.fn.Create('select',{id:'from_address'},$.options.markers,{text:'address',value:'address'});
		$.toAddress = $.fn.Create('select',{id:'to_address'},$.options.markers,{text:'address',value:'address'});
		$.travelModes = $.fn.Create('select',{id:'travelModes',change:$.fn.MapMe.SetTravelMode},$.availableTravelModes);
		
		$($.options.routeForm.selector + '> *').each(function(){
			if($.options.fromAddress && $.options.toAddress){
				// Element verwijderen uit het formulier die vervangen worden door anderen.
				// Uitzonderingen : 
				//		elementen met className 'ignore'
				//		selectboxen met id 'travelModes', 'to_address' en 'from_address'	
				if((this.tagName == 'SELECT' && (this.id == 'travelModes' || this.id == 'from_address' || this.id == 'to_address')) ||
				   this.id == $.searchBtn.attr('id') || $(this).hasClass('ignore')){
				} else {
					$(this).remove();
				}
			}
			
			if($.options.toAddress == 'markers' && this.id && this.tagName != 'SELECT')
				this.id = this.id.replace("to_","from_");
		});
		
		// Dropdown(s) aan formulier toevoegen
		if($.options.fromAddress == 'markers'){			
			$.options.routeForm.find('select#from_address').remove();
			$.fromAddress.insertBefore($.options.routeForm.find(':first'));
		}
		
		// Andere dropdown toevoegen als deze er ook is
		if($.options.toAddress == 'markers'){
			$.options.routeForm.find('select#to_address').remove();
			$.toAddress.insertBefore($.searchBtn);
		}
		
		if($.options.travelModeSelector){
			if(!$.options.routeForm.find('select#travelModes').length)
			$.travelModes.insertBefore($.searchBtn);
			else
			$.options.routeForm.find('#travelModes').bind('change',$.fn.MapMe.SetTravelMode);
		}
		
		// Als er een select box aanwezig is voor maptypes deze op de huidige waarde zetten
		if($.options.routeForm.find('select#maptypes'))
		$.options.routeForm.find('select#maptypes').val($.options.mapType);
		
		// Als er een select box is voor reis manieren deze op de huidige waarde zetten
		if($.options.routeForm.find('select#travelModes'))
		$.options.routeForm.find('select#travelModes').val($.options.travelMode);
		
		// Enter key toevoegen aan form
		$.options.routeForm.bind('keydown',function(event){ 
			if(event.keyCode == 13)
				$.fn.MapMe.GetRouteFrom(); 
		});
		
		// Klikfunctie toevoegen aan button			
		$.searchBtn.bind('click',$.fn.MapMe.GetRouteFrom);
	}
	
	// Bereken route
	$.fn.MapMe.GetRouteFrom = function(){
		var start_address, end_address;
	
		$.each(['from','to'],function(index,prefix){
			var address = false;
			if($.options.routeForm.find('select#'+prefix+'_address').length){
				if($.options.routeForm.find('#'+prefix+'_address').val()){
					address = $.options.routeForm.find('#' + prefix + '_address').val();				
				}
			// Of vanuit invulvelden
			} else {
				var postalcode = $.options.routeForm.find('#' + prefix + '_postalcode').val() + ' ';
				var place = $.options.routeForm.find('#' + prefix + '_place').val();
				var country = $.options.routeForm.find('#' + prefix + '_country').val();
				// Route in elkaar zetten
				if(place && country)
					address = $.options.routeForm.find('#' + prefix + '_address').val() +' ,' + postalcode + place + ',' + country;
			}
			
			if(prefix == 'from' && address)
			start_address = address;
			
			if(prefix == 'to' && address)
			end_address = address;
		});
		
		// Adres doorgeven aan de SetDirections functie
		$.fn.MapMe.SetDirections([start_address, end_address]);
		return false;
	}
	
	// Draai de route om
	$.fn.MapMe.TurnRoute = function(){
		if(!$.fromAddress || !$.toAddress)
		return;
	
		var temp = $.fromAddress.val();
		$.fromAddress.val($.toAddress.val());
		$.toAddress.val(temp);
		
		$.fn.MapMe.GetRouteFrom();
	}
	
	// Checken of er een center is meegegeven
	$.fn.MapMe.CheckForCenter = function(){
		// Loop door de markers heen en check of er een bij is waarop de kaart gecentreerd moet worden
		var markerIsCenter = false;
		$.fn.MapMe.RemoveAllMarkers();
		$.each($.options.markers,function(){ 
			markerIsCenter = $(this).get(0).isCenter;
		});
		
		// Als geen enkele marker het centrale punt is dan centreren op marker 1
		if(!$.options.setCenter && !$.options.fitBounds && !markerIsCenter)
		$.options.markers[0].isCenter = true;
	}
	
	/***********************************************************************
	* Markers op de kaart zetten, infowindowpopup maken, marker icon maken,*
	* functie om markers via xml in te laden en optionele animatie         *
	************************************************************************/
	
	// Geocoder uitvoeren
	$.fn.MapMe.AddMarker = function(marker){
		if(!marker.address && !marker.latLng)
		return;
		
		(function(_marker){
			// Address in Marker
			var lookup = {'address':_marker.address};
			// Als LatLng aanwezig is deze opzoeken
			if(_marker.latLng)
			lookup = {'latLng': new google.maps.LatLng(_marker.latLng.lat, _marker.latLng.lng)};

			// Request sturen naar Google voor het address
			$.geocoder.geocode( lookup , function(results, status){
				if (status == google.maps.GeocoderStatus.OK) {
					// Lat en Lng opslaan in marker
					_marker.latLng = results[0].geometry.location;
					_marker.myLatLng = new google.maps.LatLng(_marker.latLng.lat(),_marker.latLng.lng());
					
					// Lat en Lng ook toevoegen aan bounds 
					// (hiermee worden via de functie fitBounds alle markers in beeld gebracht)
					$.bounds.extend(_marker.myLatLng);
					
					if($.options.fitBounds)
					$.fn.MapMe.FitBounds();
					
					// Marker maken en op de kaart zetten
					_marker.icon = $.fn.MapMe.GetMarkerIcon(_marker);
					_marker.content = marker.content || results[0].formatted_address;
					
					$.fn.MapMe.SetAnimation();
					
					// Als marker het centrale punt is hierop centreren en het infowindow hiervan openen
					if(_marker.isCenter && !$.options.fitBounds){
						$.fn.MapMe.SetCenter({lat:_marker.latLng.lat(),lng:_marker.latLng.lng()});		
						$.fn.MapMe.InfoWindowContent(_marker);
					}
					
					// Als de optie setcenter aanwezig is in de options de kaart op dit punt centreren
					if($.options.setCenter)
						$.fn.MapMe.SetCenter({lat:$.options.setCenter.lat, lng:$.options.setCenter.lng});

					google.maps.event.addListener(_marker.icon, 'click', function() {
						$.fn.MapMe.InfoWindowContent(marker,event);
					});
					
				} else {
					$.fn.MapMe.Error("Geocode was not successful for the following reason: " + status);
				}
			});
		})(marker);
	}
		
	// Infopopup window
	// Content komt uit de marker waarvan die weer gezet wordt in de opties.
	$.fn.MapMe.InfoWindowContent = function(marker, event){
		var type = marker.contenttype || false
		
		if(type && (type.toLowerCase() == 'url' || type.toLowerCase() == 'function')){
			var dothis = marker.content;
			
			// Voer deze functie, url alleen uit als er op de marker is geklikt
			if(!event)
			return;
			
			// Als content een functie is de functie controleren en uitvoeren
			if(typeof(dothis)=='function'){
				dothis();
				return;
			}
			
			// Als Content een URL is en deze mist de http, deze ervoor plakken.
			dothis = dothis.indexOf('http://') == -1 ? "http://" + dothis : dothis;

			// Check of window type is meegegeven
			if(marker.window == '_blank')
				window.open(dothis);
			else 
				// Ga naar de meegegeven URL
				document.location.href = dothis;
			return;
		}
	
		var content = marker.content ? marker.content.replace(/,/g,"<br/>") : '';
		$.infoWindow.setContent("<div><strong>"+marker.title+"</strong><br/>"+content+"</div>");
		
		if(event || marker.popup)
		$.infoWindow.open($.gmap, marker.icon);
	}
	
	// Zet MarkerIcon in elkaar 
	// Eventueel met custom image, shadow en positie (op te geven via options);
	$.fn.MapMe.GetMarkerIcon = function(marker){
		if($.options.icons){
			// Checken of de meegegeven marker id voor komt in de custom markers array
			if(marker.icon > 0 &&  marker.icon <= $.options.icons.length){
				var opts = $.options.icons[marker.icon-1];
				if(!opts.anchor)
				opts.anchor = {x:0,y:32};
				
				var icon = new google.maps.MarkerImage(opts.file, null, null,
					// Ancher (x,y)
					new google.maps.Point(opts.anchor.x, opts.anchor.y)
				)
				
				// Optioneel een schaduw toevoegen
				if(opts.shadow)
					var shadow = new google.maps.MarkerImage(opts.shadow, null, null,
						// Ancher (x,y)
						new google.maps.Point(0, opts.anchor.y)
					)
				
			}
		}

		return new google.maps.Marker({		
			draggable: 		$.options.markersAreDraggable,
			icon: 			icon,
			map: 			$.gmap, 
			position: 		marker.latLng,
			shadow: 		shadow
		});
	}
	
	// Laad Markers uit XML bestand 
	// Relatief pad 
	$.fn.MapMe.LoadMarkersFromXML = function(file){
		var file = file || $.options.markers;
		if(!$.options.markers.indexOf('.xml'))
		return;
		
		$.ajax({
			url: file, type:'GET', dataType:'xml',
			success:function(xml){ 
				$.options.markers = new Array();
				// Loop door bestand en haal alle markers op
				$(xml).find('marker').each(function(){
					// Alleen markers toevoegen als deze een address of latLng paramater hebben die niet leeg zijn
					if($(this).find('address').text() || $(this).find('latLng').text())
					$.options.markers.push({
						address:		$(this).find('address').text(),
						content:		$(this).find('content').text(),
						contenttype:	$(this).find('contentype').text(),
						icon:			$(this).find('icon').text(),
						isCenter: 		$(this).find('isCenter').text(),
						latLng:			$(this).find('latLng').text(),
						point: 			$(this).find('point').text(),
						title:			$(this).find('title').text(),
						window: 		$(this).find('window').text()
					});
				});
			}
		});
	}
	
	$.fn.MapMe.SetAnimation = function(){
		$.each($.options.markers,function(){
			try{
				$(this).get(0).icon.setAnimation(google.maps.Animation[$.options.animation]);
			} catch(e){}
		});
	}
	
	/*************************************************************
	* Directions opvragen bij Google en deze op de kaart tekenen *
	**************************************************************/
	
	$.fn.MapMe.SetDirections = function(waypoints){
		if(!$.isLoaded){
			setTimeout(function(){$.fn.MapMe.SetDirections(waypoints)},100);
			return;
		}
		
		// Markers van de kaart halen
		$.fn.MapMe.RemoveAllMarkers();
		
		var start_address, end_address;
		// Start en eind punt
		if($.isArray(waypoints)){
			for(i=0;i<waypoints.length;i++){
				waypoints[i] = {location:waypoints[i]};
			}
			
			start_address = waypoints.shift();
			end_address = waypoints.pop();
		}
		
		if(!start_address && !end_address && !waypoints){
			// Waypoints instellen
			var waypoints = new Array();
			// Sorteren op point
			$.options.markers.sort(function(a, b){
				return a.point-b.point
			});
							
			// Toevoegen aan waypoints
			$.each($.options.markers,function(){
				var loc = $(this).get(0).address || $(this).get(0).latlng;
				
				if(loc && $(this).get(0).point)
				waypoints.push({location: loc});
			});
			
			start_address = waypoints.shift();
			end_address = waypoints.pop();
		}
		
		if(!start_address.location || !end_address.location){
			alert('geen start en/of eind punt');
			return;
		}
		
		if($.availableTravelModes.indexOf($.options.travelMode)==-1 || $.options.travelMode == false)
			$.options.travelMode = $.availableTravelModes[0];
		
		// Request in elkaar zetten
		$.request = {
			origin: start_address.location, 
			destination: end_address.location,
			waypoints : waypoints,
			optimizeWaypoints : true,
			travelMode: google.maps.DirectionsTravelMode[$.options.travelMode],
			provideRouteAlternatives : true
		};
	
		// Directionsdisplay toevoegen aan kaart
		$.directionsDisplay.setMap($.gmap);
		$.directionsDisplay.setPanel(document.getElementById($($.options.directionsPanel).attr('id')));
		
		// Als de route verlegd wordt actie ondernemen
		google.maps.event.addListener($.directionsDisplay, 'directions_changed', function() {
			var distance = $.fn.MapMe.CalculateRouteDistance($.directionsDisplay.directions);
			
			if($.options.distancePanel)
			$.options.distancePanel.html(distance + ' km');
			
		});

		$.fn.MapMe.RequestRoute();
	}
	
	// Als er op de kaart geklikt wordt wordt via deze functie de route bepaald
	// Werkt met een timeout (gedefinieerd in de options) en $.options.addWaypointsOnClick moet op 'true' staan
	$.fn.MapMe.OnClickSearch = function(){
		if($.customLatLngs.length < 2)
		return;
	
		$.each($.customMarkers,function(index,value){
			this.setMap(null);
		});
		$.fn.MapMe.SetDirections($.customLatLngs);
		// Arrays legen voor nieuwe zoekopdracht
		$.customLatLngs = new Array();
		$.customMarkers = new Array();
	}
	
	// Route opvragen
	$.fn.MapMe.RequestRoute = function(){
		$.directionsService.route($.request, function(result, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				//console.log(result.routes[0].warnings);
				$.directionsDisplay.setDirections(result);
				//$.fn.MapMe.GetElevation(result.routes[0].overview_path);
				$.fn.MapMe.ShowSteps(result);
			} else { $.fn.MapMe.Error("Geocode was not successful for the following reason: " + status); }
		});
	}
	
	$.fn.MapMe.ShowSteps = function(result) {
		if(!result || !$.options.showRouteSteps) return;
		
		var route = result.routes[0].legs[0];
		for (var i = 0; i < route.steps.length; i++) {
			var marker = new google.maps.Marker({
				position: route.steps[i].start_point, 
				map: $.gmap,
				instructions: route.steps[i].instructions
			});
			$.customMarkers.push(marker);
			
			(function(_marker){
				google.maps.event.addListener(_marker, 'click', function() {	
					$.infoWindow.setContent(_marker.instructions);
					$.infoWindow.open($.gmap, _marker);
				})
			})(marker);
		}
	}
	
	// Vraag hoogte op van punten
	$.fn.MapMe.GetElevation = function(points){
		if(!points.length)
		return;
		
		$.elevationService.getElevationForLocations({locations:points}, function(results, status) {
			if (status == google.maps.ElevationStatus.OK) {
				// Retrieve the first result
				if (results[0]) {
					$.log("Hoogte is hier " + results[0].elevation.toFixed(2) + " meter")
				} else {
					$.fn.MapMe.Error("No results found");
				}
			} else {
				$.fn.MapMe.Error("Elevation service failed due to: " + status);
			}
		});
	};
	
	$.fn.MapMe.RemoveAllMarkers = function(){
		$.each($.options.markers, function(){
			if(typeof(this.icon) == 'object')
			this.icon.setMap(null);
		});
		
		$.each($.customMarkers, function(){
			this.setMap(null);
		});
	}
	
	/*********************************************
	* Zoom, MapType, Center en streetview zetten *
	**********************************************/
	
	// Zet zoom level van de map
	$.fn.MapMe.SetZoom = function(zoom){
		var zoom = zoom || $.options.zoom;
		$.gmap.setZoom(zoom);
	}
	
	// Zet travelmode naar andere waarde
	$.fn.MapMe.SetTravelMode = function(travelMode){
		var travelMode = travelMode || $.options.travelMode;
		
		// Als deze functie aangeroepen wordt vanuit een selectbox
		if(event.type == 'change')
		travelMode = event.target.value;

		// Als travelmode niet bestaat de default kiezen
		if($.availableTravelModes.indexOf(travelMode)==-1)
		travelMode = 'DEFAULT';
		
		$.options.travelMode = travelMode;
		$.request.travelMode = google.maps.DirectionsTravelMode[$.options.travelMode];
		
		$.fn.MapMe.RequestRoute();		
		
	}
	
	// Zet Maptype 
	// Mogelijke types ('SATELLITE','TERRAIN','HYBRID','ROADMAP')
	$.fn.MapMe.SetMapType = function(mapTypeId){
		var mapTypeId = (mapTypeId || $.options.mapType).toUpperCase();
		
		//if($.isArray($.availableMapTypes) && $.availableMapTypes.indexOf(mapTypeId)==-1)
		//	mapTypeId = $.availableMapTypes[3];			
		
		
		$.streetViewService = $.gmap.getStreetView();
		$.streetViewService.setPosition($.gmap.getCenter());
		// Streetview aan of uit zetten
		$.streetViewService.setVisible(mapTypeId=='STREETVIEW');
		
		mapTypeId = mapTypeId == 'STREETVIEW' ? 'ROADMAP' : mapTypeId;
		$.gmap.setMapTypeId(mapTypeId.toLowerCase());
	}
	
	$.fn.MapMe.GetMapType = function(){
		if($.gmap)
		return $.gmap.getMapTypeId();
	}
	$.fn.MapMe.GetAvailableMapTypes = function(){
		return $.availableMapTypes;
	}
	$.fn.MapMe.GetAvailableControlPositions = function(){
		return $.availableControlPositions;
	}
	
	// Zet Controlbuttons + options en locatie hiervoor
	// Kan na initialiseren worden aangepast
	// Aan deze functie kan een object met opties meegegeven worden
	// om een control aan of uit te zetten, de locatie te wijzigen of de weergave hiervan
	$.fn.MapMe.SetMapControls = function(controls){
		if(controls){
			$.each(controls,function(index,value){
				$.options.controls[index] = value;
			});
		}
		
		if($.gmap){
			// Zoomen bij dubbelklik op de kaart
			$.gmap.disableDoubleClickZoom = $.options.controls.disableDoubleClickZoom;
			
			// Map type control
			$.gmap.mapTypeControl = $.options.controls.mapTypeControl;
			$.gmap.mapTypeControlOptions = { 
				position: google.maps.ControlPosition[$.options.controls.mapTypeControlPosition],
				style: google.maps.MapTypeControlStyle[$.options.controls.mapTypeControlStyle] 
			}
			
			// Overviewmap (kleine kaartje rechts onder in beeld)
			$.gmap.overviewMapControl = $.options.controls.overviewMapControl;
			$.gmap.overviewMapControlOptions = { 
				opened: $.options.controls.mapTypeControlOpened
			};
			
			// Map pan control
			$.gmap.panControl = $.options.controls.panControl;
			$.gmap.panControlOptions = { 
				position: google.maps.ControlPosition[$.options.controls.panControlPosition] 
			}
			
			// Map scale control
			$.gmap.scaleControl = $.options.controls.scaleControl;
			$.gmap.scaleControlOptions = { 
				position: google.maps.ControlPosition[$.options.controls.scaleControlPosition] 
			}
			
			// Scrolwheel enabled of niet
			$.gmap.scrollwheel = $.options.controls.scrollwheel;
			
			// Map streetview control
			$.gmap.streetViewControl = $.options.controls.streetViewControl;
			$.gmap.streetViewControlOptions = { 
				position: google.maps.ControlPosition[$.options.controls.streetViewControlPosition] 
			}	
			
			// Map zoom control
			$.gmap.zoomControl = $.options.controls.zoomControl;
			$.gmap.zoomControlOptions = { 
				position: google.maps.ControlPosition[$.options.controls.zoomControlPosition],
				style : google.maps.ZoomControlStyle[$.options.controls.zoomControlStyle] 
			}
		}
	}
	
	// Laat de fotos wel of niet zien
	// Standaard staat het op de waarde die in de options wordt meegegeven (true of false)
	$.fn.MapMe.TogglePanoramio = function(event){
		if(event)
		$.options.showPanoramio = !$.options.showPanoramio;
		
		var setMap = $.options.showPanoramio ? $.gmap : null;
		$.panoramioLayer.setMap(setMap);
	}
	
	// Filter de foto's die getoond worden in de panoramio layer
	$.fn.MapMe.FilterPanoramio = function(tag){
		$.options.showPanoramio = true;
		$.panoramioLayer.setMap($.gmap);
		$.panoramioLayer.setTag(tag);
	}
	
	// Zet het centrale punt van de map 
	$.fn.MapMe.SetCenter = function(latLng){
		var latLng = latLng || $.options.defaultCenter;
		$.gmap.setCenter(new google.maps.LatLng(latLng.lat, latLng.lng));
		
		if($.streetViewService)
		// Streetview meenemen in het center
		$.streetViewService.setPosition($.gmap.getCenter());
	}
	
	// Als deze functie wordt aangeroepen wordt de kaart 
	// zo gecentreerd en gezoomed dat alle markers in beeld zijn
	$.fn.MapMe.FitBounds = function(){
		$.gmap.fitBounds($.bounds);
	}
	
	// Afstand berekenen tussen 2 punten
	$.fn.MapMe.CalculateDistance = function(from_address,to_address){	
		// Deze functie kan worden aangeroepen zonder eerste MapMe aan te roepen
		// Daarvoor moet wel eerst het script van google worden ingeladen
		if(typeof($.isLoaded) == 'undefined')
		$.fn.MapMe();
		
		// Wachten totdat het script geladen is en ga dan pas verder
		if(!$.isLoaded){
			setTimeout(function(){$.fn.MapMe.CalculateDistance(from_address,to_address)},100);
			return;
		}
		
		$.Distances = [from_address, to_address];
		$.Points = new Array();
		$.afstand = 0;
		
		for(i=0;i<$.Distances.length;i++){
		
			$.geocoder.geocode({'address':$.Distances[i]} , function(results, status){
				if (status == google.maps.GeocoderStatus.OK) {
					// Lat en Lng opslaan in marker
					$.Points.push(results[0]);
									
					if($.Points.length == 2)
					$.afstand = google.maps.geometry.spherical.computeDistanceBetween(
									new google.maps.LatLng($.Points[0].geometry.location.lat(),$.Points[0].geometry.location.lng()),
									new google.maps.LatLng($.Points[1].geometry.location.lat(),$.Points[1].geometry.location.lng()));
					
					// Hoe krijg ik dit als return van $.fn.MapMe.CalculateDistance?
					if($.afstand){
						$.returnMsg = 'De afstand tussen "';
						$.returnMsg += $.Points[0].formatted_address;
						$.returnMsg += '" en "';
						$.returnMsg += $.Points[1].formatted_address;
						$.returnMsg += '" is ' +($.afstand/1000).toFixed(2) + ' km';
						$.log($.returnMsg);
					}
				} else {
					$.fn.MapMe.Error("Geocode was not successful for the following reason: " + status);
				}
			});
		};
		
		return false;
		//return ($.afstand/1000).toFixed(2);
		
	}
	
	// Afstand bereken van een route
	$.fn.MapMe.CalculateRouteDistance = function(result){
		// Bereken totale afstand
		var totaal = 0;
		for (i = 0; i < result.routes[0].legs.length; i++) {
			totaal += result.routes[0].legs[i].distance.value;
		}
		// resultaat terug geven in km.
		return (totaal/1000).toFixed(2);
	}
	
	/*****************************************
	* Creeer HTML element (alleen nog select)*
	******************************************/
	
	$.fn.Create = function(htmlElementName, parameters, children, childrenParameters){
		var html = $('<' + htmlElementName + '></' + htmlElementName + '>');
		var children = children.sort() || false;
		
		// Parameters aan htmlElement geven
		$.each(parameters, function(index,value){
			if(index == 'change' || index == 'click'){
				$(html).bind(index,value);
			} else {
				$(html).attr(index,value);
			}
		});
		
		// Children toevoegen aan htmlElement
		// Eerst uitzoeken welke kinderen het heeft
		var childNodeName;
		switch($(html).get(0).nodeName.toLowerCase()){
			case 'select' : 
			default : childNodeName = 'option'; break;
		}
		
		if(childNodeName!='option'){
			alert(childNodeName + ' wordt nog niet ondersteund');
			return;
		}
		
		$.each(children, function(index,values){
			var value = values;
			var text  = values;
			if(typeof(values) == 'object'){
				var value = childrenParameters.value == 'id' ? index : values[childrenParameters.value];
				var text  = values[childrenParameters.text];
			}
			
			var childNode = $('<'+ childNodeName + '></' + childNodeName + '>');
			childNode.val(value);
			childNode.text(text);
			
			$(html).append(childNode);
		})
		
		return html;
	}
	
	/**********************************************************
	* Versie, VersieFix, Pausefunctie, errors en log functies *
	***********************************************************/
	
	// Pauze functie
	$.fn.pause = function( iMilliseconds )
	{
	  var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');';
	  window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")');
	}
	
	// Versie fix (oude variabele omzetten naar nieuwe
	$.fn.VersionFix = function(){
		if($.options.hasTravelMode && !$.options.travelMode)
		$.options.travelMode = true;
		
		if($.options.hasStreetview)
		$.options.controls.streetViewControl = $.options.hasStreetview;
		
		if($.options.markerIsDraggable)
		$.options.markersAreDraggable = $.options.markerIsDraggable
	}
	
	// Output error naar browser
	$.fn.MapMe.Error = function(msg){
		$.log(msg);
	}
	
	// Log functie (check of dit ondersteund wordt in browser)
	$.log = function(){
		var debug = $.options && $.options.debug || true;
		if (window.console && window.console.log && debug)
		console.log(Array.prototype.join.call(arguments,' '));
	}
	
	$.fn.MapMe.ver = function() { return ver; };
	
	//$(document).ready(function(){ $.log('[MapMe version: ' + $.fn.MapMe.ver() + ']')})
})(jQuery);
