var http		= null;
var nocookies		= null;

function setInner(id,strTo)
{
$(id).innerHTML		= strTo;
}

function ajaxUpdater(dataUrl,targetid,nocache,debug)
{
updater		= function (http)
{
$(targetid).innerHTML		= http.responseText;
}
ajaxCall(dataUrl,updater,nocache,debug);
}

function ajaxCall(dataUrl,returnFunction,nocache,debug,returnVar,mode,params)
{

if (!mode)
{ var mode		= "GET"; }

//create a variable for handling requests to be reused
var http		= null;
//If nocache is passed, make each call unique
if (nocache != null && nocache == 1)
{
var dt		= new Date();
var dtString		= ''+dt.getFullYear()+dt.getMonth()+dt.getDate()+dt.getHours()+dt.getMinutes()+dt.getMilliseconds();
} 
if (debug != null && debug == 1 )
{
prompt('',dataUrl);};

//try to create the xmlHttpRequest object with non-IE code first, else fallback on IE
try
{
http		= new XMLHttpRequest(); // non-IE
}

catch (error)
{

try
{
http		= new ActiveXObject("Microsoft.XMLHTTP"); // IE
}

catch (error)
{
return false;
}

}

// more error checking
try
{
//open the http page
http.open(mode, dataUrl , true);

if (mode == "POST")
{
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(params);
}

}

catch (error)
{
alert('Page not found');
return false;
}

//upon a change of status of the request for the lookup page, call the javascript handler
http.onreadystatechange		= function()
{
//readystate of 4 means the request is complete
if (http.readyState == 4)
{
//status code of 200 means OK (regular status codes)
if (http.status != 200)
{
alert('Page not found');
return false;
}

else
{
returnFunction(http,returnVar);
}

}

}

//close the connection (very important for memory leaks)
if (mode != "POST")
{
http.send(null);
}

return false;
}

var lastError		= null;
var uname		= 'guest';

function processUpdate(http)
{

if (http.responseText.indexOf('OK') >= 0)
{
$('errMsg_profile').innerHTML		= 'Thanks for the update!';
}

else if (http.responseText.indexOf('Username Taken') >= 0)
{
$('errMsg_profile').innerHTML		= 'An account with that username already exists.';
}

else if (http.responseText.indexOf('Email Taken') >= 0)
{
$('errMsg_profile').innerHTML		= 'An account with that email address already exists.';
}

else if (http.responseText.indexOf('Bad Original Password') >= 0)
{
$('errMsg_profile').innerHTML		= 'Please confirm your original password to approve the changes.';
}

else
{
$('errMsg_profile').innerHTML		= 'An account with that email address already exists.';
}

}

var MILESASKM		= 1.609344;
var RUNNINGCAL		= 1.036;
var CYCLINGCAL		= 1.036;
var INLINECAL		= 1.036;
var icon			= null;
var iconfinish		= null;
var map				= null;
var geocoder		= new GClientGeocoder();
var baseIcon		= null;
var currentPoint	= null;
var userMove		= true;

varcurrentX			= null;
varcurrentY			= null;
varcurrentZoom		= 14;
var googleZoom		= 3;
var currentFile		= "";
var currentRouteId	= null;
var currentRouteName= null;
var currentRouteOwner= null;

//user prefs
var currentUnit		= "miles";
var currentSpeed	= 3.0;
var currentPace		= 10.0;
var currentWeight	= 190;
var minutesPerUnit	= 60 / currentSpeed;
var altUnit			= "km";
var currentSport	= "Walking";

var lastTab			= null;
var lastTabLabel	= null;
var lastSubTab		= null;
var lastSubTabLabel	= null;
var mileIcon		= new Array();
var baseSign		= null;
var recording		= false;

var route			= [];
var routeDistance	= 0;
var request			= null;
var env				= "http://www.dogside.com/";
var firstRequest	= true;
varfilterDist		= null;
var filterUnits		= null;
var training_wt		= null;

function RouteStatus()
{}
RouteStatus.prototype		= new GControl();

/*TODO: Might use graft to replace many of the dom creation items.*/

RouteStatus.prototype.initialize		= function(map)
{
var container		= document.createElement("div");

var statusDiv		= document.createElement("div");
statusDiv.id		= 'statusDiv';
this.setButtonStyle_(statusDiv);
container.appendChild(statusDiv);
statusDiv.appendChild(document.createTextNode("Dist"));
var distElm		= document.createElement("span");
distElm.id		= "currentDist";
distElm.style.padding		= "0 5px 0 5px";
distElm.appendChild(document.createTextNode("7 mi / 10 km"));
statusDiv.appendChild(distElm);
//statusDiv.appendChild(document.createElement("br"));

statusDiv.appendChild(document.createTextNode("Speed"));
var spdElm		= document.createElement("span");
spdElm.id		= "currentSpeed";
spdElm.style.padding		= "0 0 0 5px";
spdElm.appendChild(document.createTextNode("6.0 mph / 8 kmh"));
statusDiv.appendChild(spdElm);
var spdLink		= document.createElement("span");
spdLink.style.textDecoration		= "underline";
spdLink.style.color		= "blue";
spdLink.style.cursor		= "pointer";
spdLink.style.padding		= "0 0 0 3px";
spdLink.appendChild(document.createTextNode("change"));
GEvent.addDomListener(spdLink, "click", function()
{
modifySpeed();
//return false;
});
statusDiv.appendChild(spdLink);
statusDiv.appendChild(document.createElement("br"));

statusDiv.appendChild(document.createTextNode("Pace"));
var paceElm		= document.createElement("span");
paceElm.id		= "currentPace";
paceElm.style.padding		= "0 0 0 5px";
paceElm.appendChild(document.createTextNode("10.0 m/mile"));
statusDiv.appendChild(paceElm);
var paceLink		= document.createElement("span");
paceLink.style.textDecoration		= "underline";
paceLink.style.color		= "blue";
paceLink.style.cursor		= "pointer";
paceLink.style.padding		= "0 5px 0 5px";
paceLink.appendChild(document.createTextNode("change"));
GEvent.addDomListener(paceLink, "click", function()
{
modifyPace();
//return false;
});
statusDiv.appendChild(paceLink);

statusDiv.appendChild(document.createTextNode("Time"));
var tmElm		= document.createElement("span");
tmElm.id		= "currentTime";
tmElm.style.padding		= "0 0 0 5px";
tmElm.appendChild(document.createTextNode("0:59:03"));
statusDiv.appendChild(tmElm);
var tmLink		= document.createElement("span");
tmLink.style.textDecoration		= "underline";
tmLink.style.color		= "blue";
tmLink.style.cursor		= "pointer";
tmLink.style.padding		= "0 0 0 5px";
tmLink.appendChild(document.createTextNode("change"));
GEvent.addDomListener(tmLink, "click", function()
{
modifyTime();
//return false;
});
statusDiv.appendChild(tmLink);

statusDiv.appendChild(document.createElement("br"));
//statusDiv.appendChild(document.createTextNode(getSport()+" "));
var sptLink		= document.createElement("span");
sptLink.style.textDecoration		= "underline";
sptLink.style.color		= "blue";
sptLink.style.cursor		= "pointer";
sptLink.style.padding		= "0 5px 0 5px";
sptLink.appendChild(document.createTextNode(getSport()+""));
sptLink.id		= "sptSelectLink";
GEvent.addDomListener(sptLink, "click", function()
{
modifySport();
//return false;
});
statusDiv.appendChild(sptLink);
statusDiv.appendChild(document.createTextNode("Calories"));
var calElm		= document.createElement("span");
calElm.id		= "currentCal";
calElm.style.padding		= "0 0 0 5px";
calElm.appendChild(document.createTextNode("359"));
statusDiv.appendChild(calElm);
var wgtDiv		= document.createElement("span");
wgtDiv.id		= "currentWeight";
wgtDiv.style.padding		= "0 0 0 5px";
wgtDiv.appendChild(document.createTextNode("for "+currentWeight+ " pound person"));
statusDiv.appendChild(wgtDiv);
var wgtLink		= document.createElement("span");
wgtLink.style.textDecoration		= "underline";
wgtLink.style.color		= "blue";
wgtLink.style.cursor		= "pointer";
wgtLink.style.padding		= "0 0 0 5px";
wgtLink.appendChild(document.createTextNode("change"));

GEvent.addDomListener(wgtLink, "click", function()
{
modifyWeight();
//return false;
});
statusDiv.appendChild(wgtLink);

map.getContainer().appendChild(container);
return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
RouteStatus.prototype.getDefaultPosition		= function()
{
var mapWidth		= (map.getSize().width / 2)-150;
return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(mapWidth, 0));
}

