/**
 * @author frank
 */
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map= Array(1,2);
//= new google.maps.LatLng(51.4761452, 3.7122267);
//var latlng = new google.maps.LatLng(51.4761452, 3.7122267);
//var latlng = new google.maps.LatLng(51.4761452, 3.7122267);


function createGoogleMaps(waardes){
			
	var rel = 'Uw adres en woonplaats...';

	var MapsID = waardes[2];	


	new Element('div', { 'id': 'canvas_'+MapsID}).inject($('googleMaps_'+MapsID));
	new Element('div', { 'id': 'frmRoute_'+MapsID}).inject($('googleMaps_'+MapsID));
	
	
	new Element('input', { 
		'id': 'van_'+MapsID,
		'value': rel,
		events: {
			'focus': function(){
				if(this.get('value')==rel){
					this.set('value','');
				}
			},
			'blur': function(){
				if(this.get('value')==''){
					this.set('value',rel);
				}
			}
		}
	}).inject($('frmRoute_'+MapsID));

	new Element('input', { 
		'id': 'btnRoute_'+MapsID,
		'type':'button',
		'value':'Route',
		'class':'button',
		events: {
			'click': function(){
				direction($('van_'+MapsID).get('value'), new google.maps.LatLng(waardes[0], waardes[1]),waardes[2]);
			}
		}}).inject($('frmRoute_'+MapsID));
	
	//new Element('div', { 'id': 'directions_'+MapsID}).inject($('googleMaps_'+MapsID));

	initGoogleMaps(waardes);
	
}

var latlng ;
function initGoogleMaps(waardes) {
	//var map;	
	
	var href = '/route.php?begin='+ waardes[0] +'|'+ waardes[1] + '&end=';
	
	var MapsID = waardes[2];	
	
	if($('van_'+MapsID)){
		$('van_'+MapsID).addEvent('keyup', function(){
			$('mb'+ MapsID).set('href', href + $('van_'+MapsID).get('value'));
		});
	}
	
	
	
	latlng = new google.maps.LatLng(waardes[0], waardes[1]);
	
	directionsDisplay = new google.maps.DirectionsRenderer();
	var myOptions = {
		zoom: 13,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		mapTypeControlOptions: {  
			style: google.maps.MapTypeControlStyle.DROPDOWN_MENU  
		}
	};
	map[waardes[2]] = new google.maps.Map($('canvas_'+waardes[2]), myOptions);
	var marker = new google.maps.Marker({
		position: latlng,
		map: map[waardes[2]]
	}); 
	
	
  	
}

function direction(start, end,mapid){
	directionsDisplay.setMap(map[mapid] );
	directionsDisplay.setPanel($('directions'));
	
	var request = {
		origin: start, 
		destination: end,
		travelMode: google.maps.DirectionsTravelMode.DRIVING
	};
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
	  		directionsDisplay.setDirections(response);
		}else{
			alert('No street or city found.\nPlease try again.');
		}
	});
}

window.addEvent('domready', function(){
	//alert('ok');
	var array;
	$$('.maps').each(function(el){
		array = el.get('rel').split('|');
		//createGoogleMaps(array);
		initGoogleMaps(array);
	});
	
	if($('directions')){
		//alert(array[3]);
	   direction(array[3], new google.maps.LatLng(array[0], array[1]), array[2]);
	}
});
