//map functions for Google Maps API V3 by Ben Beckford

/*Generate map styles at: http://gmaps-samples-v3.googlecode.com/svn/trunk/styledmaps/wizard/index.html

Example usage:

<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/maps_functions_v3.js"></script>
<script type="text/javascript" src="http://maps.google.co.uk/maps/api/js?sensor=false&amp;key=ABQIAAAAQmgxb2K8HFvl_SKRZsLfwRSJx3J6llU8viU-jAWyZd7L5UlWBhRjtI42uk8PU0rAR9wp-UWRpqQSYQ"></script>

<script type="text/javascript">
$(document).ready(function(){
	createMap({
			  
			  //USE XML
			  xmlPath: "storage/xml/locations.xml",
			  
			  //OR USE SINGLE LAT AND LNG
			  lat: 51.5001973, lng: -0.1262295,
			  
			  containerID: "map",
			  mouseWheel: true,
			  zoom: 12,
			  forceCenterLng: 51.5055,
			  forceCenterLat: -0.0738,
			  allControlsOn: false,
			  navigationControl: true,
			  mapTypeControl: true,
			  scaleControl: true,
			  streetViewControl: true,
			  mapStyle: [ { featureType: "all", elementType: "all", stylers: [ { hue: "#ff0044" } ] } ]
	});
	
});
</script>

<div style="width: 650px; height: 600px" id="map"></div>

*/

var Map, $Container, directionsService, directionsDisplay, geocoder, latlngbounds, markersArray;
var allControlsOn = false;

function locationObject(){
	this.long = 0;
	this.lat = 0;
	this.title = "";
	this.address = "";
	this.link = "";
}

function createMap(params)
{
	var markersArray = new Array();
	var locationArray = new Array();
	var iconArray = new Array();
	
	if(params.xmlPath != null)
	{
		$.ajax({
			type: "GET",
			url: encodeURI(params.xmlPath),
			dataType: "xml",
			success: function(xml) {
				$(xml).find('xml').each(function(){
												 
					var i = 0;
				
					$(this).find('location').each(function(){
						
						var location = new locationObject();
						location.long = $(this).attr("longitude");
						location.lat = $(this).attr("latitude");
						location.title = $(this).attr("title");
						if(location.title == null)
						{
							location.title = "";
						}
						
						location.balloonContent = $(this).attr("balloonContent");
	
						locationArray.push(location);
						
						var markerImage = "";
						
						if($(this).attr("icon") != null || $(this).attr("icon") != "")
						{
							markerImage = $(this).attr("icon");
						}
						
						iconArray.push(markerImage);
						
						//$('#locationLinks').append('<div class="locationBtn" onclick="selectMarker('+i+')">'+ location.title +'</div>');
						
						i++;
					});
					
					initMap(params, markersArray, locationArray, iconArray);
					
				});
			}
	   });
	}
	else
	{
		var location = new locationObject();
		location.long = params.lng;
		location.lat = params.lat
		location.title = "";

		locationArray.push(location);
		
		iconArray.push("");
		
		initMap(params, markersArray, locationArray, iconArray);
	}			
}

var initMap = function(params, markersArray, locationArray, iconArray) {
	/*
	if(params.lat == null)
	{
		params.lat = 51.5001973; 
	}
	if(params.lng == null)
	{
		params.lng = -0.1262295; 
	}
	*/
			
	geocoder = new google.maps.Geocoder();	
	
	if(params.allControlsOn != null)
	{
		allControlsOn = params.allControlsOn;
	}
	
	var startPoint = new google.maps.LatLng(-0.1262295, 51.5001973);
	
	var Options = {
		center: startPoint,
		zoom: 10,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		navigationControl: allControlsOn,
		mapTypeControl: allControlsOn,
		scaleControl: allControlsOn,
		streetViewControl: allControlsOn
	}
	
	if(params.zoom != null)
	{
		Options.zoom = params.zoom;
	}
	if(params.navigationControl != null)
	{
		Options.navigationControl = params.navigationControl;
	}
	if(params.mapTypeControl != null)
	{
		Options.mapTypeControl = params.mapTypeControl;
	}
	if(params.scaleControl != null)
	{
		Options.scaleControl = params.scaleControl;
	}
	if(params.streetViewControl != null)
	{
		Options.streetViewControl = params.streetViewControl;
	}
	
	if(params.mapStyle != null)
	{
		Options.mapTypeControlOptions = { mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'customMapStyle'] };
	}
	
	if(params.mouseWheel == false)
	{
		Options.scrollwheel = false;
	}
	
	Map = new google.maps.Map(document.getElementById(params.containerID), Options);
	
	/*
	if(params.markerImage != null)
	{
		var markerImage = params.markerImage;
		
		if(params.markerCenterX != null && params.markerCenterY != null && params.markerWidth != null && params.markerHeight != null)
		{
			var imagePath = markerImage;
			markerImage = new google.maps.MarkerImage(
				imagePath,
				// This marker width/height
				new google.maps.Size(params.markerWidth, params.markerHeight),
				// The marker top left origin (used for sprite images)
				new google.maps.Point(0,0),
				// The anchor for this image is the base of the flagpole at 0,32.
				new google.maps.Point(params.markerCenterX, params.markerCenterY)
			);  

		}
		
		addMarker(Map, startPoint, markerImage, "", false);
	}
	*/
	
	if(params.mapStyle != null)
	{
		var styledMapOptions = {
			name: "customMapStyle"
		}
	
		var customMapType = new google.maps.StyledMapType(params.mapStyle, styledMapOptions);
		
		Map.mapTypes.set('customMapStyle', customMapType);
		Map.setMapTypeId('customMapStyle');
	}
		
	latlngbounds = new google.maps.LatLngBounds();

	for (var i = 0; i < locationArray.length; i++)
	{
		var newPoint = new google.maps.LatLng(locationArray[i].long, locationArray[i].lat);
		
		var marker = addMarker(Map, {Point: newPoint, Icon: iconArray[i], InfoWindow: locationArray[i].balloonContent, Title: locationArray[i].title });
		markersArray.push(marker);
		
		latlngbounds.extend(newPoint);
	}
	
	
	if(params.forceCenterLat != null && params.forceCenterLng != null)
	{
		var newPoint = new google.maps.LatLng(params.forceCenterLng, params.forceCenterLat);
		Map.setCenter( newPoint );
	}
	else
	{
		Map.setCenter( latlngbounds.getCenter() );
	}
}