// Sets the proper CSS for the given button element.
RouteStatus.prototype.setButtonStyle_		= function(button)
{
//button.style.textDecoration		= "underline";
//button.style.color		= "blue";
button.style.backgroundColor		= "white";
button.style.font		= "11px Arial";
button.style.border		= "1px solid black";
button.style.padding		= "2px";
button.style.marginBottom		= "3px";
button.style.textAlign		= "center";
button.style.width		= "340px";
//button.style.cursor		= "pointer";
button.style.display		= "none";
}


function RouteControls()
{
}
RouteControls.prototype		= new GControl();

RouteControls.prototype.initialize		= function(map)
{
var container		= document.createElement("div");

var controlsDiv		= document.createElement("div");
controlsDiv.id		= 'controlsDiv';
this.setButtonStyle_(controlsDiv);
container.appendChild(controlsDiv);

var createRouteLink		= createIconDOM ('',beginRecording,'Create a route','/images/icons/add.png','createRouteLink','controlEnabled');
var findRouteLink 		= createIconDOM ('',showRouteList,'Find a route','/images/icons/zoom.png','findRouteLink','controlEnabled');
var saveRouteLink 		= createIconDOM ('',saveCurrentRoute,'Save route','/images/icons/disk.png','saveRouteLink',currentRouteId?'controlEnabled':'controlDisabled');
var removeMarkerLink 		= createIconDOM ('',removeMarker,'Remove marker','/images/icons/bin_closed.gif','removeMarkerLink',currentRouteId?'controlEnabled':'controlDisabled');

controlsDiv.appendChild(createRouteLink);
controlsDiv.appendChild(findRouteLink);
controlsDiv.appendChild(saveRouteLink);
controlsDiv.appendChild(removeMarkerLink);
map.getContainer().appendChild(container);
return container;
}
RouteControls.prototype.getDefaultPosition		= function()
{
// var mapWidth		= (map.getSize().width / 2)-150;
return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 29));
// return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 0));
}

RouteControls.prototype.setButtonStyle_		= function(button)
{
/*button.style.backgroundColor		= "white";
button.style.font		= "12px Arial";
button.style.border		= "1px solid black";
button.style.padding		= "3px 0";
button.style.lineHeight		= "16px"
// button.style.margin		= "0 10px 0 0";
button.style.textAlign		= "center";
// button.style.width		= "310px";*/
}

function createIconHTML (href,onClick,title,imgSrc)
{
var commonText		= "<a href='"+href+"' onclick='"+onClick+"'><img src='"+imgSrc+"' title='"+title+"'></a>";
commonText += "<a href='"+href+"' onclick='"+onClick+"' title='"+title+"'>"+title+"</a><br />";
return commonText;
}

function createIconDOM (href,clck,title,imgSrc,linkid,linkClass)
{
var iconLink		= document.createElement("span");
iconLink.id		= linkid;

if (linkClass)
{
iconLink.className		= linkClass;
}

var beginRecordingIcon		= document.createElement("img");
beginRecordingIcon.src		= imgSrc;
beginRecordingIcon.align		= "absbottom";
iconLink.appendChild(beginRecordingIcon);
iconLink.appendChild(document.createTextNode(title));

GEvent.addDomListener(iconLink, "click", clck); 
return iconLink;
}

function toggleUnits()
{
currentUnit		= currentUnit == "miles" ? "km" : "miles";
setUnitCookie();
altUnit		= currentUnit == "miles" ? "km" : "miles";
currentSpeed		= altUnit == "miles" ? currentSpeed * MILESASKM : currentSpeed / MILESASKM;
setSpeedCookie();
minutesPerUnit		= 60 / currentSpeed;
drawRoute(route);
return false;
}

function modifySpeed()
{
var newSpeed		= prompt("Enter your new speed in "+currentUnit+" per hour");
try
{
parseFloat(newSpeed);
currentSpeed		= newSpeed;
minutesPerUnit		= 60/currentSpeed;
setSpeedCookie();
drawRoute(route);
return false;
}

catch (e)
{
alert("The speed you entered was not valid, reverting to old speed");
return false;
}

//alert('hold'+newSpeed);
return false;
}

function modifyPace()
{
var newPace		= prompt("Enter your new pace in minutes per "+currentUnit);
try
{
parseFloat(newPace);
currentSpeed		= 60/newPace;
minutesPerUnit		= newPace;
setSpeedCookie();
drawRoute(route);
return false;
}

catch (e)
{
alert("The pace you entered was not valid, reverting to old pace");
return false;
}

//alert('hold'+newSpeed);
return false;
}

function modifyTime()
{
var newTime		= prompt("Enter your duration in minutes");
try
{
parseFloat(newTime);
currentSpeed		= routeDistance/(newTime/60);
minutesPerUnit		= 60/currentSpeed;
setSpeedCookie();
drawRoute(route);
return false;
}

catch (e)
{
alert("The duration you entered was not valid, reverting to old time");
return false;
}

//alert('hold'+newSpeed);
return false;
}

function getSport()
{
return currentSport;
}

function getCalorieFactor()
{
return RUNNINGCAL;
}

function modifySport()
{
showForm(280,400);
}

function setSport()
{
var spt		= document.forms['prefForm'];
var user_input		= 'Running';
for (i=0;i<spt.sportSelector.length;i++)
{

if (spt.sportSelector[i].checked)
{
user_input		= spt.sportSelector[i].value;
}

}
document.getElementById('sptSelectLink').innerHTML		= user_input;
currentSport		= user_input;

switch (currentSport)
{
case 'Running':
}

//setSportCookie();
return false;
}

