// JavaScript Document

/**
* Data for initial map load
*/
hamilton = new google.maps.LatLng(42.826834, -75.54431);
myInitOptions = {
	zoom: 10,
	center: hamilton,
	mapTypeId: google.maps.MapTypeId.ROADMAP
}

/**
* Data for the markers consisting of a name, a LatLng and a zIndex for
* the order in which these markers should display on top of each
* other.
*/
/*
pois = [
  ['Two Broad Street, Hamilton NY 13346', 1],
  ['12 South Broad, Norwich NY 13815', 2]
];
 */
pois = [
 ['306 Utica Street, Hamilton, NY', 1]
];
 
/**
* Trail Data
*/
stonyPond = [
  ['Stony Pond XC-Ski Trail Head', 42.880057, -75.722770, 1, '<div style="color: black"><strong>XC-Skiing at Stony Pond (Full Moon Trek)<br/>Start Location:<br/>&nbsp;&nbsp;Latitude:</strong> 42.880057&deg; N<br/><strong>&nbsp;&nbsp;Longitude:</strong> 75.722770&deg; W<br/><strong>Date:</strong> Dec 30, 2009 7:01 pm<br/><strong>Distance:</strong> 3.07 miles<br/><strong>Elapsed Time:</strong> 57:42.4<br/><strong>Min Altitude:</strong> 1,430 ft<br/><strong>Max Altitude:</strong> 1,613 ft</div>', './xml/stonypond-xcski.xml',14]
];
golfCourse = [
  ['Colgate\'s Golf Course XC-Ski Trail Head', 42.823162, -75.538285, 1, '<div style="color: black"><strong>XC-Skiing at Colgate\'s Golf Course<br/>Start Location:<br/>&nbsp;&nbsp;Latitude:</strong> 42.823162&deg; N<br/><strong>&nbsp;&nbsp;Longitude:</strong> 75.538285&deg; W<br/><strong>Date:</strong> Dec 28, 2009 2:08 pm<br/><strong>Distance:</strong> 3.37 miles<br/><strong>Elapsed Time:</strong> 53:45.0<br/><strong>Min Altitude:</strong> 1,164 ft<br/><strong>Max Altitude:</strong> 1,478 ft</div>', './xml/golfcourse-xcski.xml',14]
];
towPath = [
	['Tow Path Trail Head', 42.830064, -75.548655, 1, '<div style="color: black"><strong>XC-Skiing at Hamilton\'s Tow Path<br/>Start Location:<br/>&nbsp;&nbsp;Latitude:</strong> 42.8298&deg; N<br/><strong>&nbsp;&nbsp;Longitude:</strong> 75.549&deg; W<br/><strong>Date:</strong> Jan 11, 2010 5:25 pm<br/><strong>Distance:</strong> 4.67 miles<br/><strong>Elapsed Time:</strong> 01:25:07</div>', 'xml/towpath-xcski.xml',14]
];
colgateXCTrail = [
	['Colgate\'s Cross Country Trail Head', 42.812341, -75.537685, 1, '<div style="color: black"><strong>XC-Skiing on Colgate\'s Cross Country Trails<br/>Start Location:<br/>&nbsp;&nbsp;Latitude:</strong> 42.8143&deg; N<br/><strong>&nbsp;&nbsp;Longitude:</strong> 75.5368&deg; W<br/><strong>Date:</strong> Jan 9, 2010 5:02 pm<br/><strong>Distance:</strong> 3.3 miles<br/><strong>Elapsed Time:</strong> 00:56:56</div>', 'xml/colgatetrails-xcski.xml',14]
];
battenkill = [
  ['The infamous Battenkill Route', 43.091690, -73.413391, 1, '<div style="color: black"><strong>The infamous Battenkill Route<br/><strong>Distance:</strong> 62 mi<br/><strong>Ascent:</strong> 2684 ft</div>', './xml/2010Battenkill.gpx.xml',10]
];
vernonCenter = [
  ['Vernon Center Route', 42.9392363, -75.4610076, 1, '<div style="color: black"><strong>Vernon Center Route<br/><strong>Distance:</strong> 54 mi<br/><strong>Ascent:</strong> 2029 ft</div>', './xml/Vernon_Center_Route.gpx.xml',10]
];
cazenoviaFenner = [
  ['Cazenovia via Fenner', 42.890689, -75.7061, 1, '<div style="color: black"><strong>Cazenovia via Fenner<br/><strong>Distance:</strong> 44 mi<br/><strong>Ascent:</strong> 1570 ft</div>', './xml/Cazenovia_Fenner.gpx.xml',10]
];
deansboroLoop = [
  ['Deansboro Loop', 42.902535, -75.480022, 1, '<div style="color: black"><strong>Deansboro Loop<br/><strong>Distance:</strong> 37 mi<br/><strong>Ascent:</strong> 1441 ft</div>', './xml/Deansboro_Loop.gpx.xml',11]
];
georgetownLoop = [
  ['Georgetown Loop', 42.781106, -75.636406, 1, '<div style="color: black"><strong>Georgetown Loop<br/><strong>Distance:</strong> 37 mi<br/><strong>Ascent:</strong> 1240 ft</div>', './xml/Georgetown_Loop.gpx.xml',11]
];
hatchLakeLoop = [
  ['Hatch Lake Loop', 42.821914, -75.626106, 1, '<div style="color: black"><strong>Hatch Lake Loop<br/><strong>Distance:</strong> 26 mi<br/><strong>Ascent:</strong> 948 ft</div>', './xml/Hatch_Lake_Loop.gpx.xml',11]
];
solsvillesWindmills = [
  ['Solsville\'s Windmills', 42.904958, -75.581474, 1, '<div style="color: black"><strong>Solsville\'s Windmills<br/><strong>Distance:</strong> 32 mi<br/><strong>Ascent:</strong> 1380 ft</div>', './xml/Solsville_Windmill_Loop.gpx.xml',11]
];
lebanonLoop = [
  ['Lebanon Loop', 42.75792, -75.562248, 1, '<div style="color: black"><strong>Lebanon Loop<br/><strong>Distance:</strong> 28 mi<br/><strong>Ascent:</strong> 481 ft</div>', './xml/Lebanon_Loop.gpx.xml',11]
];
singleTrak = [
  ['Single Trak', 42.818593, -75.538795, 1, '<div style="color: black"><strong>Single Trak<br/><strong>Distance:</strong> 6 mi<br/><strong>Ascent:</strong> 700 ft</div>', './xml/SingleTrak.gpx.xml',14]
];
stonyPond = [
  ['Stony Pond Trails', 42.884306, -75.713782, 1, '<div style="color: black"><strong>Stony Pond Trails<br/><strong>Distance:</strong> 6 mi<br/><strong>Ascent:</strong> 500 ft</div>', './xml/StonyPondStateForest.gpx.xml',14]
];
tourDeCure = [
	['Tour de Cure', 43.2392, -75.9100, 1, '<div style="color: black"><strong>Tour de Cure</strong></div>', './xml/Tour_de_Cure_2010.gpx.xml', 9]
];

