

var gMaxRouteLength = 30

function remakeMapUri(map, oldUri, id)
{
	uri = oldUri
	if(oldUri.indexOf("=")==-1){
		uri = uri + "?"
	}else{
		uri = uri + "&"
	}
	uri = uri + "center_x="+map.getCenter().lng()+"&"
	uri = uri + "center_y="+map.getCenter().lat()+"&"
	uri = uri + "zoom_level="+map.getZoom()+"&"
	mtype = map.getCurrentMapType()
	if(mtype==G_SATELLITE_MAP){
		uri = uri + "map_type=Satellite&"
	}else if(mtype==G_HYBRID_MAP){
		uri = uri + "map_type=Hybrid&"
	}
	uri = uri + "route="+id
	return uri
}

function makePrintUri(map, oldUri, id)
{
	uri = remakeMapUri(map, oldUri, id)
	uri = uri + "&print=1"
	return uri
}

function hideElement(id)
{
	el = document.getElementById(id)
	if(el){
		el.style.display='none';
	}
}
function showElement(id, typeShow)
{
	el = document.getElementById(id)
	if(el){
		if(typeShow){
			el.style.display=typeShow;
		}else{
			el.style.display='';
		}
	}
}

function showRouteElements(routes, elems, id)
{
	for (i in routes){
		if(routes[i]['id']==id){
			for (j in elems){
				el_name = 'route_'+id+'_'+elems[j];
				showElement(el_name)
			}
			return;
		}
	}
}

function hideRouteElements(routes, elems)
{
	for (i in routes){
		rid = routes[i]['id']
		for (j in elems){
				el_name = 'route_'+rid+'_'+elems[j];
				hideElement(el_name)
		}
	}
}

function distBetweenPts(route, start, stop)
{
	total = 0;
	if(typeof(start)=="string"){
		start = parseInt(start);
	}
	if(typeof(stop)=="string"){
		stop = parseInt(stop);
	}
	for(var i=start+1; i<=stop; i++){
		total+= route['pts'][i].distanceFrom(route['pts'][i-1])
	}
	return total;
}

function rescalePt(pt, scale, bounds)
{
	n = bounds.getNorthEast().lat();
	w = bounds.getSouthWest().lng();

	dlat = n-pt.lat();
	dlng = pt.lng() - w;
	dlat = dlat * scale;
	dlng = dlng * scale;
	r = new GLatLng(n-dlat, w+dlng);

	return r;
	
}
function makeRouteOverlay(route, map, scale)
{
	var latlng = []
	for (i in route['pts']){
		ll = route['pts'][i];
		/*
		if(scale!=1.0){
			ll = rescalePt(ll, scale, map.getBounds())
		}
		*/
		//GLog.write("ll:"+ll)
		latlng.push(ll);
	}
	if(route['edit_mode']==true){
		return new GPolyline(latlng, color = "#ED1E33");
		
	}else if(route['isPrint']==1){
		return new GPolyline(latlng, color = "#FFFFFF", weight=5, opacity=1.0);
	}else{
		return new GPolyline(latlng, color = "#28D62B");
	}
}

var gIconDir = '/static/images/ui/icons/mapmarkers/'

function routeIconName(pointNr, edit_mode)
{
	var img;
	if(pointNr==0){
		img = gIconDir+ 'start.png';
	}else{
		img = gIconDir+ pointNr +'.png'
	}
	return img;
}

function routeIconPrintName(pointNr, edit_mode)
{
	var img;
	if(pointNr==0){
		img = gIconDir+ 'start.gif';
	}else{
		img = gIconDir+ pointNr +'.gif'
	}
	return img;
}

function makeRouteIcon(pointNr, edit_mode)
{
	var icon = new GIcon();

	icon.image = routeIconName(pointNr, edit_mode);
	//icon.printImage = routeIconPrintName(pointNr, edit_mode);
	//icon.mozPrintImage = routeIconPrintName(pointNr, edit_mode);
 	icon.iconSize = new GSize(16, 16);
	icon.iconAnchor = new GPoint(7, 7);
	icon.infoWindowAnchor = new GPoint(7, 7);
	return icon;
}