function modifyWeight()
{
var newWeight		= prompt("Enter your weight in pounds");
try
{
parseFloat(newWeight);
currentWeight		= newWeight;
setWeightCookie();

if (currentUnit == "miles")
{
$('currentCal').innerHTML		= fix((routeDistance*MILESASKM) * (currentWeight/2.2) * getCalorieFactor(),1);
}

else
{
$('currentCal').innerHTML		= fix(routeDistance * (currentWeight/2.2) * getCalorieFactor(),1);
}
$('currentWeight').innerHTML		= "based on " + currentWeight + " pound person " + getSport();
return false;
}

catch (e)
{
alert("The weight you entered was not valid, reverting to " + currentWeight + " pounds");
return false;
}

return false;
}

function mapLocByFraction (lat_factor,lng_factor)
{
var bnds		= map.getBounds();
var latlng		= 
new GLatLng(
lat_factor != undefined ? bnds.getNorthEast().lat() - ((bnds.getNorthEast().lat()-bnds.getSouthWest().lat())*(lat_factor)) : map.getCenter().lat(),
lng_factor != undefined ? bnds.getNorthEast().lng() - ((bnds.getNorthEast().lng()-bnds.getSouthWest().lng())*(lng_factor)) : map.getCenter().lng()
);
return latlng;
}

function addAddress()
{
userId		= null;
var stZip		= $('stZip').value;
findAddress(stZip);
return false;
}


function usePointFromPostcode(postcode, callbackFunction)
{
var localSearch = new GlocalSearch();
localSearch.setSearchCompleteCallback(null,

function()
{

if (localSearch.results[0])
{
var resultLat = localSearch.results[0].lat;
var resultLng = localSearch.results[0].lng;
var point = new GLatLng(resultLat,resultLng);
callbackFunction(point);
}

else
{
alert("Postcode not found!");
}

});
localSearch.execute(postcode + ", UK");
}

function findAddress(ad)
{

if ((ad == undefined) || (ad.length == 0))
{
alert('Please enter a postal/zip code or an address');
}

else
{
ad		= ad == "Address" ? "" : ad;
usePointFromPostcode(
ad,
function(point)
{

if (!point)
{
alert(ad + " not found: try a postal/zip code or city and country.");
}

else
{
map.setCenter(point, 13);
}

}
);
//var urchinURL		= "/ziplookupxml/?a="+ad;
}

}

function setWeightCookie()
{
createCookie("userWeight",currentWeight,100);
}

function getWeightCookie()
{
var userWeight		= readCookie("userWeight");

if(userWeight)
{

try
{
parseFloat(userWeight);
currentWeight		= userWeight;
return currentWeight;
}

catch (e)
{
currentWeight		= 190;
setWeightCookie();
return currentWeight;
}

}

}

function setLatCookie()
{
createCookie("lat",map.getCenter().lat(),100);
}

function setLongCookie()
{
createCookie("lg",map.getCenter().lng(),100);
}

function setZoomCookie()
{
googleZoom		= map.getZoom();
createCookie("zmlevel",17-googleZoom,100);
}

function setMapMode()
{
switch (map.getCurrentMapType().getName())
{
case 'Map' : createCookie("mode","normal",100);break;
case 'Satellite' : createCookie("mode","satellite",100);break;
case 'Hybrid' : createCookie("mode","hybrid",100);break;
default : break;
}

}

function getLatCookie()
{
var userLat		= readCookie("lat");

if(userLat)
{

try
{
currentLat		= parseFloat(userLat);
return currentLat;
}

catch (e)
{
currentLat		= '';
setLatCookie();
return currentLat;
}

}

}

function getLngCookie()
{
var userLng		= readCookie("lg");

if(userLng)
{

try
{
currentLng		= parseFloat(userLng);
return currentLng;
}

catch (e)
{
currentLng		= '';
setLngCookie();
return currentLng;
}

}

}

function getZmCookie()
{
var userZm		= readCookie("zmlevel");

if(userZm)
{

try
{
currentZm		= parseFloat(userZm);
return currentZm;
}

catch (e)
{
currentZm		= '';
setZoomCookie();
return currentZm;
}

}

}

function setUnitCookie()
{
createCookie("userUnit",currentUnit,100);
}

function getUnitCookie()
{
var userUnit		= readCookie("userUnit");

if(userUnit)
{

try
{
currentUnit		= userUnit;
altUnit		= currentUnit == "miles" ? "km" : "miles";
return currentUnit;
}

catch (e)
{
currentUnit		= "miles";
setUnitCookie();
return currentUnit;
}

}

}

function setSpeedCookie()
{
createCookie("userSpeed",currentSpeed,100);
}

function getSpeedCookie()
{
var userSpeed		= readCookie("userSpeed");

if(userSpeed)
{

try
{
parseFloat(userSpeed);
currentSpeed		= userSpeed;
minutesPerUnit		= 60 / currentSpeed;
return currentSpeed;
}

catch (e)
{
currentSpeed		= 3.0;
minutesPerUnit		= 60 / currentSpeed;
setSpeedCookie();
return currentSpeed;
}

}

}

function setPaceCookie()
{
createCookie("userPace",currentPace,100);
}

function getPaceCookie()
{
var userPace		= readCookie("userPace");

if(userPace)
{

try
{
parseFloat(userPace);
currentPace		= userPace;
minutesPerUnit		= currentPace;
return currentPace;
}

catch (e)
{
currentPace		= 10.0;
minutesPerUnit		= currentPace;
setPaceCookie();
return currentPace;
}

}

}

/* Cookie Functions courtesy of Quirksmode
http://www.quirksmode.org/js/cookies.html
*/
function createCookie(name,value,days)
{

if (days)
{
var date		= new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires		= "; expires="+date.toGMTString();
}

else var expires		= "";
document.cookie		= name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
var nameEQ		= name + "=";
var ca		= document.cookie.split(';');
for(var i=0;i < ca.length;i++)
{
var c		= ca[i];
while (c.charAt(0)==' ') c		= c.substring(1,c.length);

if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}

return null;
}