var map = null;
var geocoder = null;
var directionDisplay = null;
var directionsService = null;
var pathCoordinates = [];
var poly = null;
var trackData;
var infowindowLevel = 0;

/**
*/
function initializeSearch(start, end) {
	geocoder = new google.maps.Geocoder();
	directionsService = new google.maps.DirectionsService();
	directionsDisplay = new google.maps.DirectionsRenderer();
	directionsDisplay.setPanel(document.getElementById("directionsPanel"));
	
	var map = new google.maps.Map(document.getElementById("map_canvas"), myInitOptions);
	directionsDisplay.setMap(map);
	
	if (start == null || end == null)
		setLocations(map, pois);
	else
		calcRoute(start, end);
}

/**
*/
function loadTrack(data) {
	detectBrowser();
	
	var trackData = data[0];
	var trackLatLong = new google.maps.LatLng(trackData[1], trackData[2]);
	var initOptions = {
		zoom: trackData[6],
		center: trackLatLong,
		mapTypeId: google.maps.MapTypeId.TERRAIN
	}
	var map = new google.maps.Map(document.getElementById("map_canvas"), initOptions);
	
	setMarkers(map, data);
	setLocations(map, pois);
	setTrack(map, trackData[5]);
}

/**
*/
function loadMarker(location) {
	detectBrowser();
	
	var map = new google.maps.Map(document.getElementById("map_canvas"), myInitOptions);
	
	setTrack(map, trackData);
	setMarkers(map, pois);
}

/**
*/
function detectBrowser() {
	var useragent = navigator.userAgent;
	var mapdiv = document.getElementById("map_canvas");
	
	if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) {
		mapdiv.style.width = '100%';
		mapdiv.style.height = '100%';
	} else {
		mapdiv.style.width = '300px';
		mapdiv.style.height = '400px';
	}
}

/**
*/
function setLocations(map, locations) {
	for (var i = 0; i < locations.length; i++) {
		var poi = locations[i];
		codeAddress(map, poi[0], poi[1]);
	}
}