function dragendFunc(map, route, pointNr)
{
	marker = route['overlays']['markers'][pointNr]
	pos = marker.getPoint();
	route['pts'][pointNr] = pos;
	redrawRoute(map, route);
}

function centerMapToPt(map, route, pt)
{
	map.setCenter(route['pts'][pt]);
}

function dragFunc(map, route, pointNr)
{
	marker = route['overlays']['markers'][pointNr]
	pos = marker.getPoint();
	route['pts'][pointNr] = pos;
	redrawPolyline(map, route);
	//GLog.write(marker);
	//onMarkerDrag(globalMap, gRoute, globalMap);
}

function makeRouteMarker(pt, pointNr, map, route)
{
		var attrs = {icon: makeRouteIcon(pointNr, route['edit_mode'])};
		if(route['edit_mode']==true){
			attrs.draggable = true;
			attrs.dragCrossMove = false;
		}
		if (typeof(pt.note)!="undefined" && pt.note.length>0){
			attrs.title = pt.note
		}
		var marker = new GMarker(pt, attrs);
		if(route['edit_mode']==true){
			def = function(){ dragendFunc(map, route, pointNr);}
			GEvent.addListener(marker, "dragend", def);
			drag = function(){ dragFunc(map, route, pointNr);}
			GEvent.addListener(marker, "drag", drag);
		}else{
			var clickFunc = function(){
										txt = route.formatInfoWindowFn(pointNr);
										marker.openInfoWindowHtml(txt);
										}
			GEvent.addListener(marker, "click", clickFunc);
		
		}
		marker.pointNr = pointNr
		return marker;

}
function makeRouteMarkers(pts, map, route)
{
	var markers = []
	for (i in pts){
		markers.push(makeRouteMarker(pts[i], i, map, route));
	}
	return markers;
}

function ppCoord(full)
{
	deg = Math.floor(full);
	full = (full - deg) * 60
	min = Math.floor(full)
	min = ''+min;
	if (min.length==1) min = '0'+min;

	full = ( full - min)*60
	sec = Math.floor(full)
	sec = ''+sec;
	if(sec.length==1) sec = '0'+sec
	r = ''+deg+'\u00b0 '+min+"' "+ sec+"''"
	return r 
}
function roundMetersToMiles(meter)
{
	
	r = Math.floor(meter/18.52);
	r = (r/100).toString(10);
	//fix cases where r is 17.2 and it should be 17.20 or 17 and it should be 17.00
	dotPos = r.indexOf('.')
	if(dotPos==-1){
		r= r+'.00'
	}
	else if(dotPos==r.length-2){
		r = r+'0';
	}
	return r
}


function redrawPolyline(map, route)
{
	newPolyline = makeRouteOverlay(route, map, gScale)
	if (route['overlays']['polyline']){
		map.removeOverlay(route['overlays']['polyline']);
	}
	map.addOverlay(newPolyline);
	
	route.overlays['polyline'] = newPolyline;

}

function redrawMarkers(map, route)
{
	newMarkers = makeRouteMarkers(route['pts'], map, route);
	for (mrkr in route['overlays']['markers']){
		map.removeOverlay(route['overlays']['markers'][mrkr]);
	}
	for (mrkr in newMarkers){
		map.addOverlay(newMarkers[mrkr]);
	}
	route['overlays']['markers'] = newMarkers;
}

function redrawRoute(map, route)
{
	redrawPolyline(map, route);
	redrawMarkers(map, route);
	//route["updateDisplayFn"]()
	route.updateDisplayFn()
	return route;

}

function findRoutePoint(route, pt)
{
	for(i in route['pts']){
		if (pt.distanceFrom(route['pts'][i])< 10) return i;
	}
	return -1;
}

function addRoutePoint(route, latlong, map, note)
{
	//GLog.write("route pts len"+ route.pts.length)
	if(route['pts'].length <gMaxRouteLength){
		if(-1!=findRoutePoint(route, latlong)){
			return;//can't have two points on the same place
		}
		if(note){
			latlong.note = note;
		}

		route['pts'].push(latlong);
		if (map){
			return redrawRoute(map, route);
		}
	}else{
		alert("Route to long!");
		return 0;
	}

}

