(function($) {
	$.fn.maps = function(options) {
		var opts = $.extend({}, $.fn.maps.defaults, options);
		return this.each(function(i) {
			var $this 						= $(this);
			$this.opts 						= $.extend({}, opts);
			$this.opts.zoom					= 14;
			$this.opts.map					= null;
			$this.opts.directionsService	= null;
			$this.opts.markers				= Array();
			var myOptions = {
			  zoom: $this.opts.zoom,
			  mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			
			$boundary = new google.maps.LatLngBounds();
			$this.opts.map = new google.maps.Map(document.getElementById("routemap"), myOptions);
			$this.opts.directionsService = new google.maps.DirectionsService();
			$this.opts.directionsDisplay = new google.maps.DirectionsRenderer();
			$this.opts.directionsDisplay.setMap($this.opts.map);
			$this.opts.directionsDisplay.setPanel($("#routebeschrijving").get(0));
						
			$this.find('.adressen li').each(function(i){
				$(this).click(function(){
					$this.find('.adressen li.active').removeClass('active');
					$(this).addClass('active');
					$this.find('select[name=naar]').val($(this).attr('rel'));
					$this.opts.map.setZoom(10);	
					$this.opts.map.panTo($this.opts.markers[$(this).index()].getPosition());	
				})
				$coor 	= $(this).attr('rel').split(',');
				$pos 	= new google.maps.LatLng($coor[0],$coor[1]);
				if($this.find('.adressen li').length == 1){
					$this.opts.map.setCenter($pos);
					$this.find('.adressen').hide();
					$this.find('.to').hide();
				}
				$boundary.extend($pos);	
				$this.opts.markers[i] = new google.maps.Marker({
					position: $pos, 
					map: $this.opts.map,
					title: $(this).find('strong').html()
				}); 			
			})
			if($this.find('.adressen li').length > 1){
				$this.opts.map.fitBounds($boundary);
			}

			$this.find("input[type=button]").click(function(){
				$.fn.maps.route($this);						 
			});
		});
	};
	$.fn.maps.route = function($this){
		var start = $this.find("[name=postcode]").val() + ', ' + $this.find("[name=land]").val();
		$coor 		= $this.find('[name=naar]').val().split(',');
		$target 	= new google.maps.LatLng($coor[0],$coor[1]);
		var request = {
			origin:start, 
			destination: $target,
			travelMode: google.maps.DirectionsTravelMode.DRIVING
		};
		
		$this.opts.directionsService.route(request, function(response, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				$("#routebeschrijving > div").html('');
				$("#routebeschrijving").show();
				$('html,body').animate({'scrollTop': $("#routebeschrijving").offset().top + 'px'}, 800);
				$this.opts.directionsDisplay.setDirections(response);
			}else{
				alert($this.find('.submitter').attr('rel'));
			}
		});
	};
})(jQuery);