/**
*/
function setMarkers(map, locations) {
	for (var i = 0; i < locations.length; i++) {
		var poi = locations[i];
		var latlng = new google.maps.LatLng(poi[1], poi[2]);
		// Origins, anchor positions and coordinates of the marker
		// increase in the X direction to the right and in
		// the Y direction down.
		var image = new google.maps.MarkerImage('images/info.png',
			// This marker is 32 pixels wide by 32 pixels tall.
			new google.maps.Size(32, 37),
			// The origin for this image is 0,0.
			new google.maps.Point(0, 0),
			// The anchor for this image is the base of the trail at 0,32.
			new google.maps.Point(0, 37));
		var shadow = new google.maps.MarkerImage('images/trail.shadow.png',
			// The shadow image is larger in the horizontal dimension
			// while the position and offset are the same as for the main image.
			new google.maps.Size(59, 32),
			new google.maps.Point(0,0),
			new google.maps.Point(0, 32));
		// Shapes define the clickable region of the icon.
		// The type defines an HTML <area> element 'poly' which
		// traces out a polygon as a series of X,Y points. The final
		// coordinate closes the poly by connecting to the first
		// coordinate.
		var shape = {
			coord: [1, 1, 1, 20, 18, 20, 18 , 1],
			type: 'poly'
		};
		var poiMarker = new google.maps.Marker({
				position: latlng,
				map: map,
				title: poi[0],
				zIndex: poi[3],
				// shadow: shadow,
				icon: image,
				shape: shape
		});
		var info = poi[4];
		attachInfowindow(map, poiMarker, poi[3], info);
	}
}

/**
*/
function xmlLoad(url) {
	if (window.XMLHttpRequest) {
		xhttp=new XMLHttpRequest();
	}
	else {
		xhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xhttp.open("GET",url,false);
	xhttp.send("");
	return xhttp.responseXML;
}

/**
*/
function setTrack(map, url) {
	// We create pathCoordinates as an MVCArray so we can
	// manipulate it using the insertAt() method
	pathCoordinates = new google.maps.MVCArray();
	
	trackData = xmlLoad(url);
	var trkpts = trackData.documentElement.getElementsByTagName("trkpt");
	for (var i = 0; i < trkpts.length; i++) {
		var lat = parseFloat(trkpts[i].getAttribute("lat"));
		var lng = parseFloat(trkpts[i].getAttribute("lon"));
		var latlng = new google.maps.LatLng(lat,lng);
		pathCoordinates.insertAt(i, latlng);
	}
	
	var polyOptions = {
		path: pathCoordinates,
		strokeColor: '#FF0000',
		strokeOpacity: 1.0,
		strokeWeight: 3
	}
	
	poly = new google.maps.Polyline(polyOptions);
	poly.setMap(map);
}

/**
*/
function codeAddress(map, poi, z) {
	if (geocoder) {
		geocoder.geocode( { 'address': poi }, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					// Origins, anchor positions and coordinates of the marker
					// increase in the X direction to the right and in
					// the Y direction down.
					var image = new google.maps.MarkerImage('images/POI.png',
						// This marker is 32 pixels wide by 32 pixels tall.
						new google.maps.Size(32, 32),
						// The origin for this image is 0,0.
						new google.maps.Point(0, 0),
						// The anchor for this image is the base of the POI at 0,32.
						new google.maps.Point(32, 32));
					var shadow = new google.maps.MarkerImage('images/POI.shadow.png',
						// The shadow image is larger in the horizontal dimension
						// while the position and offset are the same as for the main image.
						new google.maps.Size(59, 32),
						new google.maps.Point(0,0),
						new google.maps.Point(32, 32));
					// Shapes define the clickable region of the icon.
					// The type defines an HTML <area> element 'poly' which
					// traces out a polygon as a series of X,Y points. The final
					// coordinate closes the poly by connecting to the first
					// coordinate.
					var shape = {
						coord: [1, 1, 1, 20, 18, 20, 18 , 1],
						type: 'poly'
					};
					var poiMarker = new google.maps.Marker({
							map: map, 
							position: results[0].geometry.location,
							title: 'Adventure Bikes & Boards',
							zIndex: z,
							shadow: shadow,
							icon: image,
							shape: shape
					});
					var info = '<div style="color: #000">Adventure Bikes & Boards<br/>'+poi+'<br/>'+results[0].geometry.location+'</div>';
					attachInfowindow(map, poiMarker, z, info);
				}
		});
	}
}

/**
*/
function attachInfowindow(map, marker, number, info) {
	var infowindow = new google.maps.InfoWindow({ content: info });
	google.maps.event.addListener(marker, 'click', function() {
			infowindow.setZIndex(number);
			infowindow.open(map,marker);
	});
}

/**
*/
function calcRoute(start, end) {
	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 {
				var warnings = document.getElementById("warnings_panel");
				warnings.innerHTML = "<strong>There seems to be an error. We did not recognize your address: <br/>'"+start+"'</strong>";
			}
	});
}