function initGMap(start_x,start_y,zoom,f,rid,dv,sdv,mode,un)
{
//training_wt		= new Walkthrough('popInForm','demoTitle','demoImage','demoCaption','demoPrev','demoNext');
setPanelSize();
getUnitCookie();
getWeightCookie();
getSpeedCookie();

var userLat		= getLatCookie();
var userLng		= getLngCookie();
var userZm		= getZmCookie();
/* if userLat & userLng & userZm set use them */
uname			=un;
currentFile			= f;

var baseIcon			= new GIcon();
baseIcon.iconSize		= new GSize(17, 17);
baseIcon.iconAnchor		= new GPoint(8, 17);
baseIcon.infoWindowAnchor= new GPoint(5, 1);

icon					= new GIcon(baseIcon);
icon.image				= "/images/general/mile_blank.png";

baseSign				= new GIcon();
baseSign.iconSize		= new GSize(18, 19);
baseSign.iconAnchor		= new GPoint(18, 19);
baseSign.infoWindowAnchor= new GPoint(15, 13);

WalkPointer				= new GIcon(baseSign);
WalkPointer.image		= "/images/general/pointer_walk.png";

InterestPointer			= new GIcon(baseSign);
InterestPointer.image	= "/images/general/pointer_interest.png";

startIcon				= new GIcon(baseIcon);
startIcon.image			= "/images/general/start.png";

for (i=1;i<31;i++)
{
mileIcon[i]				= new GIcon(baseIcon);
mileIcon[i].image		= "/images/general/mile_blank.png";
}

finishIcon				= new GIcon(baseIcon);
finishIcon.image		= "/images/general/finish.png";


map						= new GMap2($("map"),{draggingCursor: 'pointer' });

/* ADD MAP CONTROLS */
map.addControl(new GLargeMapControl());
//map.addControl(new GMapTypeControl());
map.addControl(new GScaleControl());
map.addControl(new RouteStatus());
//map.addControl(new RouteControls());
currentX				= start_x;
currentY				= start_y;

//added for gmap2 compatibility
currentZoom		= 17 - zoom;
map.setCenter(new GLatLng(start_y,start_x), currentZoom);


lastPoint				= null;
firstPoint				= null;
GEvent.addListener(map, "moveend", function()
{

if (userMove == false)
{
//mapEventTracker._trackEvent('Auto move map');
userMove		= true;
}

else
{

if (route.length == 0)
{
//mapEventTracker._trackEvent('Drag map');
//map.clearOverlays();
//setLatCookie();
//setLongCookie();
//setZoomCookie();
//setMapMode();
loadRoutes();
}

}

});

GEvent.addListener(map, "zoom", function()
{
//mapEventTracker._trackEvent('Zoomed map','generic zoom',map.getZoom());
setLatCookie();
setLongCookie();
setZoomCookie();
setMapMode();

if (route.length == 0)
{
map.clearOverlays();
loadRoutes();
}

else
{
drawRoute(route);
}

});
GEvent.addListener(map, 'click', function(overlay, point)
{

if (overlay)
{
//do nothing 
}

else if (point && recording)
{

if (route.length == 0)
{
startRoute(point);
}

else if (route[route.length-1].x != point.x && route[route.length-1].y != point.y)
{
route.push(point);
//This marks the route as saveable
//currentRouteId		= null;
drawRoute(route);
}
}

});

if (rid)
{
recording		= true;
loadRoute(rid);
currentRouteId		= rid;
}

else
{
loadRoutes(null,null);
}

/*if (messageSent)
{
map.openInfoWindowHtml (mapLocByFraction(2/3,0.5), messageSent);
messageSent		= null;
}*/

return false;
}

function reinitGMap()
{
/*window.location.href		= "/routes/route_list.php?lg="+map.getCenter().lng()+"&lat="+map.getCenter().lat()+"&zmlevel="+(17-map.getZoom());
return false;*/
}

function createMarker(point, mtext, icon,pointNum)
{

/*if (pointNum != undefined && pointNum > 0 )
{
var marker		= new GMarker(point,{draggable: true,icon:icon});
}

else
{*/
var marker		= new GMarker(point,{draggable: false,icon:icon});
/*}*/
var html		= "<div style='background:#fff;width:300px;'>" + mtext + "</div>";
GEvent.addListener(marker, "click", function()
{
currentPoint		= marker.getPoint();
map.setCenter(currentPoint, map.getZoom());
marker.openInfoWindowHtml(html);
});
/*TODO: fix this to prevent a has no properties message*/
GEvent.addListener(marker, "dragend", function()
{
currentPoint		= marker.getPoint();
map.setCenter(currentPoint, map.getZoom());
//marker.openInfoWindowHtml(html);
if (pointNum != undefined)
{
route[pointNum]		= currentPoint;
//map.removeOverlay(marker);
drawRoute(route);
}
});
GEvent.addListener(marker, "dragstart", function()
{
map.closeInfoWindow();
//map.removeOverlay(marker);
});

return marker;
}

function createRouteMarker(point, title, html, icon, rid, html2, routeNumber)
{
// var marker		= new GMarker(point,icon);
var latlng		= new GLatLng(point.y, point.x);
opts		= {
"icon": eval(icon),
"clickable": true,
"title": title,
"labelOffset": new GSize((routeNumber.length == 1 ? -3 : -5), -28)
};
var marker		= new LabeledMarker(latlng, opts);
var divhtml		= "<div style='background:#fff;'>" + html + "</div>";
GEvent.addListener(marker, "click", function()
{
//loadRoute(rid);
currentPoint		= marker.getPoint();
userMove		= false;

/*if (map.getZoom() > 13)
{ 
map.setCenter(currentPoint, map.getZoom());
map.panTo(currentPoint);
}

else
{
map.setCenter(currentPoint, 17 - 2);
}
*/

if (html2)
{
marker.openInfoWindowTabsHtml([new GInfoWindowTab('Overview',html), new GInfoWindowTab('Description',html2)]); 
}

else
{
marker.openInfoWindowHtml(divhtml);
}
});
return marker;
}

function createIconHTML (href,onClick,title,imgSrc)
{
var commonText		= "<a href='"+href+"' onclick='"+onClick+"'><img src='"+imgSrc+"' title='"+title+"'></a>&nbsp;";
commonText += "<a href='"+href+"' onclick='"+onClick+"' title='"+title+"'>"+title+"</a>";
return commonText;
}

function showForm(height,width)
{
var theForm		= $('popInForm');
theForm.className		= 'popShow';

if (height)
{ theForm.style.height		= height; }

if (width)
{ theForm.style.width		= width; }

var theBg		= $('popInForm_bg');
theBg.className		= 'popShow';
return false;
}

function popIn()
{
$('popInForm_bg').className		= 'popShow';
$('popInForm_bg').style.height		= (document.documentElement.clientHeight)+'px';
return false;
};

function hideForm()
{
$('popInForm').className		= 'popHide';
$('popInForm_bg').className		= 'popHide';
return false;
}

function showRouteList ()
{
}

function toggleTabs(tabName)
{

if (lastTab)
{
lastTab.className		= 'hiddenTab';
lastTabLabel		= $(lastTab.id+'_nav');
}

else
{
$('home').className		= 'hiddenTab';
lastTabLabel		= $('home_nav');
}

if (lastTabLabel)
{
lastTabLabel.className		= 'tablabel';
}

var urchinURL		= "/toggleTabs/"+tabName;

if (tabName != 'routes')
{
ajaxCall('/showTab.php?t='+tabName,showTab,1,0,tabName);
}

else
{
showTab(null,tabName);
}

return false;
}

function showTab(http,tgt)
{
lastTab		= $(tgt);

if (http != null)
{
lastTab.innerHTML		= http.responseText;
}
lastTab.className		= 'visibleTab';
lastTabLabel		= $(lastTab.id+'_nav');

if (lastTabLabel)
{
lastTabLabel.className		= 'tablabelHi';
}

return false;
}

