﻿// JScript File


function CalcArrow(heading)
{
    var normalized = heading % 360;
    if (normalized < 0) normalized = 360 + normalized;
    var dir = Math.round(normalized / 3) * 3;
    arrow = 'Arrow/Arrow' + PadDigits(dir, 3) + '.png';
    return arrow;
}



function FormatTime(time)
{
   var hh = time.Hours + "";
   if (hh.length == 1) hh = "0" + hh;
   
   var mm = time.Minutes + "";
    if (mm .length == 1) mm  = "0" + mm ;
  
   var ss = time.Seconds+ "";
    if (ss.length == 1) ss = "0" + ss;
  
   return hh + ":" + mm + ":" + ss;
}

function FormatDateTime(time)
{
   var hh = time.getHours() + "";
   if (hh.length == 1) hh = "0" + hh;
   
   var mm = time.getMinutes() + "";
    if (mm .length == 1) mm  = "0" + mm ;
  
   var ss = time.getSeconds()+ "";
    if (ss.length == 1) ss = "0" + ss;
  
   return hh + ":" + mm + ":" + ss;
}

function SetIntervalStatus(distance)
{
   if (globalMetricUnits && distance < 1)
      window.status = "Interval dist:" + (distance * 1000).toFixed(0) + "m";
   else if (globalMetricUnits)
      window.status = "Interval dist:" + distance.toFixed(2) + "km";
   else
      window.status = "Interval dist:" + KilosToMiles(distance).toFixed(2) + "mi";
}

function SetWaypointStatus(waypoint)
{
    if (waypoint == null) 
    {
       window.status = "";
       return;
    }
    
    // update the window status - Web browser must be set to allow this
    var alt = "";
    if (waypoint.Altitude != UNKNOWN_ALTITUDE_KM)
       if (globalMetricUnits)
          alt = ' Alt:' + KilosToMeters(waypoint.AltitudeKM).toFixed(0) + 'm';
       else
          alt = ' Alt:' + KilosToFeet(waypoint.AltitudeKM).toFixed(0) + 'ft';
 
    var status = 'Time:' + waypoint.Timestamp.getFullYear() + "." +  (waypoint.Timestamp.getMonth()+1) + "." + waypoint.Timestamp.getDate() + "." +  FormatDateTime(waypoint.Timestamp);   
    
    if (globalMetricUnits)
    {
       if (waypoint.ElapsedDistanceKM > 1)
          status += ' Dist:' + waypoint.ElapsedDistanceKM.toFixed(2) +'km';
       else
          status += ' Dist:' + (waypoint.ElapsedDistanceKM * 1000).toFixed(0) +'m';
    }
    else
       status += ' Dist:' + KilosToMiles(waypoint.ElapsedDistanceKM).toFixed(2) +'mi';
       
    if(waypoint.Heading >= 0)
       status += ' Head: ' + waypoint.Heading.toFixed(0);
    
    status += ' Lat:' + waypoint.Latitude.toFixed(5) + ' Lon:' + waypoint.Longitude.toFixed(5) + alt ;
    
    if ( waypoint.TextDescription )
       status += ' Desc:' + waypoint.TextDescription  
   
     window.status = status;
}

function WebServiceError(fault,context,name) {
   CompleteWebRequest();
   alert('Error on '+ name==null?"":name + ' Web request:\n' + (fault==null?"":fault.get_message())); 
} 
    
// function setBodyHeightToContentHeight() {
//        document.body.style.height = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight)+"px";
//        document.body.style.width = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth)+"px";
//    }
//   
    
function GetWindowWidth(){var width=0;if(typeof(window.innerWidth)=='number'){width=window.innerWidth;}else if(document.documentElement&&document.documentElement.clientWidth){width=document.documentElement.clientWidth;}else if(document.body&&document.body.clientWidth){width=document.body.clientWidth;}if(!width||width<100){width=100;}return width;}
function GetWindowHeight(){var height=0;if(typeof(window.innerHeight)=='number'){height=window.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){height=document.documentElement.clientHeight;}else if(document.body&&document.body.clientHeight){height=document.body.clientHeight;}if(!height||height<100){height=100;}return height;}

