
// Google maps variables
var map;
var markerFromAirport;
var markerToAirport;

var flightPath;
var distanceBetween;
var latLngBounds;

var geocoder;

function init_google_maps() 
{
		
	geocoder = new google.maps.Geocoder();
	
	
	var latlng = new google.maps.LatLng(50, 10);
	
	var myOptions = {
	  zoom: 3,
	  center: latlng,
	  mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var mapContainer = document.getElementById("gMapContainer");
	map = new google.maps.Map(mapContainer , myOptions);
	    
	if (markerFromAirport) {
		addMarker(markerFromAirport.position, "markerFromAirport");
	}
	if (markerToAirport) {
		addMarker(markerToAirport.position, "markerToAirport");
	}
	makeRoute();
}	


function makeRoute() {
	clearRoute();
	if (markerFromAirport && markerToAirport) 
	{
		var routing = [];
		routing.push(markerFromAirport.position);
		routing.push(markerToAirport.position);
		
		// Extend view area
		latLngBounds = new google.maps.LatLngBounds();
		latLngBounds.extend(markerFromAirport.position);
		latLngBounds.extend(markerToAirport.position);
		
		
		flightPath = new google.maps.Polyline({
			path: routing,
			strokeColor: "#FF0000",
			strokeOpacity: 1.0,
			strokeWeight: 2,
			geodesic: true
		});

		
		flightPath.setMap(map);
		
		// Calculate distance between points
		distanceBetween = Math.round(google.maps.geometry.spherical.computeDistanceBetween(markerFromAirport.position, markerToAirport.position)/1000);
		
		
		map.setCenter(latLngBounds.getCenter(), 10);
		map.fitBounds(latLngBounds);
		
	}
	else
	{
		// Set center if only one marker is set
		if (markerFromAirport) {
			
			map.setCenter(markerFromAirport.position);
		}
		resetDistanceText();
	}	
	updateRouteInformationText();
}

function resetDistanceText() {
	distanceBetween = '';
}
function addGoogleDivToLeftArea()
{
	
	var divName = '#leftTextArea';
	var minAirportLengthForLookup = 3;
	$(divName).prepend('<div class="testDiv" id="testDiv"><div id="closeRouteInformation">X</div><p class="paragraphTitle">Trip planner</p><div id="gMapContainer"></div><div id="routeTextContainer">'+getRouteInformationText()+'</div></div>');
	$('#testDiv').append('<div id="routeInformationDisclaimer">For at fuldf&oslash;re Deres foresp&oslash;rgsel, tryk p&aring; Send &gt&gt&gt</div>');
	$('#txtFromAirport').keyup(function() {
		var fromAirport = $('#txtFromAirport').val();
		if ((fromAirport.length) >= minAirportLengthForLookup) {
			getAirportGeoCode(fromAirport, "markerFromAirport");
			
		}
		else
		{
			clearMarkers("markerFromAirport");
			clearRoute();
		}
		updateRouteInformationText();
		
	});
	
	$('#txtToAirport').keyup(function() {
		var toAirport = $('#txtToAirport').val();
		if ((toAirport.length) >= minAirportLengthForLookup) {
			getAirportGeoCode(toAirport, "markerToAirport");
			
		}
		else
		{
			clearMarkers("markerToAirport");
			clearRoute();
		}
		updateRouteInformationText();
		
	});
	$('#DatoUd, #DatoRetur, #txtPAX').keyup( function() {
	
		
		updateRouteInformationText();
		
	});
	$('#Time_departure, #Time_return').change( function() {
		
		updateRouteInformationText();
	});
	
}

function getAirportGeoCode(address, marker) {
	clearRoute();
	// Sleep for OVER_QUERY_LIMIT. 
	setTimeout(function() {
		geocoder.geocode( { 'address': address}, function(results, status) {
			
	        if (status == google.maps.GeocoderStatus.OK) {
	          
	          var foundAirport = false;
	          var placeMarkerLocation;
	          for (i in results) {
	        	  for (t in results[i].types) {
	        		  if (results[i].types[t] == "airport") {
	        			  placeMarkerLocation = results[i].geometry.location;
	        			  foundAirport = true;
	        			  //console.log('Found airport '+placeMarkerLocation);
	        		  }
	        	  }
	          }
	          if (!foundAirport) {
	        	  // No specific airport found. Add first result
	        	  if (results[0]) {
	        		  placeMarkerLocation = results[0].geometry.location;
	        	  }
	        	  //console.log('Found default '+placeMarkerLocation);
	          }
	          
	          if (placeMarkerLocation) {
	        	 //console.log('Return marker : '+placeMarkerLocation);
		         
		         addMarker(placeMarkerLocation, marker);
		 		
	          }
	        } 
	        else 
	        {
	        	//console.log(status);
	        	return status;
	          
	        }
	      });
	
	
	}, 1000);
}

function addMarker(latLng, marker) {
	
	clearMarkers(marker);
	if (latLng) {
	
		map.setCenter(latLng);
	    var setMarker = new google.maps.Marker({
	    	map: map,
	    	position: latLng
	    	
	    });
	    window[marker] = setMarker;
	    /*
	    
	    if (marker == "from") {
	    	
	    	markerFromAirport = setMarker;
	    }
	    if (marker == "to") {
	    	
	    	markerToAirport = setMarker;
	    }*/
	    
	    makeRoute();
	}

}
function clearRoute() {
	
	if (flightPath) {
		resetDistanceText();
		flightPath.setMap(null);
	}
	
}
function clearMarkers(clearMarker) {
	
	if (window[clearMarker]) {
		var m = window[clearMarker];
		m.setMap(null);
		m = null;
		latLngBounds = null;
	}
	/*
	if (clearMarker == "from") {
		if (markerFromAirport) {
			markerFromAirport.setMap(null);
			markerFromAirport = null;
			latLngBounds = null;
		}
	}
	if (clearMarker == "to")
	{
		if (markerToAirport) {
			markerToAirport.setMap(null);
			markerToAirport = null;
			latLngBounds = null;
		}
	}
	*/
}
function updateRouteInformationText() {
	
	$('#routeTextContainer').html(getRouteInformationText());
	
}


function getRouteInformationText() {
	var writableDistance = (distanceBetween) ? distanceBetween+'km' : '';
	fromAirportText = $('#txtFromAirport').val();
	toAirportText = $('#txtToAirport').val();
	
	outBoundDate = $('#DatoUd').val();
	homeBoundDate = $('#DatoRetur').val();
	outBoundTime = $('#Time_departure').val();
	homeBoundTime = $('#Time_return').val();
	
	nrOfPax = $('#txtPAX').val();
	
	outputText = '<table id=\"routeInformationTable\"><tr><td colspan=\"2\">Rute: '+fromAirportText+' - '+toAirportText+'</td></tr>';
	outputText += '<tr><td> Dato ud: '+outBoundDate+' </td><td>Tid: '+outBoundTime+'</td></tr>';
	outputText += '<tr><td> Dato retur: '+homeBoundDate+' </td><td>Tid: '+homeBoundTime+'</td></tr>';
	outputText += '<tr><td> Passagerer: '+nrOfPax+'</td><td>Distance: '+writableDistance+'</td></tr>';
	return outputText;
	
};