function removeRoutePoint(route, pointNr, map)
{
	newPts = [];
	for (i in route['pts']){
		if(i!=pointNr){
			newPts.push(route['pts'][i])
		}
	}
	route['pts'] = newPts;
	return redrawRoute(map, route);
	
}


function hideRoute(map, route)
{
	if(!route['overlays']['polyline']) return;
	map.removeOverlay(route['overlays']['polyline']);
	for (mrkr in route['overlays']['markers']){
		map.removeOverlay(route['overlays']['markers'][mrkr]);
	}
	route['edit_mode'] = false
	el = document.getElementById(route['displayId'])
	el.innerHTML=''
	
}

function findRoute(routes, id)
{
	for(r in routes){
		if(routes[r]['id']==id){
			return r
		}
	}
	return -1;
}

function findRouteByName(routes, rname)
{
	for(r in routes){
		if(routes[r]['name']==rname){
			return r
		}
	}
	return -1;
}
function findMaxNr(baseName, routes)
{
	maxNr = 0
	len_b= baseName.length; 
	for(r in routes){
		nm = routes[r]['name']
		if (nm.length>len_b && nm.substring(0, len_b)==baseName)//base name match
		{
			nr = nm.substr(len_b, nm.length-len_b);
			nr = parseInt(nr)
			if(typeof(maxNr)=="number" && nr>maxNr){
				maxNr = nr;
			}
		}
	}
	return maxNr;
}
function findAvailableNameNr(baseName, routes)
{
	nr = findMaxNr(baseName, routes);
	return nr+1;
}

function deleteRoute(routes, id)
{
	nr = findRoute(id);
	if(nr==-1) return routes;
	newRoutes = [];
	for (i in routes){
		if(i!=nr){
			newRoutes.push(routes[i]);
		}
	}
	return newRoutes;
}


function findRouteBounds(route)
{
	minLat = 90.0;
	maxLat = -90.0;
	minLng = 180.0;
	maxLng = -180.0;
	for (i in route['pts']){
		lat = route['pts'][i].lat();
		lng = route['pts'][i].lng();
		if (lat>maxLat) maxLat = lat;
		if (lng>maxLng) maxLng = lng;
		if (lat<minLat) minLat = lat;
		if (lng<minLng) minLng = lng;
	}
	//GLog.write('MaxLat:'+maxLat+'MinLat:'+minLat+'MaxLng:'+maxLng+'MinLng:'+minLng)
	r=  new GLatLngBounds(new GLatLng(minLat, minLng), new GLatLng(maxLat, maxLng));
	return r;
}
function centerRoute(map, route)
{
	if(route['pts'].length < 1){
		return;
	}
	routeBounds = findRouteBounds(route);
	maxZoom = map.getBoundsZoomLevel(routeBounds);
	if(map.getZoom()>maxZoom){
		map.setZoom(maxZoom);
	}
	mapBounds = map.getBounds();
	if(!mapBounds.containsBounds(routeBounds)){
		map.panTo(routeBounds.getCenter());
	}
}


function showRoute(map, routes, route, id)
{
	hideRoute(map, route)
	for(r in routes){
		if(routes[r]['id']==id){
			route = routes[r];
			redrawRoute(map, route);
			centerRoute(map, route);
			return route;
		}
	}
	
	return 0;
}

function prepareSubmit(route)
{
	r = {'name': route['name'], 'id':route['id']}
	if(route['id'] != 'new'){
		r['action'] = 'updateRoute'
	}else{
		r['action'] = 'addRoute'
	}
	for (i in route['pts']){
		r['lat_'+i] = route['pts'][i].lat(); 
		r['lng_'+i] = route['pts'][i].lng();
		if (typeof(route['pts'][i].note)!="undefined" &&
			route['pts'][i].note.length>0){
			r['note_'+i] = route['pts'][i].note;
		}
	}
	return r
}