function KilosToMeters(kilos) { return kilos * 1000; }
function MetersToKilos(meters) { return meters / 1000; }
function KilosToFeet(kilos) { return kilos * 3280.8399; }
function MetersToFeet(meters) { return meters * 3.2808399; }
function FeetToKilos(feet) { return feet / 3280.8399; }
function FeetToMeters(feet) { return feet / 3.2808399; }
function KilosToMiles(kilos) { return kilos * 0.621371192; }
function MilesToKilos(miles) { return miles / 0.621371192; }


function getCookieVal (offset) {
   var endstr = document.cookie.indexOf (";", offset);
   if (endstr == -1)
      endstr = document.cookie.length;
   return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        while (i < clen) {
                var j = i + alen;
                if (document.cookie.substring(i, j) == arg)
                        return getCookieVal (j);
                i = document.cookie.indexOf(" ", i) + 1;
                        if (i == 0)
                                break;
                }
   return null;
}

function SetCookie (name, value) 
{
    var argv = SetCookie.arguments;
    var argc = SetCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    var path = (argc > 3) ? argv[3] : null;
    var domain = (argc > 4) ? argv[4] : null;
    var secure = (argc > 5) ? argv[5] : false;
    
    document.cookie = name + "=" + escape (value) +
                ((expires == null) ? "" : ("; expires=" +
                expires.toGMTString())) +
                ((path == null) ? "" : ("; path=" + path)) +
                ((domain == null) ? "" : ("; domain=" + domain)) +
                ((secure == true) ? "; secure" : "");
}

function ParseDist(dist) {
    dist = dist.trim();
    var result = dist.split(" ");

    if (result.length == 2) {
        if (result[1] == "km") return result[0] / 1;
        else if (result[1] == "mi") return MilesToKilos(result[0]);
    }

    if (dist.endsWith("mi")) return MilesToKilos(dist.replace("mi",""));
    if (dist.endsWith("m")) return MetersToKilos(dist.replace("m",""));

    return null;
}

function getURLParameters() 
{
	var sURL = window.document.URL.toString();
	//if (sURL.endsWith('#')) sURL=sURL.substring(0,sURL.length-1);
	
	var results = new Array();

	if (sURL.indexOf("?") > 0)
	{
		var arrParams = sURL.split("?");
			
		var arrURLParams = arrParams[1].split("&");
		
		var arrParamNames = new Array(arrURLParams.length);
		var arrParamValues = new Array(arrURLParams.length);
		
		var i = 0;
		for (i=0;i<arrURLParams.length;i++)
		{
			var sParam =  arrURLParams[i].split("=");
			
			results[sParam[0]]=unescape(sParam[1]);
		}
	}
	return results;
}

function SortWaypoint(wp1, wp2)
{
    return wp1.Timestamp - wp2.Timestamp;
}

function resizeOuterTo(w,h) {
 if (parseInt(navigator.appVersion)>3) {
   if (navigator.appName=="Netscape") {
    top.outerWidth=w;
    top.outerHeight=h;
   }
   else top.resizeTo(w,h);
 }
}

function ShowAboutPanel()
{
    var panelWidth = 300;
    var panelHeight = 300;
    
    var x = map.GetX( map.GetCenterLongitude() ) - panelWidth/2;
    var y = map.GetY( map.GetCenterLatitude() ) - panelHeight/2;
     
    var panel = new VE_Panel("About gpsTrainer",x,y,panelWidth,panelHeight,"blue",31,"About gpsTrainer","","","Mouse Over!",false);

    panel.onCloseClick = function(e) { panel.Hide(); };
  
    var body = "<h2>About Us and Our Sports Training Technologies</h2>"
    body += "<p></p>";
	 body += "	<h3>Terms of Use, Privacy, and Credits</h3>";
	 body += "	<p>Your use of the gpsTrainer site and of the maps, routes and other ";
	 body += "		information presented by the site, is at all times subject to the following:</p>";
	 body += "	<ul>";
	 body += "		<li>";				
	 body += "		</li>";
	 body += "	</ul>";
	 body += "	<p>Copyright 2006 Peak Software Consulting, LLC</p>";

    panel.body.innerHTML = body;
    
    //panel.SetFooter("<a href='http://www.gpsTrainer.com'>gpsTrainer</a>");
    //panel.SetToolbar(GetToolbar());
}


