var map;
var map_center;
var edit_mode;
var theMarkers;
var theData;
var theCoords;
var thePolyline;
var drawPolyline = false;
var latlngBounds;
var distance = 0;
var duration = 0;

var curSpeed = 0;
var curDistance = 0;
var curDuration = 0;
var curHeading;

var geocoder;

function epictracker_initialize_admin()
{
	epictracker_initialize(true);
}

function epictracker_initialize(edit, map_div_id)
{	
	if (!edit) 
	{
		edit = false;
	}

	edit_mode = edit;
	
	if (!map_div_id)
	{
		map_div_id = "et_map_canvas";
	}
	
	if (theData && (theData.length>0))
	{
		map_center = new google.maps.LatLng(theData[0]['lat'], theData[0]['lng']);	
	}
	else
	{
		map_center = new google.maps.LatLng(0, 0);
	}
	
	var myOptions = {zoom: 5, center: map_center, mapTypeId: google.maps.MapTypeId.HYBRID, streetViewControl: false};
	map = new google.maps.Map(document.getElementById(map_div_id), myOptions);

	createMarkers();
	
	if (edit)
	{
		initEditor(map_div_id);
	}
	else
	{
		initViewer(map_div_id);
	}
	
	zoomToFitAll();
}

function initViewer(map_div_id)
{
	if (drawPolyline)
	{
		createPolyline();
	}

	doJourneyStats();

	if (theCoords.length >= 2)
	{
		var distInKMs = distance / 1000;
		var distInMiles = distance * 0.000621371192;
		jQuery(".et_distance").html(Math.round(distInMiles) + " miles");
		var oneDay = 60*60*24;
		var numDays = duration/oneDay;
		jQuery(".et_duration").html(Math.round(numDays) + " days");
		jQuery(".et_avg_speed").html(Math.round(distInMiles/numDays)  + " miles/day");
		jQuery(".et_heading").html("Heading: " + Math.round(curHeading)  + "&deg;");
		jQuery(".et_speed").html("Miles/day: " + Math.round(curDistance*0.000621371192 / (curDuration/(3600*24))));
		
		//jQuery("div.scrollable").scrollable({ items: '#thumbs', hoverClass: 'hover' });	
	}
	else
	{
		jQuery(".epic_stats_display").html("There are not enough posts to show statistics.");
	}
}

function initEditor(map_div_id)
{
	geocoder = new google.maps.Geocoder();
}

function codeAddress()
{
	var address = document.getElementById("et_search_str").value;
	if (geocoder)
	{
		geocoder.geocode( { 'address': address}, 
							function(results, status)
							{
								if (status == google.maps.GeocoderStatus.OK)
								{
									var lat = results[0].geometry.location.lat();
									var lng = results[0].geometry.location.lng();
									
									var newPos = new google.maps.LatLng(lat,lng);
									theMarkers[0].setPosition(newPos);
									updateMap(lat, lng);
									updateFormFields(lat, lng);
								}										
								else 
								{
									alert("Geocode was not successful for the following reason: " + status);
								}
							});
	}
}

function updateMap(lat, lon)
{
	var newPos = new google.maps.LatLng(lat,lon);
	map.setCenter(newPos);
	//map.setZoom(15);
}

function updateFormFields(lat, lng, lat_field_id, lng_field_id)
{	
	if (!lat_field_id)
	{
		lat_field_id = "et_lat";
	}
	
	if (!lng_field_id)
	{
		lng_field_id = "et_lng";
	}
	
	var dec = 7;
	lat = Math.round(lat*Math.pow(10,dec))/Math.pow(10,dec);
	lng = Math.round(lng*Math.pow(10,dec))/Math.pow(10,dec);			
	document.getElementById(lat_field_id).value = lat;
	document.getElementById(lng_field_id).value = lng;			
}				

function randomizeLocation(id)
{
	var idx = getPostIndexFromID(id);
	var curPos = theMarkers[idx].position;
	var lat1 = curPos.lat();
	var lon1 = curPos.lng();
	
	var tmpAdj = Math.random();
	var tmpAdj2 = Math.random();			
	var latAdj = (0.5-tmpAdj)/100;
	var lonAdj = (0.5-tmpAdj2)/100;			
	var lat2 = lat1 + latAdj;
	var lon2 = lon1 + lonAdj;			
	
	var newPos = new google.maps.LatLng(lat2, lon2);
	theMarkers[idx].setPosition(newPos);
	map.setCenter(newPos);
	
	updateFormFields(lat2, lon2);
}



