/* 
RecPath distance mapping software
Copyright (C) 2005  Andy Allen

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

You can contact the author at andy@recpath.com
*/
var map, r, rLine, selectedTool;

var REMOVE_RADIUS = 10;	
var LINE_COLORS = new Array('#FF0000', '#FFA500', '#FFFF00', '#00FF00', '#0000FF', '#00FFFF', '#8B008B' , '#000000');
var LINE_COLOR = 0;
var LINE_WEIGHT = 6;
var LINE_OPACITY = .5;
var MAP_TYPE = 0;

function initMap() {
	if (GBrowserIsCompatible()) {
		var homePoint = new GPoint(-112.076683,33.468917);
		map = new GMap(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		GEvent.addListener(map, "click", GMap_Click);
		GEvent.addListener(map, "maptypechanged", GMap_MapTypeChanged);
		
		r = new RPRoute();
		var centerAndZoom = r.ReadSmallUrl(window.location.search.substr(1));
		if (centerAndZoom.length > 1) {
			if (centerAndZoom[2] == 1)
				map.setMapType(G_SATELLITE_TYPE);
			else if (centerAndZoom[2] == 2) 
				map.setMapType(_HYBRID_TYPE);
			else
				map.setMapType(G_MAP_TYPE);
				
			map.centerAndZoom(centerAndZoom[0], centerAndZoom[1]); 
			LINE_COLOR = centerAndZoom[3];
			LINE_WEIGHT = centerAndZoom[4];
			LINE_OPACITY = centerAndZoom[5];
		}
		else {
			map.centerAndZoom(homePoint, 6);
		}
		
		plotPolyline();
		updateDistanceDisplay(r.ComputeLength());
		selectedTool = "addToEnd";
	}
	else
	{
		alert("Sorry, you are using a browser I can't support.");
	}
}


function GMap_Click(overlay, point) {
	removePolyline();
	
	switch (selectedTool) {
		case 'addToEnd':
			r.AddPointToEnd(new GPoint(point.x, point.y));
			break;
		case 'insert':
			
			var newIx = r.AddPointToMiddle(new GPoint(point.x, point.y));
			break;
		case 'removeAny':
			var removedIx = r.FindNearestPoint(point);
			var allowGap = getRemoveThreshold(map.getZoomLevel());
			var actualGap = r.MilesBetween(point, r.Points[removedIx]);
			
			if(actualGap <= allowGap) {
				removed = r.RemovePointAt(removedIx);
			}
			break;
	}
	
	plotPolyline();
	updateDistanceDisplay(r.ComputeLength());

}

function GMap_MapTypeChanged() {
	var t = map.getCurrentMapType();
	if (t == _HYBRID_TYPE) {
		MAP_TYPE = 2;
	}
	else if (t == G_SATELLITE_TYPE) {
		MAP_TYPE = 1;
	}
	else {
		MAP_TYPE = 0;
	}	
}


function addToEnd_Click() {
	if (selectedTool != 'addToEnd') {
		selectedTool='addToEnd';
		buttonDown("lnkAddToEnd");
		buttonUp("lnkInsert");
		buttonUp("lnkRemove");
	}
	return false;
}

function insertPoint_Click() {
	if (selectedTool != 'insert') {
		selectedTool='insert';
		buttonUp("lnkAddToEnd");
		buttonDown("lnkInsert");
		buttonUp("lnkRemove");
	}
	return false;
}

function removePoint_Click() {
	if (selectedTool != 'removeAny') {
		selectedTool='removeAny';
		buttonUp("lnkAddToEnd");
		buttonUp("lnkInsert");
		buttonDown("lnkRemove");
	}
	return false;
}

function removeFromEnd_Click() {
	if(r.Points.length >= 1) {
		removePolyline();
		r.RemovePointFromEnd();
		plotPolyline();
		updateDistanceDisplay(r.ComputeLength());
	}
	return false;
}

function undoLast_Click() {
	removePolyline();
	r.Undo();	
	updateDistanceDisplay(r.ComputeLength());
	plotPolyline();
	return false;
}

function removeAll_Click() {
	removePolyline();
	r.RemoveAllPoints();
	updateDistanceDisplay(0);
	return false;
}

function loadSmallUrl_Click() {
	window.location.href = r.MakeSmallUrl(map.getCenterLatLng(), map.getZoomLevel(), MAP_TYPE, LINE_COLOR, LINE_WEIGHT, LINE_OPACITY);
	return false;
}

function loadReallySmallUrl_Click() {
	window.location.href = r.MakeSmallUrl(map.getCenterLatLng(), map.getZoomLevel(), MAP_TYPE, LINE_COLOR, LINE_WEIGHT, LINE_OPACITY, 5, 3);
	return false;
}

function changeColor_Click() {
	removePolyline();
	LINE_COLOR = (LINE_COLOR + 1) % LINE_COLORS.length;
	plotPolyline();
	return false;
}

function changeWeight_Click() {
	removePolyline();
	LINE_WEIGHT = ((LINE_WEIGHT) % 9) + 3;
	plotPolyline();
	return false;
}

function changeOpacity_Click() {
	removePolyline();
	LINE_OPACITY = parseFloat(LINE_OPACITY) + parseFloat(.25);
	if (LINE_OPACITY == 1.25) LINE_OPACITY = parseFloat(0.25);
	plotPolyline();
	return false;
}

function addressSearch_Click() {
	var contain = document.getElementById("geoContain");
	var srch = document.getElementById("searchText");
	var btn = document.getElementById("lnkAddress");
	btn.onclick = function() { return geoClose_Click(); }		
	buttonDown("lnkAddress");
	contain.style.display = "block";	
	srch.focus();
}

function geoClose_Click() {
	var contain = document.getElementById("geoContain");
	var btn = document.getElementById("lnkAddress");
	btn.onclick = function() { return addressSearch_Click() }
	buttonUp("lnkAddress");
	contain.style.display = "none";	
}

function performAddressSearch_Click() {
	var s = document.getElementById("searchText");
	var results = document.getElementById("geoResult");
	if (s.value != "") {
		results.innerHTML = "Searching...";
		getMatches(s.value, showGeoMatches);
	}
	else {
		results.innerHTML = "Please enter an address.";
		s.focus();
	}
		
}

function takeOutOpen_Click() {
	var t = document.getElementById("takeOut");
	var btn = document.getElementById("lnkTakeOut");
	var out = document.getElementById("txtTakeOut");
	t.style.display = "block";
	buttonDown("lnkTakeOut");
	btn.onclick = function() { return takeOutClose_Click() }	
}

function takeOutClose_Click() {
	var t = document.getElementById("takeOut");
	var btn = document.getElementById("lnkTakeOut");
	t.style.display = "none";
	buttonUp("lnkTakeOut");
	btn.onclick = function() { return takeOutOpen_Click() }
}

function str2rte_Click() {
	var txt = document.getElementById("txtTakeOut");
	var str = txt.value;
	var msg = document.getElementById("txt2map_message");
	msg.innerHTML = "Loading route...";
	
	var centerAndZoom = r.ReadSmallUrl(str);
	if (centerAndZoom.length > 1) {
		if (centerAndZoom[2] == 1)
			map.setMapType(G_SATELLITE_TYPE);
		else if (centerAndZoom[2] == 2) 
			map.setMapType(_HYBRID_TYPE);
		else
			map.setMapType(G_MAP_TYPE);
			
		map.centerAndZoom(centerAndZoom[0], centerAndZoom[1]); 
		LINE_COLOR = centerAndZoom[3];
		LINE_WEIGHT = centerAndZoom[4];
		LINE_OPACITY = centerAndZoom[5];
	}
	plotPolyline();
	updateDistanceDisplay(r.ComputeLength());
	msg.innerHTML = "";
	takeOutClose_Click();

	return false;
}

function rte2str_Click() {
	var txt = document.getElementById("txtTakeOut");
	var msg = document.getElementById("txt2map_message");
	msg.innerHTML = "Making route...";
	txt.value = "v=2&r=" + r.MakePackedRoute(map.getCenterLatLng(), map.getZoomLevel(), MAP_TYPE, LINE_COLOR, LINE_WEIGHT, LINE_OPACITY);
	msg.innerHTML = "";
	return false;
}

function showGeoMatches(matches) {
	var successOrError = matches.shift();
	var results = document.getElementById("geoResult");
	var contain = document.getElementById("geoContain");
	var newHTML = "";		

	if (successOrError == "success") {
		if (matches[0].indexOf("couldn't find") == -1) {	
			if (matches.length == 1) {
				var parts = matches[0].split(",");
				followSearchResult(parts.shift(), parts.shift(), parts.join(","));
			}
			else {
				for (var i = 0; i < matches.length; i++) {
					var parts = matches[i].split(",");
					var lat = parts.shift();
					var lon = parts.shift();
					var addr = parts.join(",");
					newHTML += "<a href='javascript:void(0);' onclick='followSearchResult(" + lat + "," + lon + ",\"" + addr + "\");'>" + addr + "</a><br />";
				}
			}
		}
		else {
			newHTML = "That address was not found.";
		}
	}
	else {
		newHTML = "Error: " + matches.join("\n");
	}
	results.innerHTML = newHTML;
}

function followSearchResult(lat, lon, label) {
	map.centerAndZoom(new GPoint(lon, lat), 1); 
	geoClose_Click();
}

function searchOnEnter() {
	if(window.event && window.event.keyCode == 13) {
		performAddressSearch_Click();
		return false; 
	}
	else
		return true; 
}

function updateDistanceDisplay(newDist) {
	estimateLinkSize();
	var distReadOut = document.forms["frmDistance"].elements["txtDistance"];
	distReadOut.value = fixDecimal(newDist, 3);
}

function estimateLinkSize() {
	var maxLinkSize = 2000;
	var bigButton = document.getElementById("btnBigLink");
	var lilButton = document.getElementById("btnLilLink");
	
	var estSmall = r.EstimatePackedRouteSize(true);
	var estBig = r.EstimatePackedRouteSize(false);
	
	if (estBig > maxLinkSize) {
		bigButton.src = bigButton.src.replace("biglink.gif", "biglink_disabled.gif")
		bigButton.onclick = function () {  }
		bigButton.title =  "Route too long for big link";
	}
	else {
		bigButton.src = bigButton.src.replace("biglink_disabled.gif", "biglink.gif")
		bigButton.onclick = function () { return loadSmallUrl_Click() }
		bigButton.title =  "Make a Link\n(est. " + estBig + " characters)";
	}

	if (estSmall > maxLinkSize) {
		lilButton.src = lilButton.src.replace("link.gif", "link_disabled.gif")
		lilButton.onclick = function () {  }
		lilButton.title = " Route too long for compact link";
	}
	else {
		lilButton.src = lilButton.src.replace("link_disabled.gif", "link.gif")
		lilButton.onclick = function () { return loadReallySmallUrl_Click() }
		lilButton.title = "Make a Compact Link\n(est. " + estSmall + " characters)";
	}
}

function removePolyline() {
	if (rLine) {
		map.removeOverlay(rLine);
	}
}

function plotPolyline() {
	ptAry = r.Points;
	if(ptAry.length == 1) {
		var otherPoint = new GPoint(ptAry[0].x + 0.00001, ptAry[0].y);
		ptAry.push(otherPoint);
		rLine = new GPolyline(ptAry, LINE_COLORS[LINE_COLOR], LINE_WEIGHT, LINE_OPACITY);
		ptAry.pop();
	}
	else {
		rLine = new GPolyline(ptAry, LINE_COLORS[LINE_COLOR], LINE_WEIGHT, LINE_OPACITY);
	}
	map.addOverlay(rLine);
}

function getRemoveThreshold(zoom) {
	var thresholdMiles;
	if (zoom < 7) {
		var milesPerPx = new Array(0.0005079957102729373,0.0012174150045456625,0.002432680681019887,0.0048632106091041245,0.009726241947514594,0.019452304621870132,0.03890442996944458);
		thresholdMiles = REMOVE_RADIUS * milesPerPx[zoom];
	}
	else {
		thresholdMiles = 1000;
	}
	return thresholdMiles;
}

function buttonDown(id) {
	var button = document.getElementById(id);
	if (button.src.indexOf('_dn.gif') == -1) button.src = button.src.replace('.gif', '_dn.gif');
}

function buttonUp(id) {
	var button = document.getElementById(id);
	if (button.src.indexOf('_dn.gif') > -1)button.src = button.src.replace('_dn.gif', '.gif');
}