function beginRecording()
{
recording		= true;
map.clearOverlays();
route		= [];
routeDistance		= 0;
currentRouteId		= null;
/*$('controlsDiv').innerHTML		= 'Begin recording';*/
//var saveButton		= $('saveRouteLink');
//saveButton.className		= 'controlEnabled';
//var removeMarkerButton		= $('removeMarkerLink');
//removeMarkerButton.className		= 'controlEnabled';
//$('rName').innerHTML		= 'New';
//$('routeResults2').innerHTML		= '';
//return false;
}

function startRoute(point)
{
route.push(point);
currentRouteId		= null;
drawRoute(route);
}

function loadRoute(rid)
{
ajaxCall("/routes/fetchRoute.php?rid="+rid,showRoute,1,0,rid);
}

function claimRoute(rid)
{
var dataUrl		= '/routes/claimRoute.php?rid='+rid;
var urchinURL	= "/account/claimRoute";

//perform ajax call
ajaxCall(dataUrl,displayClaimResult,1,0);
var wl		= $('login_container');
//toggleTabs('account');
popIn();
showForm(100);
$('popUpContent').innerHTML		= 'Processing your claim';
//$('errMsg').className		= 'error';
return false;
}

//display the page content
function displayClaimResult(http)
{
//readystate of 4 means the request is complete
if (http.readyState == 4)
{
//status code of 200 means OK (regular status codes)
if (http.status != 200)
{
alert("page not found"+http.status);
return false;
}

else
{

if (http.responseText.indexOf('OK') >= 0)
{
$('popUpContent').innerHTML		= '<h1>Route claimed successfully</h1><br /><p>It will now appear in your list of routes.</p>';
//$('errMsg').className		= 'error';
lastError		= null;
}

else if (http.responseText.indexOf('Your route') >=0)
{
$('popUpContent').innerHTML		= '<h1>This is your route!</h1><br /><p>You can\'t claim a route you already own.</p>';
//$('errMsg').className		= 'error';
lastError		= null;
}

else if (http.responseText.indexOf('Already claimed') >=0)
{
$('popUpContent').innerHTML		= '<h1>This route has already been claimed by someone.</h1><br /><p>If you believe you created this route please email me at support@dogside.com.</p>';
//$('errMsg').className		= 'error';
lastError		= null;
}

else if (http.responseText.indexOf('No user')>=0)
{
$('popUpContent').innerHTML		= '<h1>You must be logged in to claim a route.</h1><br /><p>Please log in or create a new account.</p>';
//$('errMsg').className		= 'error';

}

}

}

}

function setRouteOwner(http)
{
currentRouteOwner		= http.responseText.split(' ');
currentRouteOwner		= currentRouteOwner[1];
}

function showRoute(http,rid)
{
var xmlDoc				= http.responseXML;
var markers				= xmlDoc.documentElement.getElementsByTagName("marker");
var newRoute			= [];

for (var i = 0; i < markers.length; i++)
{
var point				= new GPoint(parseFloat(markers[i].getAttribute("lng")), parseFloat(markers[i].getAttribute("lat")));
newRoute.push(point);
}

route=newRoute;
map.clearOverlays();
map.setCenter(new GLatLng(route[0].y,route[0].x), 14);
currentRouteId		= rid;
drawRoute(newRoute);
return false;
}
/*TODO: absolutely must use graft instead of this code*/
function processRouteList(request)
{
var xmlDoc		= request.responseXML;
var markers		= xmlDoc.documentElement.getElementsByTagName("marker");
var markerDoc		= xmlDoc.documentElement;
/* TODO: Zoom map to cover all markers */
//Create routelist
if (!firstRequest)
{
}

else
{
firstRequest		= false;
}


for (var i		= 0; i < markers.length; i++)
{
var point		= new GPoint(parseFloat(markers[i].getAttribute("lng")),
           parseFloat(markers[i].getAttribute("lat")));
//allPoints.push(point);
var routeId		= markers[i].getAttribute("rid");
var routeTitle	= markers[i].getAttribute("desc");
var html		= "<div style='width:300px;'>";
html			+= "<p>"+ routeTitle;

/*var submittedBy		= markers[i].getAttribute("submit_by");
if (submittedBy == 'guest')
{
html			+= "<p>"+ routeTitle +" by a "+ submittedBy +" &nbsp;&nbsp;(&nbsp;<a href='"+currentFile+"?rid="+routeId+"' onclick='return claimRoute(\""+routeId+"\");' title='Claim this route as yours.'>claim this route</a>&nbsp;)<br />";
}

else
{
html			+= "<p>"+ routeTitle +" by <a href='"+currentFile+"?u="+submittedBy+"' title='View more routes by "+ submittedBy +"'>"+ submittedBy +"</a><br />";
}*/

html			+= "<br>";

if (fix(markers[i].getAttribute("dist"),2) > 0)
{
html			+= "Distance: "+ fix(markers[i].getAttribute("dist"),2) +" miles";
}

if (fix(markers[i].getAttribute("points"),2) > 1)
{
html			+= "&nbsp;<a href=\"javascript:loadRoute('"+routeId+"')\" title='View the route details.'>View</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
}

/*html			+= "&nbsp;<a title='Request that this route be deleted.' onclick='return removeRoute(\""+routeId+"\");' href='mailto:support@dogside.com?subject=Bad route&body=Route "+ routeId +"'>Delete</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";*/

var uId		= markers[i].getAttribute("submit_by");

var rli		= document.createElement("li");

if (i % 2 == 0)
{
rli.className		= 'stripe clearfix';
}

else
{
rli.className		= 'nostripe clearfix';
}

rli.innerHTML 		= '<a class="rtMrk" href="/'+currentFile+'?rid='+routeId+'" title="View Route"><div class="LabeledMarker_markerLabel">'+routeId+'</div></a>';

var rtDets		= document.createElement("div");
rtDets.className		= 'rtDetails';
rtDets.innerHTML += '<a class="rtName" href="/'+currentFile+'?rid='+routeId+'" title="View Route">'+routeTitle+'</a>';
rtDets.innerHTML += '&nbsp;('+ fix(markers[i].getAttribute("dist"),2) + ' miles';

var rtCreator		= '';

if (uId != 'guest')
{
rtCreator		= '<a href="/'+currentFile+"?u="+uId+'">' + uId + '</a>'
}

else
{
rtCreator		= 'guest';
}

var routeOptions		= "";

if (routeId)
{
routeOptions += "<a href='"+currentFile+"?rid="+routeId+"' onclick='return bookmarkRoute();'>Bookmark</a>&nbsp;";
routeOptions += "<a onclick='return removeRoute(\""+routeId+"\");' href='mailto:support@dogside.com?subject=Bad route&body=Route "+ routeId +"'>Delete</a>";

rtDets.innerHTML += routeOptions;
}
rli.appendChild(rtDets);

Pointer			= "";

if (fix(markers[i].getAttribute("points"),2) > 1)
{
Pointer			= "WalkPointer";	
}

else
{
Pointer			= "InterestPointer";	
}

var marker		= createRouteMarker(point,routeTitle,html,Pointer,routeId,"","");
map.addOverlay(marker);
}

}

