﻿// JScript File


 


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)
{
   busyAddingWaypoints = false;
   ClearWaitCursor();
   alert('Error on '+ 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 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 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 ExtractPoints(waypoints)
    {
        // Waypoints can be either and associative array or a standard array
        // It must be sorted to insure the order is correct
        if (waypoints == null) return null;
        
        var points = new Array();
        var sorted = new Array();
        
        // This will work for the associative array also
        for (var i in waypoints) 
        {
            if (waypoints[i] != null && waypoints[i].Longitude != null)
            {
               sorted.push (waypoints[i]);
            }
        }
        
        sorted.sort (SortWaypoint);
        
        for (var i=0; i<sorted.length; i++)
        {
            points.push (sorted[i].Longitude);
            points.push (sorted[i].Latitude);
        }
        
        return points;
    }

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 CalcTotalDistance()
    {
      
        var distance = 0;
        
        if (pointCount < 2) return 0;
        
        var p1 = new Object();
        var p2 = new Object();
        
        p1.lon = pts[0];
        p1.lat = pts[1];
            
        for(var i=1; i<	pointCount; i++)
        {
            p2.lon = pts[i*2];
            p2.lat = pts[i*2+1];
            
            distance += calcDistance(p1, p2);
            
            p1.lon = p2.lon;
            p1.lat = p2.lat;
        }
        
        return distance;
    }
    
    
    function degToRad(p)
	{
	return 	(Math.PI/180)*p;
	}
	
function RadToDeg(r)
{
   return (r *180)/Math.PI;
}
    
function calcDistance(p1x, p2x) {
  // returns kilometers
  var R = 6371; // 3958.759;// earth's mean radius in statue miles  6371; // earth's mean radius in km 
  
    var p1 = new Object();
    var p2 = new Object();
        
    p1.lat = degToRad(p1x.lat);
    p1.lon = degToRad(p1x.lon);
    p2.lat = degToRad(p2x.lat);
    p2.lon = degToRad(p2x.lon);
        
 
  var dLat  = p2.lat - p1.lat;
  var dLong = p2.lon - p1.lon;

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(p1.lat) * Math.cos(p2.lat) * Math.sin(dLong/2) * Math.sin(dLong/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
	//alert(d);
  return d;
}

function isFirefox()
{
   return (navigator.userAgent.indexOf("Firefox/") != -1)
}

function isSafari()
{
   return (navigator.userAgent.indexOf("Safari/") != -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()
{
    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("/S ", "/South ");
            input = input.replace("/N ", "/North ");
            input = input.replace("/E ", "/East ");
            input = input.replace("/W ", "/West ");
         
            input = input.replace("/", " aka ");
         }
         
         input = input.replace("onto S ", "onto South ");
         input = input.replace("onto N ", "onto North ");
         input = input.replace("onto E ", "onto East ");
         input = input.replace("onto W ", "onto West ");
         input = input.replace("at S ", "at South ");
         input = input.replace("at N ", "at North ");
         input = input.replace("at E ", "at East ");
         input = input.replace("at W ", "at West ");
         input = input.replace("on S ", "on South ");
         input = input.replace("on N ", "on North ");
         input = input.replace("on E ", "on East ");
         input = input.replace("on W ", "on West ");
         input = input.replace(" St ", " Street ");

         if (input.indexOf("Destination") > 0) input = input.substring(0, input.indexOf("Destination"));
         input = input.trim();
         
         if (input.endsWith(" Aly")) input = input.substring(0, input.length - 3) + "Alley";
         if (input.endsWith(" Anx")) input = input.substring(0, input.length - 3) + "Annex";
         if (input.endsWith(" Ave")) input = input.substring(0, input.length - 3) + "Avenue";
         if (input.endsWith(" Bch")) input = input.substring(0, input.length - 3) + "Beach";
         if (input.endsWith(" Bnd")) input = input.substring(0, input.length - 3) + "Bend";
         if (input.endsWith(" Blvd")) input = input.substring(0, input.length - 4) + "Boulevard";
         if (input.endsWith(" Byp")) input = input.substring(0, input.length - 3) + "Bypass";
         if (input.endsWith(" Cswy")) input = input.substring(0, input.length - 4) + "Causeway";
         if (input.endsWith(" Ctr")) input = input.substring(0, input.length - 3) + "Center";
         if (input.endsWith(" Cir")) input = input.substring(0, input.length - 3) + "Circle";
         if (input.endsWith(" Ct")) input = input.substring(0, input.length - 2) + "Court";
         if (input.endsWith(" Cv")) input = input.substring(0, input.length - 2) + "Cove";
         if (input.endsWith(" Dr")) input = input.substring(0, input.length - 2) + "Drive";
         if (input.endsWith(" Ft")) input = input.substring(0, input.length - 2) + "Fort";
         if (input.endsWith(" Fwy")) input = input.substring(0, input.length - 3) + "Freeway";
         if (input.endsWith(" Hbr")) input = input.substring(0, input.length - 3) + "Harbor";
         if (input.endsWith(" Ln")) input = input.substring(0, input.length - 2) + "Lane";
         if (input.endsWith(" Pkwy")) input = input.substring(0, input.length - 4) + "Parkway";
         if (input.endsWith(" Pl")) input = input.substring(0, input.length - 2) + "Place";
         if (input.endsWith(" Rd")) input = input.substring(0, input.length - 2) + "Road";
         if (input.endsWith(" St")) input = input.substring(0, input.length - 2) + "Street";
         if (input.endsWith(" Trl")) input = input.substring(0, input.length - 3) + "Trail";

       
         return input;
      }