(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(){
				   $.fn.maps.clickAdres($this, $(this));
				})
				$coor 	= $(this).attr('rel').split(',');
				$pos 	= new google.maps.LatLng($coor[0],$coor[1]);
				$boundary.extend($pos);	
				$this.opts.markers[i] = new google.maps.Marker({
					position: $pos, 
					map: $this.opts.map,
					title: $(this).find('strong').html()
				}); 			
			})
			
			
			

			$this.find("input[type=button]").click(function(){
				$.fn.maps.route($this);						 
			});
			
			if($this.find('.adressen li').length == 1){
				 $el = $this.find('.adressen li:eq(0)');
				 $.fn.maps.clickAdres($this, $el);
				 $this.find('select[name=naar]').hide();
				 $this.find('.adressen').hide();
				 $this.opts.map.setCenter($this.opts.markers[$el.index()].getPosition());	
			}else{
				$this.opts.map.fitBounds($boundary);	
			}
		});
	};
	
	$.fn.maps.clickAdres = function($this, $el){
		$this.find('.adressen li.active').removeClass('active');
		$el.addClass('active');
		$this.find('select[name=naar]').val($el.attr('rel'));
		$this.opts.map.setZoom(14);	
		$this.opts.map.panTo($this.opts.markers[$el.index()].getPosition());	
	}
	
	$.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);