function searchRoutes(term)
{
findAddress(term);
return false;
}

function routesByDist(dist,units)
{

if (dist != undefined && units != undefined && units.length >= 0)
{

if (dist != 0)
{
filterDist		= dist;
filterUnits		= units;
$('filterApplied').className		= "error popShow";
$('filterApplied').innerHTML		= "Filter applied: showing "+dist+" "+units+" routes";
}

else
{
filterDist		= null;
filterUnits		= null;
$('filterApplied').className		= "popHide";
$('filterApplied').innerHTML		= "Filter applied: showing "+dist+" "+units+" routes";
}

map.clearOverlays();
loadRoutes();
}

else
{
alert('Distance should be a number and units should be miles or km');
}

return false;
}

function loadRoutes()
{
var boundsSW		= map.getBounds().getSouthWest();
var boundsNE		= map.getBounds().getNorthEast();
googleZoom		= map.getZoom();

if ((googleZoom >= 12) && (!isNaN(boundsSW.lng())) && (!isNaN(boundsSW.lat())) && (!isNaN(boundsNE.lng())) && (!isNaN(boundsNE.lat())))
{
var routeListURL		= "/routes/getRoutes.php";
ajaxCall(routeListURL,processRouteList,1,0);
}

else if (googleZoom < 12)
{
//do nothing yet
}

else
{
alert('There appears to be a problem retrieving this map - please email support@dogside.com with a screenshot so we can try to fix it.');
}

return false;
}

function goHome()
{

if (route.length > 1)
{
for (var i=route.length-2;i >= 0 ;i--)
{
route.push(route[i]);
}
map.clearOverlays();
var ctr		= new GLatLng(route[route.length-1].y,route[route.length-1].x);
map.setCenter(ctr,map.getZoom());
drawRoute(route);
}

return false;
}

function removeMarker ()
{

if (currentRouteId || route.length != 0)
{
var oldPoint		= route[route.length-1];
modifyPoint(oldPoint,null);
}

else
{
alert('You must be working with a route to remove a marker');
}

}

function modifyPoint (oldPoint,newPoint)
{
var newRoute		= [];
var rt		= route;
for (var i=0;i <= rt.length-1;i++)
{

if (oldPoint.x == rt[i].x && oldPoint.y == rt[i].y)
{

if (newPoint)
{
newRoute.push(newPoint);
}

}

else
{
newRoute.push(rt[i]);
}

}
route		= newRoute;
drawRoute(route);
return false;
}

function routeSave()
{
var un		= $('rtu');
un.value		= uname;

if (route.length == 0)
{
alert('You must add points to a route before you can save it');
}

else
{
var routeListURL		= "/routes/saveRoute.php";
routeListURL			+= "?ds=" + document.getElementById("ds").value;
//routeListURL			+= "&u=" + document.getElementById("u").value;
routeListURL			+= "&d=" + document.getElementById("d").value;
routeListURL			+= "&pl=" + document.getElementById("pl").value;
map.clearOverlays();
ajaxCall(routeListURL,loadRoutes,1,0);	
}

}

function saveCurrentRoute()
{

if (currentRouteId || route.length != 0)
{
saveRoute(currentRouteId);
}

else
{
alert('You must be working with a route to save it');
}

}

function saveRoute(rid)
{
var html		= "<strong>Save Your Route</strong><br />";
//html			+= "<p>You can only save changes to a route if you are logged in.<br /> If you are not logged in, you can only save it as a new route.</p>";
html			+= "<i>Enter a name for your route.</i>";
html			+= "<form action='javascript:routeSave()' method='post'>";

var currName	= $('rName');
var currDesc	= $('rDesc');

if (currName)
{
html			+= "<input name='ds' id='ds' value='"+currName.innerHTML+"'><br />";
}

else
{
html			+= "<input name='ds' id='ds' value=''><br />";
}

html			+= "<input type='hidden' name='u' id='rtu' value='guest'>";

html			+= "<input type='hidden' name='d' id='d' value='"+(currentUnit == "miles" ? fix(routeDistance,1) : fix((routeDistance/MILESASKM),1))+"'>";
html			+= "<input type='hidden' name='dkm' value='"+(currentUnit == "km" ? fix(routeDistance,1) : fix((routeDistance*MILESASKM),1))+"'>";
var qryString		= "";
for (var i=0;i <= route.length-1;i++)
{
qryString += route[i].x + "," + route[i].y + ":";
}
html			+= "<input type='hidden' name='pl' id='pl' value='"+qryString+"'>";

html			+= "<input type=\"submit\" value=\"Save Route\" />";
html			+= "</form>";
map.openInfoWindowHtml (mapLocByFraction(2/3,0.5), html);
return false;
}

function removeRoute(rid)
{

if (!confirm('Are you sure you want to delete this route?'))
{
return false;
}

var dataUrl		= '/routes/deleteRoute.php?r='+rid;

//perform ajax call
ajaxCall(dataUrl,deleteRoute,1,0,rid);
return false;
}

