(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.mainposition			= new google.maps.LatLng(51.069924,5.844828);
			$this.opts.centerposition		= new google.maps.LatLng(51.069924,5.844828);
			$this.opts.zoom					= 14;
			$this.opts.map					= null;
			$this.opts.directionsService	= null;
			
			var myOptions = {
			  zoom: $this.opts.zoom,
			  center: $this.opts.centerposition,
			  mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			
			$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));
			  
			var marker = new google.maps.Marker({
				position: $this.opts.mainposition, 
				map: $this.opts.map,
				title: "Limburg Plant"
			}); 
			
			$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();
		var request = {
			origin:start, 
			destination:$this.opts.mainposition,
			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('[type=submit]').attr('class'));
			}
		});
	};
})(jQuery);