function addMarker(id, title, lat, lng, args)
{
	if (!theData)
	{
		theData = new Array();
	}

	// make sure there aren't any duplicate id's added
	for (var i=0; i<theData.length; i++)
	{
		if (theData[i]['id'] == id)
		{
			return false;
		}
	}
	
	
	var theItem = new Array();
	theItem['id'] = id;
	theItem['title'] = title;
	theItem['lat'] = lat;
	theItem['lng'] = lng;

	if (args)
	{
		 if (args['permalink'])
		 {
			theItem['permalink'] = args['permalink'];
		 }
		 if (args['theDate'])
		 {
			theItem['date'] = args['theDate'];
		 }
		 if (args['draggable'])
		 {
			theItem['draggable'] = args['draggable'];
		 } 
	}	
	
	theData.push(theItem);

	return theData.length;
}

function createMarkers()
{
	theMarkers = new Array();
	theCoords = new Array();
	
	if (map)
	{
		for (var i=0; i<theData.length; i++)
		{
			var tmpDraggable = (theData[i]['draggable'] === true);
			var newMarker = new google.maps.Marker({
				position: new google.maps.LatLng(theData[i]['lat'], theData[i]['lng']),
				map: map,
				title: theData[i]['title'],
				permalink: theData[i]['permalink'],
				postID: theData[i]['id'],
				date: theData[i]['date'],
				draggable: tmpDraggable
				});
			theMarkers.push(newMarker);
			google.maps.event.addListener(theMarkers[i], 'click', function(event) { onMarkerClick(newMarker); } );
			google.maps.event.addListener(theMarkers[i], 'drag', function(event) { updateFormFields(event.latLng.lat(), event.latLng.lng());} );
			theCoords.push(new google.maps.LatLng(theData[i]['lat'], theData[i]['lng']));
		}
	}
}

function getPostIndexFromID(id)
{
	for (var i=0; i < theData.length; i++)
	{
		if (theData[i]['id'] == id)
		{
			return i;
		}
	}
	return -1;				
}

function createPolyline()
{
	if (theCoords && (theCoords.length >= 2))
	{
		thePolyline = new google.maps.Polyline({
			path: theCoords, 
			strokeColor: "CC0000", 
			strokeOpacity: 0.8, 
			strokeWeight: 2
			});

		if (map)
		{
			thePolyline.setMap(map);
		}
	}
}	

function onMarkerClick(item)
{
	if (!edit_mode && item.permalink)
	{
		window.location = item.permalink;
	}	
}

function gotoMarker(id)
{
	var idx = getPostIndexFromID(id);
	if (idx>=0)
	{
		map.panTo(theCoords[idx]);
	}
}

function gotoLatLng(latlng)
{
	map.panTo(latlng);
}

function gotoLocation(lat, lng)
{
	gotoLatLng(new google.maps.LatLng(lat,lng));
}

function zoomToFitAll()
{
	if (!theCoords || (theCoords.length==0))
	{
		return;
	}
	else if (theCoords.length==1)
	{
		gotoLatLng(theCoords[0]);
	}
	else
	{
		if (latlngBounds == null)
		{
			latlngBounds = new google.maps.LatLngBounds();

			for (var i=0; i < theCoords.length; i++)
			{
				latlngBounds.extend(theCoords[i]);
			}
		}
		map.fitBounds(latlngBounds);
	}
}

function doJourneyStats()
{
	if (theCoords.length>1)
	{
		//alert(theData[theData.length-1]['date']);
		distance = google.maps.geometry.spherical.computeLength(theCoords);
		duration = getDiffInSeconds(theData[0]['date'], theData[theData.length-1]['date']);

		// current information (between last two posts)
		curHeading = google.maps.geometry.spherical.computeHeading(theCoords[theCoords.length-2], theCoords[theCoords.length-1]);
		curDistance = google.maps.geometry.spherical.computeDistanceBetween(theCoords[theCoords.length-2], theCoords[theCoords.length-1]);
		curDuration = getDiffInSeconds(theData[theData.length-2]['date'], theData[theData.length-1]['date']);
		curSpeed = curDistance / curDuration;
	}
}

function getDiffInDays(d1, d2)
{
	var t2 = d2.getTime();
	var t1 = d1.getTime();
	return parseInt((t2-t1)/(24*3600));
}

function getDiffInHours(d1, d2)
{
	var t2 = d2.getTime();
	var t1 = d1.getTime();
	return parseInt((t2-t1)/3600);
}			

function getDiffInSeconds(d1, d2)
{
	var t2 = d2.getTime();
	var t1 = d1.getTime();
	return parseInt(t2-t1);
}			

