$(document).ready(function() {
	var denmark;
	var map;
	var geocoder;

	var routePoints = new Array();
	var routeMarkers = new Array();
	var routeOverlays = new Array();
	var totalDistance = 0.0;
	var lineIx = 0;	
	
	var start = new google.maps.MarkerImage('/images/122/greenpointer.png');
	var end = new google.maps.MarkerImage('/images/122/redcircle.png');
	
	initialize();
	
	
	$('#searchAddress').keypress(function(e) {
		if(!e) e = window.event;
		if(e.which == 13) {
			// $(this).blur();
			// $('#submit').focus().click();
			var searchAddress = $('#searchAddress').val();
			getCodeAddress(searchAddress);
		}
	});
	$('#searchForm a').hover(function() {
		$(this).css('cursor', 'pointer');
	});
	$('#searchForm a').click(function() {
		var searchAddress = $('#searchAddress').val();
		getCodeAddress(searchAddress);
	});
	
	$('#btnUndo').click(function() {
		if(typeof(routePoints[lineIx]) === 'undefined')
		{
			alert('Optegn venligst en rute.');
		}	
		else
		{
			undoPoint();
		}
	});
	
	$('#btnSave').click(function() {
		if(addClosing())
		{
			$('#form1').submit();
		}
	
	});
	
	// finds the coordinates for the two locations and calls the showMap() function
	function initialize()
	{
		// creating a new geocode object
		geocoder = new google.maps.Geocoder();

		// for distanceFrom function
		google.maps.LatLng.prototype.distanceFrom = function(latlng) {
		  var lat = [this.lat(), latlng.lat()]
		  var lng = [this.lng(), latlng.lng()]
		  var R = 6378137;
		  var dLat = (lat[1]-lat[0]) * Math.PI / 180;
		  var dLng = (lng[1]-lng[0]) * Math.PI / 180;
		  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		  Math.cos(lat[0] * Math.PI / 180 ) * Math.cos(lat[1] * Math.PI / 180 ) *
		  Math.sin(dLng/2) * Math.sin(dLng/2);
		  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		  var d = R * c;
		  return Math.round(d);
		}

		//display the map
		showMap();
		
		//add events
		google.maps.event.addListener( map, 'click', function(event) { 
			var location = event.latLng;
			mapClick(location);
		});
	}
	// handle map click
	function mapClick(location) {
		addRoutePoint(location);
	}
	// creates and shows the map
	function showMap() 
	{
		// center of the map (compute the mean value between the two locations)
		denmark = new google.maps.LatLng(57.21999128448 ,9.60064963658);
		
		// get the map type value from the hidden field
		var maptype = 'roadmap';

		var typeId;
	
		if (maptype == 'roadmap')
			typeId = google.maps.MapTypeId.ROADMAP;
		else if (maptype == 'hybrid')
			typeId = google.maps.MapTypeId.HYBRID;
		else if (maptype == 'satellite')
			typeId = google.maps.MapTypeId.SATELLITE;
		else if (maptype == 'terrain')
			typeId = google.maps.MapTypeId.TERRAIN;
		
		// set map options
		// set zoom level
		// set center
		// map type
		var mapOptions = 
		{
			draggableCursor: 'crosshair',
			scrollwheel: false
		};
		
		// create a new map object
		// set the div id where it will be shown
		// set the map options
		map = new google.maps.Map(document.getElementById('map_canvas2'), mapOptions);
		var overlayMap = new google.maps.Map(
		  document.getElementById('overlay_map'), {
		  mapTypeId: google.maps.MapTypeId.ROADMAP, 
		  disableDefaultUI: true
		});
		
		// Set up zoom_changed listeners so that overlayMap's zoom changes to be 4
		// less than map's and map's 4 greater than overlayMap's.
		google.maps.event.addListener(map, 'zoom_changed', function() {
		  var newZoom = Math.max(map.getZoom() - 4, 0);
		  if (overlayMap.getZoom() != newZoom) overlayMap.setZoom(newZoom);
		});
		google.maps.event.addListener(overlayMap, 'zoom_changed', function() {
		  var newZoom = overlayMap.getZoom() + 4;
		  if (map.getZoom() != newZoom) map.setZoom(newZoom);
		});
		
		// overlayMap's center stays in sync with map's center 
		overlayMap.bindTo('center', map, 'center');
		
		// Set map's properties now that all bindings and listeners are set up.
		map.setZoom(8); // This will trigger a zoom_changed on the map
		map.setCenter(denmark);
		map.setMapTypeId(maptype);
		
		/**
		 * attach the overview map to the main map and set positioning
		 */
		var overDiv = overlayMap.getDiv();
		map.getDiv().appendChild(overDiv);
		overDiv.style.position = 'absolute';
		overDiv.style.right = '0px';
		overDiv.style.bottom = '0px';
		overDiv.style.zIndex = 10;
		
		google.maps.event.addListener(overlayMap, 'idle', function() {
		  overlayMap.getDiv().style.zIndex = 10;
		});
		
	}
	// add marker arrays 
	function addRoutePoint(location) {
		var dist = 0;	

		if (!routePoints[lineIx])
		{
			routePoints[lineIx] = Array();
			routeMarkers[lineIx] = Array();
		}
		routePoints[lineIx].push(location);	
		if (routePoints[lineIx].length > 1)
		{	
			plotRoute();
			dist = routePoints[lineIx][routePoints[lineIx].length-2].distanceFrom(location) / 1000;
			totalDistance += dist;

			$('#dist').html(function(){
				var content = "Længde: <span style='color:red; font-size: 22px;'>" +
				totalDistance.toFixed(3) + 
				"</span> km";
				return content;
			});
			document.getElementById('km').value = totalDistance.toFixed(3);
		}
		else {
			var markerOptions = {
				position: location, 
				icon: start,
				map: map,
				//draggable: true,
				title: 'Start',
				animation: google.maps.Animation.DROP
			}
			routeMarkers[lineIx][routePoints[lineIx].length-1] = new google.maps.Marker(markerOptions);
			saveAddress(location);		
		}
	}

	function plotRoute()
	{
		if (routeOverlays[lineIx]) {
			routeOverlays[lineIx].setMap(null);
		}
		var polyOptions = new google.maps.Polyline({
			path: routePoints[lineIx],
			strokeColor: '#C602C8',
			strokeOpacity: 1.0,
			strokeWeight: 3
			});

		routeOverlays[lineIx] = new google.maps.Polyline(polyOptions);
		routeOverlays[lineIx].setMap(map);
	}	
	
	// perform the search
	function getCodeAddress(searchAddress) { 
		geocoder.geocode( { 'address': searchAddress}, function(results, status) {
		  if (status == google.maps.GeocoderStatus.OK) {
			map.setCenter(results[0].geometry.location);
			map.setZoom(15);
		  } else {
			alert('Skriv en adresse i søgefeltet. (fx.: Vesterbro 21, aalborg)');
		  }
		});
	}
	
	function saveAddress(x)
		{
			var y = x;

			geocoder.geocode({'latLng': y}, function(results, status) {
			  if (status == google.maps.GeocoderStatus.OK) {
				if (results[1]) {
					var address = results[0].address_components;
					var zipcode = address[address.length - 1].long_name;
					document.getElementById('address').value = results[1].formatted_address;
					document.getElementById('zipcode').value = zipcode;		
				} else { 
				  // alert("No results found");
				}
			  } else {
				// alert("Geocoder failed due to: " + status);
			  }
			});

			
		}
	
	// undo polyline
	function undoPoint() {

		if (!routePoints[lineIx] || routePoints[lineIx].length == 0) {
			lineIx--;
		}
		
		if(typeof(routePoints[lineIx]) === 'undefined')
		{
			alert('Optegn venligst en rute..');
		}	
		
		else if (routePoints[lineIx].length > 1)
		{
			var dist = routePoints[lineIx][routePoints[lineIx].length-2].distanceFrom(routePoints[lineIx][routePoints[lineIx].length-1]) / 1000;
			totalDistance -= dist;

			document.getElementById("dist").innerHTML = 'Længde: '+ totalDistance.toFixed(3) + ' km';
			document.getElementById("km").value = totalDistance.toFixed(3);

						
			if (routeMarkers[lineIx][routePoints[lineIx].length-1]) {
				var marker = routeMarkers[lineIx].pop();
				// similar with map.removeOverlay(marker);
				marker.setMap(null);
			}

			routePoints[lineIx].pop();
			plotRoute();
		}
		else {
			resetRoute();	
		}
	}
	function resetRoute() {
		if (!routePoints[lineIx] || routePoints[lineIx].length == 0) 
		{
			lineIx--;
		}

		routePoints[lineIx] = null;
		// similar with = map.removeOverlay(routeOverlays[lineIx]);
		// routeOverlays[lineIx].setMap(null);

		for (var n = 0 ; n < routeMarkers[lineIx].length ; n++ ) {
			var marker = routeMarkers[lineIx][n];
			// similar with map.removeOverlay(marker);
			marker.setMap(null);
		}
		routeMarkers[lineIx] = null;
		
	}
	
	function addClosing()
	{
		if(document.getElementById('titel').value == '')
		{
			alert('Skriv venligst en beskrivende titel til din rute. fx. "Rundtur langs kysten"');
			document.getElementById('titel').focus();
			return false;
		}
		else
		{		
			if(routePoints[lineIx] && routePoints[lineIx].length > 1)
			{
				if (routeMarkers[lineIx][routePoints[lineIx].length-1])
					// the same as = map.removeOverlay(routeMarkers[lineIx][routePoints[lineIx].length-1]);
					routeMarkers[lineIx][routePoints[lineIx].length-1].setMap(null);
					
				var markerOptions = {
					map: map,
					icon: end,
					title: 'End'
				};
				
				routeMarkers[lineIx][routePoints[lineIx].length-1] = new google.maps.Marker(markerOptions);
				
				for (var n = 0 ; n < routePoints[lineIx].length ; n++ )
				{
					document.getElementById('routePoint').value += routePoints[lineIx][n]+'~';
				}
				return true;
				
			}
			else
			{
				alert('Optegn venligst din rute.');
				return false;
			}
		}
	}
	
});