var getDistance = function(A, B, km)
{
	if(fromMarkerMove != true)
	{
		fromMarkerMove = false;
	}
	
	var request = {
		origin:A, 
		destination:B,
		travelMode: google.maps.DirectionsTravelMode.DRIVING
	};
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			
			var distance = response.routes[0].legs[0].distance.value;
			
			distance = parseFloat(distance / 1000);
			if(km != true)
			{
				//convert to miles
				distance *= 0.621371192;
			}
			distance = format2Dec(distance);
			return(distance);
		}
		else
		{
			if(status == "ZERO_RESULTS")
			{
				return(-1)
			}
		}
	});	
}

var removeMarker = function(marker)
{
	if(marker != undefined)
	{
		marker.setMap(null);
	}
}

var addMarker = function(MapObj, params)
{
	if(params.CenterMap == null)
	{
		params.CenterMap = true;
	}
	
	var markerSettings = new Object;
	markerSettings.map = MapObj;
	markerSettings.position = params.Point;
	
	if(params.Icon != null)
	{
		markerSettings.icon = params.Icon;
	}
	if(params.Title != null)
	{
		markerSettings.title = params.Title;
	}
	
	var newMarker = new google.maps.Marker(markerSettings);
	
	if(params.InfoWindow != null && params.InfoWindow != "")
	{
		var infowindow = new google.maps.InfoWindow({
			content: params.InfoWindow
		});
		
		google.maps.event.addListener(newMarker, 'click', function() {
		  infowindow.open(MapObj, newMarker);
		});
	}
	
	if(params.CenterMap == true)
	{
		MapObj.setCenter(params.Point);
	}
	
	return(newMarker);
}

var checkValidUKPoint = function(A, B)
{
	var A = {
	origin:location1, 
	destination: "6 Baker Street, Paddington, Greater London",
	travelMode: google.maps.DirectionsTravelMode.DRIVING
	};
	
	directionsService.route(request1, function(response, status) {
		if(status == "ZERO_RESULTS")
		{
			//no route found
		}
	});		

	var request2 = {
	origin: B, 
	destination: "6 Baker Street, Paddington, Greater London",
	travelMode: google.maps.DirectionsTravelMode.DRIVING
	};
	
	directionsService.route(request2, function(response, status) {
		if(status == "ZERO_RESULTS")
		{
			//no route found
		}
	});
}

var format2Dec = function(num)
{
	num *= 100;
	num = parseInt(num);
	num /= 100;
	return num;
}


function codeAddress(address) {
	geocoder.geocode( { 'address': address}, function(results, status) {
	  if (status == google.maps.GeocoderStatus.OK) {
		alert(results[0].geometry.location);
	  } else {
		alert("Geocode was not successful for the following reason: " + status);
	  }
	});
}


/*Map resize
google.maps.event.trigger(startPointMap, 'resize');
*/

/*Zoom Map
Map.setZoom(12);
*/

/*Center Map
Map.setCenter(point);
*/

/*Directions
 	directionsService = new google.maps.DirectionsService();
	directionsDisplay = new google.maps.DirectionsRenderer();
*/

/*Draggable Marker
	var newMarker = new google.maps.Marker({
		position: Point, 
		map: Map, 
		title: Title,
		draggable: Draggable,
		icon: "storage/images/maps_marker_a.png"
	});
	
	google.maps.event.addListener(startMarker, 'dragend', function() {
		newStartPoint = startMarker.getPosition();
		mapDragUpdate();
	});
*/