function deleteRoute(http,rid)
{

if (http.responseText.indexOf('OK') >= 0)
{
var html		= "<strong>Delete this route</strong><br />";
html			+= "Thank you for helping keep WalkJogRun.net tidy!<br />";
html			+= "Your route has been removed.";
map.clearOverlays();
loadRoutes();
map.openInfoWindowHtml (mapLocByFraction(2/3,0.5), html);
}

else
{
var html		= "<strong>Delete this route</strong><br />";
html			+= "Thank you for helping keep WalkJogRun.net tidy!<br />";
html			+= "Requests to delete routes are instant if you are logged in.<br />";
html			+= "You may only delete routes you created.<br />";
html			+= "Click <a href=\"\" onclick=\"toggleTabs('account');return toggleLogin('account_create');\">here</a> to create an account<br />";
html			+= "Click <a href=\"\" onclick=\"toggleTabs('account');return toggleLogin('account_login');\">here</a> to login if you already have one.<br /><br />";
html			+= "A copy of your message will be mailed to your address";
html			+= "<form action='/routes/suggestRouteDelete.php' method='post'>";
html			+= "<em>Your E-mail address:</em><br /><input type='text' name='fromAddr' value=''><br />";
html			+= "<em>Reason for deletion:</em> &nbsp;<br /><textarea name='message'></textarea><br />";
html			+= "<input type='hidden' name='routeId' value='"+rid+"'><br />";html			+= "<input type='submit' value='Send'><br />";
html			+= "</form>";
map.openInfoWindowHtml (mapLocByFraction(0.75,0.5), html);
}

return false;
}
/*TODO: Must use graft for building elements and also 
- does draw route need to get called for each new point?*/
function drawRoute(rt)
{
map.clearOverlays();
//var saveButton		= $('saveRouteLink');
//saveButton.className		= 'controlEnabled';
var distThisLeg		= 0;
var totDistance		= 0;
var markerText		= "";
var startOverlay		= null;
//var routeList2Div		= $('routeResults2');
//routeList2Div.innerHTML		= "";
var newTable		= document.createElement('table');
var newBody		= document.createElement('tBody');
newTable.appendChild(newBody);
newTable.border		= '0';
newTable.cellSpacing		= '0';
newTable.width		= '100%';
//create holders
var r 		= document.createElement('tr');
var cn		= document.createElement('th');
var ca		= document.createElement('th');
ca.colSpan		= "2";
var cb;
var cc		= document.createElement('th');
cc.colSpan		= "2";
var cd;
//create contents
var tn		= document.createTextNode(' ');
var ta		= document.createTextNode('This Leg');
var tb;
var tc		= document.createTextNode('Total');
var td;
//add contents to holders
cn.appendChild(tn);
ca.appendChild(ta);
cc.appendChild(tc);
//add cells to row
r.appendChild(cn);
r.appendChild(ca);
r.appendChild(cc);
newBody.appendChild(r);

var r2 		= document.createElement('tr');
tn		= document.createTextNode('Turn #');
ta		= document.createTextNode('Dist');
tb		= document.createTextNode('Time');
tc		= document.createTextNode('Dist');
td		= document.createTextNode('Time');
//create holders
r 		= document.createElement('tr');
cn		= document.createElement('th');
ca		= document.createElement('th');
cb		= document.createElement('th');
cc		= document.createElement('th');
cd		= document.createElement('th');
//add contents to holders
cn.appendChild(tn);
ca.appendChild(ta);
cb.appendChild(tb);
cc.appendChild(tc);
cd.appendChild(td);
//add cells to row
r2.appendChild(cn);
r2.appendChild(ca);
r2.appendChild(cb);
r2.appendChild(cc);
r2.appendChild(cd);
var routeInfoFooter		= "";

if (currentRouteId)
{
routeInfoFooter += createIconHTML('','return saveRoute(currentRouteId);','Save','/images/icons/disk.gif');
routeInfoFooter += "&nbsp;&nbsp;";
routeInfoFooter += createIconHTML('','return claimRoute(currentRouteId);','Claim','/images/icons/add.gif');
routeInfoFooter += createIconHTML('mailto:support@dogside.com?subject=Bad route&body=Route "+ currentRouteId +"','return removeRoute(currentRouteId);','Delete Route','/images/icons/bin_closed.gif');
}

else
{
routeInfoFooter += createIconHTML('','return saveRoute();','Save','/images/icons/disk.gif');
}
routeInfoFooter += "<br />";
var footer		= document.createElement('div');
footer.innerHTML		= routeInfoFooter;
//routeList2Div.appendChild(footer);

newBody.appendChild(r2);

var mileNum		= 1;
for (var i=0;i <= rt.length-1;i++)
{

if (i==0)
{
//do nothing yet
}

else
{

distThisLeg		= calcDist(rt[i].x,rt[i].y,rt[i-1].x,rt[i-1].y);
totDistance		= distThisLeg + totDistance;
//create holders
var r 		= document.createElement('tr');

if (i % 2 == 1)
{
r.className		= 'stripe';
}

else
{
r.className		= 'nostripe';
}

var cn		= document.createElement('td');
var ca		= document.createElement('td');
var cb		= document.createElement('td');
var cc		= document.createElement('td');
var cd		= document.createElement('td');
//create contents
var tn		= document.createTextNode(i);
var ta		= document.createTextNode(fix(totDistance,2)+ " " + currentUnit);
var tc		= document.createTextNode(getFixTime(totDistance));
var tb		= document.createTextNode(fix(distThisLeg,2)+ " " + currentUnit);
var td		= document.createTextNode(getFixTime(distThisLeg));
//add contents to holders
cn.appendChild(tn);
ca.appendChild(tb);
cb.appendChild(td);
cc.appendChild(ta);
cd.appendChild(tc);
//add cells to row
r.appendChild(cn);
r.appendChild(ca);
r.appendChild(cb);
r.appendChild(cc);
r.appendChild(cd);

newBody.appendChild(r);
//routeList2Div.appendChild(newTable);

var commonTitle		= fix(totDistance,2) + " " + currentUnit;
var commonText		=  "<p>Time " + getFixTime(totDistance) + " &nbsp;&nbsp;&nbsp;";

commonText += createIconHTML('','return modifyPoint(currentPoint,null);','Remove marker','/images/icons/bin_closed.gif');
commonText += "</p>"

if (currentRouteId)
{
commonText += createIconHTML('','return saveRoute(\""+currentRouteId+"\");','Save Route','/images/icons/disk.gif');
}

else
{
commonText += createIconHTML('','return saveRoute();','Save Route','/images/icons/disk.gif');
}
commonText += "&nbsp;&nbsp;";

if (i ==rt.length-1 && rt.length > 1)
{
commonText += createIconHTML('','return goHome();','Return to start','/images/icons/house_go.gif');
//commonText += "&nbsp;&nbsp;";
}

if (i == rt.length-1)
{
markerText		= "<h3><img src='/images/finish.png' title='Finish'>Finish " + commonTitle + "</h3>" + commonText;
map.addOverlay(createMarker(rt[i],markerText,finishIcon,i));
}

else
{
markerText		= "<strong>Marker number " + i + "</strong><br />" + commonText;
//map.addOverlay(createMarker(rt[i],markerText,base_marker,i));
}

var vectorX		= (rt[i].x - rt[i-1].x) / distThisLeg;
var vectorY		= (rt[i].y - rt[i-1].y) / distThisLeg;
var stpoint		= new GPoint(rt[i-1].x,rt[i-1].y);
var stDist		= totDistance-distThisLeg;
for (stDist; stDist <= totDistance; )
{
var distToNextMile		= Math.floor(stDist+1.0)-stDist;
stpoint.x		= stpoint.x+(vectorX*distToNextMile);
stpoint.y		= stpoint.y+(vectorY*distToNextMile);

if (Math.ceil(stDist+0.000001) <= Math.floor(totDistance))
{
var marker		= new GMarker(stpoint,mileIcon[mileNum]);
map.addOverlay(marker);
mileNum=mileNum+1;
}
stDist=stDist+distToNextMile;

}

var points		= [];
points.push(rt[i]);
points.push(rt[i-1]);
points.sort(function(p1,p2)
{ return p1.x - p2.x });
map.addOverlay(new GPolyline(points));
/*if (messageSent)
{
map.openInfoWindowHtml (mapLocByFraction(2/3,0.5), messageSent);
messageSent		= null;
}*/
}

}
routeDistance		= totDistance;
markerText		= "<h3><img src='/images/general/start.png' title='Start'>Start " + commonTitle + "</h3>";
$('statusDiv').style.display		= "block";
var totDist		= fix(routeDistance,2);
$('currentDist').innerHTML		= totDist + " <a href='' onclick='return toggleUnits()'>" + currentUnit + "</a>";
$('currentTime').innerHTML		= getFixTime(totDist);

if (currentUnit == "miles")
{
$('currentSpeed').innerHTML		= fix(currentSpeed,1) + " mph";
$('currentPace').innerHTML		= fix(minutesPerUnit,1) + " mins per mile";
$('currentCal').innerHTML		= fix((totDist*MILESASKM) * (currentWeight/2.2) * getCalorieFactor(),1);
}

else
{
$('currentSpeed').innerHTML		= fix(currentSpeed,1) + " km/h ";
$('currentPace').innerHTML		= fix(minutesPerUnit,1) + " mins per km";
$('currentCal').innerHTML		= fix(totDist * (currentWeight/2.2) * getCalorieFactor(),1);
}
markerText += "<a href='' onclick='return toggleUnits();'>Switch to "+altUnit+"</a><br /><br />";
startOverlay		= createMarker(rt[0],markerText,startIcon);
map.addOverlay(startOverlay);

return false;
}