//function MetersPerPixel(map)
//{
//    var p1 = new Position(map.GetCenter().Longitude,map.GetCenter().Latitude);
//    var p2 = new Position(map.PixelToLatLong(map.GetLeft(),map.GetZoomLevel()).Longitude,map.PixelToLatLong(map.GetLeft(),map.GetZoomLevel()).Latitude);
//	
//    var radiusMeters = p1.DistanceTo(p2) * 1000 * Math.sqrt (2);
//    return radiusMeters;
//}

function MetersPerPixel(map)
{
    var earthRadius = 6378137;
    var earthCircum = earthRadius * 2 * Math.PI;
    var zoom = map.GetZoomLevel();
    return earthCircum / (( 1 << zoom ) * 256 );
}


function ChangeOpacity(node, percent)
{
    var is_ie = typeof(document.all) != 'undefined';
    var opacity = (is_ie) ? "filter" : "opacity";

    percent = (is_ie) ? "alpha(opacity=" + percent + ")" : percent/100;
    node.style[opacity] = percent;
}




function degToRad(p) {
    return (Math.PI / 180) * p;
}
	
function RadToDeg(r)
{
   return (r *180)/Math.PI;
}
    


function isFirefox()
{
   return (navigator.userAgent.indexOf("Firefox/") != -1)
}

function isSafari()
{
   return (navigator.userAgent.indexOf("Safari/") != -1)
}

function isChrome()
{
   return (navigator.userAgent.indexOf("Chrome/") != -1)
}

function isNumeric(sText) { 
   var ValidChars = "0123456789."; 
   var Char;
   for (i = 0; i < sText.length; i++) {
       Char = sText.charAt(i);
       if (ValidChars.indexOf(Char) == -1) {
          return false;
       }
    }
   return true;
}

function PadDigits(n, totalDigits) 
    { 
        n = n.toString(); 
        var pd = ''; 
        if (totalDigits > n.length) 
        { 
            for (i=0; i < (totalDigits-n.length); i++) 
            { 
                pd += '0'; 
            } 
        } 
        return pd + n.toString(); 
    } 
    
function Include(js_file)
{
  if(!document.getElementById || !document.createElement){return;} // old browsers
  js_script = document.createElement('script');
  js_script.type = "text/javascript";
  js_script.src = js_file;
  document.getElementsByTagName('head')[0].appendChild(js_script);
}   

function SetWaitCursor()
{
    document.getElementById('map').childNodes[0].style.cursor = 'wait';
    document.getElementById('profile').style.cursor = 'wait';
}

function ClearWaitCursor()
{
    //alert('clear wait cursor');
    document.getElementById('map').childNodes[0].style.cursor = 'default';
    document.getElementById('profile').style.cursor = 'default';
}
function SetMoveCursor()
{
    document.getElementById("map").style.cursor = 'Move';
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

String.prototype.endsWith = function(str) {return (this.match(str+"$")==str)}

function ExpandAbbreviations(input) {
	while (input.indexOf("/") > 0) {

			input = input.replace("/", " aka ");
		}
		
		input = input.replace("take the 1st", "turn");
		
		if (input.toLowerCase().indexOf("destination") > 0)
			input = input.substring(0, input.toLowerCase().indexOf("destination"));
		
		if (input.toLowerCase().indexOf("continue to follow") > 0)
			input = input.substring(0, input.toLowerCase().indexOf("continue to follow"));
		
		input = input.trim();

		var tokens = input.split(" ");

		var sb = "";
		for(i = 0; i < tokens.length; i++){
            var token = tokens[i];
			token = token + " ";
			
			token = token.replace("S ", "South ");
			token = token.replace("N ", "North ");
			token = token.replace("E ", "East ");
			token = token.replace("W ", "West ");
			token = token.replace("Aly ", "Alley ");
			token = token.replace("Anx ", "Annex ");
			token = token.replace("Arc ", "Arcade ");
			token = token.replace("Ave ", "Avenue ");
			token = token.replace("Byu ", "Bayoo ");
			token = token.replace("Bch ", "Beach ");
			token = token.replace("Bnd ", "Bend ");
			token = token.replace("Blf ", "Bluff ");
			token = token.replace("Blvd ", "Boulevard ");
			token = token.replace("Brk ", "Brook ");
			token = token.replace("Byp ", "Bypass ");
			token = token.replace("Cswy ", "Causeway ");
			token = token.replace("Ctr ", "Center ");
			token = token.replace("Cir ", "Circle ");
			token = token.replace("Ct ", "Court ");
			token = token.replace("Cv ", "Cove ");
			token = token.replace("Dr ", "Drive ");
			token = token.replace("Ft ", "Fort ");
			token = token.replace("Fwy ", "Freeway ");
			token = token.replace("Hbr ", "Harbor ");
			token = token.replace("Ln ", "Lane ");
			token = token.replace("Pkwy ", "Parkway ");
			token = token.replace("Pl ", "Place ");
			token = token.replace("Rd ", "Road ");
			token = token.replace("St ", "Street ");
			token = token.replace("Trl ", "Trail ");
			sb += token;
		}
		return sb.trim();
}

function clone(obj) { 
    // Handle the 3 simple types, and null or undefined 
    if (null == obj || "object" != typeof obj) return obj; 
 
    // Handle Date 
    if (obj instanceof Date) { 
        var copy = new Date(); 
        copy.setTime(obj.getTime()); 
        return copy; 
    } 
 
    // Handle Array 
    if (obj instanceof Array) { 
        copy = [];
        for (var i = 0; i < obj.length; i++) {
            copy[i] = clone(obj[i]);
        } 
        return copy; 
    } 
 
    // Handle Object 
    if (obj instanceof Object) { 
        copy = {}; 
        for (var attr in obj) { 
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); 
        } 
        return copy; 
    } 
 
    throw new Error("Unable to copy obj! Its type isn't supported."); 
} 


/*

function AltitudeGainTracker() 
{
  
this.initialized = false;
this.last = 0;

this.hysteresis = 3.048 / 1000; // 10ft 

      
public Distance Hysteresis
{
set { hysteresis = value; }
get { return hysteresis; }
}

public AltitudeGainTracker()
{
hysteresis = DefaultHysteresis;
agl = new AltitudeGainLoss();
}
public AltitudeGainTracker(Distance theHysteresis)
{
hysteresis = theHysteresis;
agl = new AltitudeGainLoss();
}
public void Reset()
{
initialized = false;
agl.Reset();
}

public AltitudeGainLoss GainLoss { get { return agl; } }

public Distance AltitudeGain
{
get
{
return agl.Gain;
}
}
public AltitudeGainLoss Update(Distance d)
{
if (!initialized)
{
initialized = true;
agl.Reset();
           
last = d;
return agl;
}
else {
// get rid of noise
if (Math.Abs(d.Subtract(last).ToFeet().Value) < Hysteresis.ToFeet().Value) return agl;

if (d.IsGreaterThan(last))
{
Distance temp = agl.Gain.Add(d.Subtract(last));
agl.Gain = temp.ToUnitType(d.Units);
}

if (d.IsLessThan(last))
{
Distance temp = agl.Loss.Add(last.Subtract(d));
agl.Loss = temp.ToUnitType(d.Units);
}

last = d;
}
return agl;
}
}
}
*/