function resetMap()
{

if (confirm("Return to route list without saving?"))
{
map.clearOverlays();
loadRoutes();
}

}


function bookmarkRoute()
{
alert("To bookmark this route, right click on the bookmark link and select 'Add to Favorites'");
return false;
}

function $(id)
{
return document.getElementById(id)
}

function RTrim(VALUE)
{
var w_space		= String.fromCharCode(32);
var v_length		= VALUE.length;
var strTemp		= "";

if(v_length < 0)
{
return"";
}

var iTemp		= v_length -1;

while(iTemp > -1)
{

if(VALUE.charAt(iTemp) == w_space)
{
}

else
{
strTemp		= VALUE.substring(0,iTemp +1);
break;
}
iTemp		= iTemp-1;

}

//End While
return strTemp;

}

//End Function

function LTrim(VALUE)
{
var w_space		= String.fromCharCode(32);

if(v_length < 1)
{
return"";
}

var v_length		= VALUE.length;
var strTemp		= "";

var iTemp		= 0;

while(iTemp < v_length)
{

if(VALUE.charAt(iTemp) == w_space)
{
}

else
{
strTemp		= VALUE.substring(iTemp,v_length);
break;
}
iTemp		= iTemp + 1;
}

//End While
return strTemp;
}

//End Function
function Trim(TRIM_VALUE)
{

if(TRIM_VALUE.length < 1)
{
return"";
}
TRIM_VALUE		= RTrim(TRIM_VALUE);
TRIM_VALUE		= LTrim(TRIM_VALUE);

if(TRIM_VALUE=="")
{
return "";
}

else
{
return TRIM_VALUE;
}

}

//End Function
function calcDist(lon1,lat1,lon2,lat2) 
{
var r		= 3963.0;
var multiplier		= currentUnit == "miles" ? 1 : MILESASKM;
return multiplier * r * Math.acos(Math.sin(lat1/57.2958) * Math.sin(lat2/57.2958) + Math.cos(lat1/57.2958) * Math.cos(lat2/57.2958) * Math.cos(lon2/57.2958 - lon1/57.2958));
}

function getFixTime(dist)
{
var minutes		= dist * minutesPerUnit;
var hours		= Math.floor(minutes/60);
var remMins		= '' + Math.round(minutes - (hours*60));
var displayMins		= remMins.length == 2 ? remMins : "0"+remMins;
return hours + ":" + displayMins;
}

function fix(num,dp)
{
return Math.floor(num * Math.pow(10,dp)) / Math.pow(10,dp)
}

function checkLen(obj,msg)
{

if (!obj.value.length || obj.value == msg)
{
obj.className		= "dataOmitted";
obj.value		= msg;
}

else
{
obj.className		= "dataEntered";
}

}

function setPanelSize()
{
var myWidth		= 0, myHeight		= 0;

if( typeof( window.innerWidth ) == 'number' )
{
//Non-IE
myWidth		= window.innerWidth;
myHeight		= window.innerHeight;
}

else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
{
//IE 6+ in 'standards compliant mode'
myWidth		= document.documentElement.clientWidth;
myHeight		= document.documentElement.clientHeight;
}

else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
{
//IE 4 compatible
myWidth		= document.body.clientWidth;
myHeight		= document.body.clientHeight;
}

}

function LabeledMarker(a,b)
{this.latlng_=a;this.opts_=b;this.labelText_=b.labelText||"";this.labelClass_=b.labelClass||"LabeledMarker_markerLabel";this.labelOffset_=b.labelOffset||new GSize(0,0);this.clickable_=b.clickable||true;this.title_=b.title||"";this.labelVisibility_=true;if(b.draggable)
{b.draggable=false}GMarker.apply(this,arguments)}
LabeledMarker.prototype=new GMarker(new GLatLng(0,0));
LabeledMarker.prototype.initialize=function(c)
{GMarker.prototype.initialize.apply(this,arguments);this.map_=c;this.div_=document.createElement("div");this.div_.className=this.labelClass_;this.div_.innerHTML=this.labelText_;this.div_.style.position="absolute";this.div_.style.cursor="pointer";this.div_.title=this.title_;c.getPane(G_MAP_MARKER_PANE).appendChild(this.div_);if(this.clickable_)
{function newEventPassthru(a,b)
{return function()
{GEvent.trigger(a,b)}}var d=['click','dblclick','mousedown','mouseup','mouseover','mouseout'];for(var i=0;i<d.length;i++)
{var e=d[i];GEvent.addDomListener(this.div_,e,newEventPassthru(this,e))}}}
LabeledMarker.prototype.redraw=function(a)
{GMarker.prototype.redraw.apply(this,arguments);var p=this.map_.fromLatLngToDivPixel(this.latlng_);var z=GOverlay.getZIndex(this.latlng_.lat());this.div_.style.left=(p.x+this.labelOffset_.width)+"px";this.div_.style.top=(p.y+this.labelOffset_.height)+"px";this.div_.style.zIndex=z}
LabeledMarker.prototype.remove=function()
{GEvent.clearInstanceListeners(this.div_);if(this.div_.outerHTML)
{this.div_.outerHTML=""}if(this.div_.parentNode)
{this.div_.parentNode.removeChild(this.div_);}this.div_=null;GMarker.prototype.remove.apply(this,arguments)}
LabeledMarker.prototype.copy=function()
{return new LabeledMarker(this.latlng_,this.opt_opts_)}
LabeledMarker.prototype.show=function()
{GMarker.prototype.show.apply(this,arguments);if(this.labelVisibility_)
{this.showLabel()}else
{this.hideLabel()}}
LabeledMarker.prototype.hide=function()
{GMarker.prototype.hide.apply(this,arguments);this.hideLabel()}
LabeledMarker.prototype.setLabelVisibility=function(a)
{this.labelVisibility_=a;if(!this.isHidden())
{if(this.labelVisibility_)
{this.showLabel()}else
{this.hideLabel()}}}
LabeledMarker.prototype.getLabelVisibility=function()
{return this.labelVisibility_}
LabeledMarker.prototype.hideLabel=function()
{this.div_.style.visibility='hidden'}
LabeledMarker.prototype.showLabel=function()
{this.div_.style.visibility='visible'}
