    var pi = 3.14159265358979;

    /* Ellipsoid model constants (actual values here are for WGS84) */
    var sm_a = 6378137.0;
    var sm_b = 6356752.314;
    var sm_EccSquared = 6.69437999013e-03;

    var UTMScaleFactor = 0.9996;

String.repeat = function(chr,count)

{    

    var str = ""; 

    for(var x=0;x<count;x++) {str += chr}; 

    return str;

}

String.prototype.padL = function(width,pad)

{

    if (!width ||width<1)

        return this;   

 

    if (!pad) pad=" ";        

    var length = width - this.length

    if (length < 1) return this.substr(0,width);

 

    return (String.repeat(pad,length) + this).substr(0,width);    

}    

String.prototype.padR = function(width,pad)

{

    if (!width || width<1)

        return this;        

 

    if (!pad) pad=" ";

    var length = width - this.length

    if (length < 1) this.substr(0,width);

 

    return (this + String.repeat(pad,length)).substr(0,width);

} 

Date.prototype.formatDate = function(format)

{

    var date = this;

    if (!format)

      format="MM/dd/yyyy";               

 

    var month = date.getMonth() + 1;

    var year = date.getFullYear();    

 

    format = format.replace("MM",month.toString().padL(2,"0"));        

 

    if (format.indexOf("yyyy") > -1)

        format = format.replace("yyyy",year.toString());

    else if (format.indexOf("yy") > -1)

        format = format.replace("yy",year.toString().substr(2,2));

 

    format = format.replace("dd",date.getDate().toString().padL(2,"0"));

 

    var hours = date.getHours();       

    if (format.indexOf("t") > -1)

    {

       if (hours > 11)

        format = format.replace("t","pm")

       else

        format = format.replace("t","am")

    }

    if (format.indexOf("HH") > -1)

        format = format.replace("HH",hours.toString().padL(2,"0"));

    if (format.indexOf("hh") > -1) {

        if (hours > 12) hours - 12;

        if (hours == 0) hours = 12;

        format = format.replace("hh",hours.toString().padL(2,"0"));        

    }

    if (format.indexOf("mm") > -1)

       format = format.replace("mm",date.getMinutes().toString().padL(2,"0"));

    if (format.indexOf("ss") > -1)

       format = format.replace("ss",date.getSeconds().toString().padL(2,"0"));

    return format;

}

    // extend String object with method for parsing degrees or lat/long values to numeric degrees
    //
    // this is very flexible on formats, allowing signed decimal degrees, or deg-min-sec suffixed by 
    // compass direction (NSEW). A variety of separators are accepted (eg 3º 37' 09"W) or fixed-width 
    // format without separators (eg 0033709W). Seconds and minutes may be omitted. (Minimal validation 
    // is done).

    Number.prototype.toRound = function(dec) {
	var result = Math.round(this*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
    } // Number.prototype.toRound

    String.prototype.parseDeg = function() {
      if (!isNaN(this)) return Number(this);                 // signed decimal degrees without NSEW

      var degLL = this.replace(/^-/,'').replace(/[NSEW]/i,'');  // strip off any sign or compass dir'n
      var dms = degLL.split(/[^0-9.]+/);                     // split out separate d/m/s
      for (var i in dms) if (dms[i]=='') dms.splice(i,1);    // remove empty elements (see note below)
      switch (dms.length) {                                  // convert to decimal degrees...
        case 3:                                              // interpret 3-part result as d/m/s
          var deg = dms[0]/1 + dms[1]/60 + dms[2]/3600; break;
        case 2:                                              // interpret 2-part result as d/m
          var deg = dms[0]/1 + dms[1]/60; break;
        case 1:                                              // decimal or non-separated dddmmss
          if (/[NS]/i.test(this)) degLL = '0' + degLL;       // - normalise N/S to 3-digit degrees
          var deg = dms[0].slice(0,3)/1 + dms[0].slice(3,5)/60 + dms[0].slice(5)/3600; break;
        default: return NaN;
      }
      if (/^-/.test(this) || /[WS]/i.test(this)) deg = -deg; // take '-', west and south as -ve
      return deg;
    }
    // note: whitespace at start/end will split() into empty elements (except in IE)


    // extend Number object with methods for converting degrees/radians

    Number.prototype.toRad = function() {  // convert degrees to radians
       return this * Math.PI / 180;
    }

    Number.prototype.toDeg = function() {  // convert radians to degrees (signed)
      return this * 180 / Math.PI;
    }

    // extend Number object with methods for presenting bearings & lat/longs

    Number.prototype.toDMS = function(dp) {  // convert numeric degrees to deg/min/sec
      if (arguments.length < 1) dp = 0;      // if no decimal places argument, round to int seconds
      var d = Math.abs(this);  // (unsigned result ready for appending compass dir'n)
      var deg = Math.floor(d);
      var min = Math.floor((d-deg)*60);
      var sec = ((d-deg-min/60)*3600).toFixed(dp);
      // fix any nonsensical rounding-up
      if (sec==60) { sec = (0).toFixed(dp); min++; }
      if (min==60) { min = 0; deg++; }
      if (deg==360) deg = 0;
      // add leading zeros if required
      if (deg<100) deg = '0' + deg; if (deg<10) deg = '0' + deg;
      if (min<10) min = '0' + min;
      if (sec<10) sec = '0' + sec;
      return deg + '\u00B0' + min + '\u2032' + sec + '\u2033';
    }

    Number.prototype.toLat = function(dp) {  // convert numeric degrees to deg/min/sec latitude
      return this.toDMS(dp).slice(1) + (this<0 ? 'S' : 'N');  // knock off initial '0' for lat!
    }

    Number.prototype.toLon = function(dp) {  // convert numeric degrees to deg/min/sec longitude
      return this.toDMS(dp) + (this>0 ? 'E' : 'W');
    }

    /*
    * DegToRad
    *
    * Converts degrees to radians.
    *
    */
    function DegToRad (deg)
    {
        return (deg / 180.0 * pi)
    }




    /*
    * RadToDeg
    *
    * Converts radians to degrees.
    *
    */
    function RadToDeg (rad)
    {
        return (rad / pi * 180.0)
    }

    /*
     * construct a LatLon object: arguments in numeric degrees
     *
     * note all LatLong methods expect & return numeric degrees (for lat/long & for bearings)
     */
    function LatLon(lat, lon) {
      this.lat = lat;
      this.lon = lon;
    }


    /*
     * represent point {lat, lon} in standard representation
     */
    LatLon.prototype.toString = function() {
      return this.lat.toLat() + ', ' + this.lon.toLon();
    }

    /*
     * calculate (initial) bearing between two points
     *   see http://williams.best.vwh.net/avform.htm#Crs
     */
    LatLon.bearing = function(lat1, lon1, lat2, lon2) {
      lat1 = lat1.toRad(); lat2 = lat2.toRad();
      var dLon = (lon2-lon1).toRad();

      var y = Math.sin(dLon) * Math.cos(lat2);
      var x = Math.cos(lat1)*Math.sin(lat2) -
              Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
      return Math.atan2(y, x).toBrng();
    }

    /*
     * calculate (initial) bearing between two points
     *   see http://williams.best.vwh.net/avform.htm#Crs
     */
    GLatLng.prototype.toBearingImage = function(p) {
      var lat1 = this.lat();
      var lon1 = this.lng();
      var lat2 = p.lat();
      var lon2 = p.lng();

      lat1 = lat1.toRad(); lat2 = lat2.toRad();
      var dLon = (lon2-lon1).toRad();

      var y = Math.sin(dLon) * Math.cos(lat2);
      var x = Math.cos(lat1)*Math.sin(lat2) -
              Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
      return Math.atan2(y, x).toBrng().toDirectionImage();
    } // GLatLng::toBearing

    Number.prototype.toBrng = function() {  // convert radians to degrees (as bearing: 0...360)
      return (this.toDeg()+360.0) % 360.0;
    }

    Number.prototype.toDirectionImage = function() {
      var dirs = new Array("north","east","south","west");
      var dir;
      var bearing = this;

      var rounded = floor(Math.round(bearing / 22.5) % 16);

      if ((rounded % 4) == 0)
        dir = dirs[rounded / 4];
      else {
        dir = dirs[2 * floor(((floor(rounded / 4) + 1) % 4) / 2)];
        dir += '_' + dirs[1 + 2 * floor(rounded / 8)];
      }  // else

      return dir+'.png';
    } // Number::toDirectionImage

    function floor(n) {
      return Math.floor(n);
    } // floor

    function fmod(x, y) {
      // http://kevin.vanzonneveld.net
      // +   original by: Onno Marsman
      // +      input by: Brett Zamir (http://brettz9.blogspot.com)
      // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
      // *     example 1: fmod(5.7, 1.3);
      // *     returns 1: 0.5
    
      var tmp, tmp2, p = 0, pY = 0, l = 0.0, l2 = 0.0;
    
      tmp = x.toExponential().match(/^.\.?(.*)e(.+)$/);
      p = parseInt(tmp[2])-(tmp[1]+'').length;
      tmp = y.toExponential().match(/^.\.?(.*)e(.+)$/);
      pY = parseInt(tmp[2])-(tmp[1]+'').length;
    
      if (pY > p) {
          p = pY;
      }
    
      tmp2 = (x%y);
    
      if (p < -100 || p > 20) {
        // toFixed will give an out of bound error so we fix it like this:
        l  = Math.round(Math.log(tmp2)/Math.log(10));
        l2 = Math.pow(10, l);
        
        return (tmp2 / l2).toFixed(l-p)*l2;
      } else {
        return parseFloat(tmp2.toFixed(-p));
      }
    } // fmod

    /*
    * ArcLengthOfMeridian
    *
    * Computes the ellipsoidal distance from the equator to a point at a
    * given latitude.
    *
    * Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
    * GPS: Theory and Practice, 3rd ed.  New York: Springer-Verlag Wien, 1994.
    *
    * Inputs:
    *     phi - Latitude of the point, in radians.
    *
    * Globals:
    *     sm_a - Ellipsoid model major axis.
    *     sm_b - Ellipsoid model minor axis.
    *
    * Returns:
    *     The ellipsoidal distance of the point from the equator, in meters.
    *
    */
    function ArcLengthOfMeridian (phi)
    {
        var alpha, beta, gamma, delta, epsilon, n;
        var result;

        /* Precalculate n */
        n = (sm_a - sm_b) / (sm_a + sm_b);

        /* Precalculate alpha */
        alpha = ((sm_a + sm_b) / 2.0)
           * (1.0 + (Math.pow (n, 2.0) / 4.0) + (Math.pow (n, 4.0) / 64.0));

        /* Precalculate beta */
        beta = (-3.0 * n / 2.0) + (9.0 * Math.pow (n, 3.0) / 16.0)
           + (-3.0 * Math.pow (n, 5.0) / 32.0);

        /* Precalculate gamma */
        gamma = (15.0 * Math.pow (n, 2.0) / 16.0)
            + (-15.0 * Math.pow (n, 4.0) / 32.0);
    
        /* Precalculate delta */
        delta = (-35.0 * Math.pow (n, 3.0) / 48.0)
            + (105.0 * Math.pow (n, 5.0) / 256.0);
    
        /* Precalculate epsilon */
        epsilon = (315.0 * Math.pow (n, 4.0) / 512.0);
    
    /* Now calculate the sum of the series and return */
    result = alpha
        * (phi + (beta * Math.sin (2.0 * phi))
            + (gamma * Math.sin (4.0 * phi))
            + (delta * Math.sin (6.0 * phi))
            + (epsilon * Math.sin (8.0 * phi)));

    return result;
    }



    /*
    * UTMCentralMeridian
    *
    * Determines the central meridian for the given UTM zone.
    *
    * Inputs:
    *     zone - An integer value designating the UTM zone, range [1,60].
    *
    * Returns:
    *   The central meridian for the given UTM zone, in radians, or zero
    *   if the UTM zone parameter is outside the range [1,60].
    *   Range of the central meridian is the radian equivalent of [-177,+177].
    *
    */
    function UTMCentralMeridian (zone)
    {
        var cmeridian;

        cmeridian = DegToRad (-183.0 + (zone * 6.0));
    
        return cmeridian;
    }



    /*
    * FootpointLatitude
    *
    * Computes the footpoint latitude for use in converting transverse
    * Mercator coordinates to ellipsoidal coordinates.
    *
    * Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
    *   GPS: Theory and Practice, 3rd ed.  New York: Springer-Verlag Wien, 1994.
    *
    * Inputs:
    *   y - The UTM northing coordinate, in meters.
    *
    * Returns:
    *   The footpoint latitude, in radians.
    *
    */
    function FootpointLatitude (y)
    {
        var y_, alpha_, beta_, gamma_, delta_, epsilon_, n;
        var result;
        
        /* Precalculate n (Eq. 10.18) */
        n = (sm_a - sm_b) / (sm_a + sm_b);
        	
        /* Precalculate alpha_ (Eq. 10.22) */
        /* (Same as alpha in Eq. 10.17) */
        alpha_ = ((sm_a + sm_b) / 2.0)
            * (1 + (Math.pow (n, 2.0) / 4) + (Math.pow (n, 4.0) / 64));
        
        /* Precalculate y_ (Eq. 10.23) */
        y_ = y / alpha_;
        
        /* Precalculate beta_ (Eq. 10.22) */
        beta_ = (3.0 * n / 2.0) + (-27.0 * Math.pow (n, 3.0) / 32.0)
            + (269.0 * Math.pow (n, 5.0) / 512.0);
        
        /* Precalculate gamma_ (Eq. 10.22) */
        gamma_ = (21.0 * Math.pow (n, 2.0) / 16.0)
            + (-55.0 * Math.pow (n, 4.0) / 32.0);
        	
        /* Precalculate delta_ (Eq. 10.22) */
        delta_ = (151.0 * Math.pow (n, 3.0) / 96.0)
            + (-417.0 * Math.pow (n, 5.0) / 128.0);
        	
        /* Precalculate epsilon_ (Eq. 10.22) */
        epsilon_ = (1097.0 * Math.pow (n, 4.0) / 512.0);
        	
        /* Now calculate the sum of the series (Eq. 10.21) */
        result = y_ + (beta_ * Math.sin (2.0 * y_))
            + (gamma_ * Math.sin (4.0 * y_))
            + (delta_ * Math.sin (6.0 * y_))
            + (epsilon_ * Math.sin (8.0 * y_));
        
        return result;
    }



    /*
    * MapLatLonToXY
    *
    * Converts a latitude/longitude pair to x and y coordinates in the
    * Transverse Mercator projection.  Note that Transverse Mercator is not
    * the same as UTM; a scale factor is required to convert between them.
    *
    * Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
    * GPS: Theory and Practice, 3rd ed.  New York: Springer-Verlag Wien, 1994.
    *
    * Inputs:
    *    phi - Latitude of the point, in radians.
    *    lambda - Longitude of the point, in radians.
    *    lambda0 - Longitude of the central meridian to be used, in radians.
    *
    * Outputs:
    *    xy - A 2-element array containing the x and y coordinates
    *         of the computed point.
    *
    * Returns:
    *    The function does not return a value.
    *
    */
    function MapLatLonToXY (phi, lambda, lambda0, xy)
    {
        var N, nu2, ep2, t, t2, l;
        var l3coef, l4coef, l5coef, l6coef, l7coef, l8coef;
        var tmp;

        /* Precalculate ep2 */
        ep2 = (Math.pow (sm_a, 2.0) - Math.pow (sm_b, 2.0)) / Math.pow (sm_b, 2.0);
    
        /* Precalculate nu2 */
        nu2 = ep2 * Math.pow (Math.cos (phi), 2.0);
    
        /* Precalculate N */
        N = Math.pow (sm_a, 2.0) / (sm_b * Math.sqrt (1 + nu2));
    
        /* Precalculate t */
        t = Math.tan (phi);
        t2 = t * t;
        tmp = (t2 * t2 * t2) - Math.pow (t, 6.0);

        /* Precalculate l */
        l = lambda - lambda0;
    
        /* Precalculate coefficients for l**n in the equations below
           so a normal human being can read the expressions for easting
           and northing
           -- l**1 and l**2 have coefficients of 1.0 */
        l3coef = 1.0 - t2 + nu2;
    
        l4coef = 5.0 - t2 + 9 * nu2 + 4.0 * (nu2 * nu2);
    
        l5coef = 5.0 - 18.0 * t2 + (t2 * t2) + 14.0 * nu2
            - 58.0 * t2 * nu2;
    
        l6coef = 61.0 - 58.0 * t2 + (t2 * t2) + 270.0 * nu2
            - 330.0 * t2 * nu2;
    
        l7coef = 61.0 - 479.0 * t2 + 179.0 * (t2 * t2) - (t2 * t2 * t2);
    
        l8coef = 1385.0 - 3111.0 * t2 + 543.0 * (t2 * t2) - (t2 * t2 * t2);
    
        /* Calculate easting (x) */
        xy[0] = N * Math.cos (phi) * l
            + (N / 6.0 * Math.pow (Math.cos (phi), 3.0) * l3coef * Math.pow (l, 3.0))
            + (N / 120.0 * Math.pow (Math.cos (phi), 5.0) * l5coef * Math.pow (l, 5.0))
            + (N / 5040.0 * Math.pow (Math.cos (phi), 7.0) * l7coef * Math.pow (l, 7.0));
    
        /* Calculate northing (y) */
        xy[1] = ArcLengthOfMeridian (phi)
            + (t / 2.0 * N * Math.pow (Math.cos (phi), 2.0) * Math.pow (l, 2.0))
            + (t / 24.0 * N * Math.pow (Math.cos (phi), 4.0) * l4coef * Math.pow (l, 4.0))
            + (t / 720.0 * N * Math.pow (Math.cos (phi), 6.0) * l6coef * Math.pow (l, 6.0))
            + (t / 40320.0 * N * Math.pow (Math.cos (phi), 8.0) * l8coef * Math.pow (l, 8.0));
    
        return;
    }
    
    
    
    /*
    * MapXYToLatLon
    *
    * Converts x and y coordinates in the Transverse Mercator projection to
    * a latitude/longitude pair.  Note that Transverse Mercator is not
    * the same as UTM; a scale factor is required to convert between them.
    *
    * Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J.,
    *   GPS: Theory and Practice, 3rd ed.  New York: Springer-Verlag Wien, 1994.
    *
    * Inputs:
    *   x - The easting of the point, in meters.
    *   y - The northing of the point, in meters.
    *   lambda0 - Longitude of the central meridian to be used, in radians.
    *
    * Outputs:
    *   philambda - A 2-element containing the latitude and longitude
    *               in radians.
    *
    * Returns:
    *   The function does not return a value.
    *
    * Remarks:
    *   The local variables Nf, nuf2, tf, and tf2 serve the same purpose as
    *   N, nu2, t, and t2 in MapLatLonToXY, but they are computed with respect
    *   to the footpoint latitude phif.
    *
    *   x1frac, x2frac, x2poly, x3poly, etc. are to enhance readability and
    *   to optimize computations.
    *
    */
    function MapXYToLatLon (x, y, lambda0, philambda)
    {
        var phif, Nf, Nfpow, nuf2, ep2, tf, tf2, tf4, cf;
        var x1frac, x2frac, x3frac, x4frac, x5frac, x6frac, x7frac, x8frac;
        var x2poly, x3poly, x4poly, x5poly, x6poly, x7poly, x8poly;
    	
        /* Get the value of phif, the footpoint latitude. */
        phif = FootpointLatitude (y);
        	
        /* Precalculate ep2 */
        ep2 = (Math.pow (sm_a, 2.0) - Math.pow (sm_b, 2.0))
              / Math.pow (sm_b, 2.0);
        	
        /* Precalculate cos (phif) */
        cf = Math.cos (phif);
        	
        /* Precalculate nuf2 */
        nuf2 = ep2 * Math.pow (cf, 2.0);
        	
        /* Precalculate Nf and initialize Nfpow */
        Nf = Math.pow (sm_a, 2.0) / (sm_b * Math.sqrt (1 + nuf2));
        Nfpow = Nf;
        	
        /* Precalculate tf */
        tf = Math.tan (phif);
        tf2 = tf * tf;
        tf4 = tf2 * tf2;
        
        /* Precalculate fractional coefficients for x**n in the equations
           below to simplify the expressions for latitude and longitude. */
        x1frac = 1.0 / (Nfpow * cf);
        
        Nfpow *= Nf;   /* now equals Nf**2) */
        x2frac = tf / (2.0 * Nfpow);
        
        Nfpow *= Nf;   /* now equals Nf**3) */
        x3frac = 1.0 / (6.0 * Nfpow * cf);
        
        Nfpow *= Nf;   /* now equals Nf**4) */
        x4frac = tf / (24.0 * Nfpow);
        
        Nfpow *= Nf;   /* now equals Nf**5) */
        x5frac = 1.0 / (120.0 * Nfpow * cf);
        
        Nfpow *= Nf;   /* now equals Nf**6) */
        x6frac = tf / (720.0 * Nfpow);
        
        Nfpow *= Nf;   /* now equals Nf**7) */
        x7frac = 1.0 / (5040.0 * Nfpow * cf);
        
        Nfpow *= Nf;   /* now equals Nf**8) */
        x8frac = tf / (40320.0 * Nfpow);
        
        /* Precalculate polynomial coefficients for x**n.
           -- x**1 does not have a polynomial coefficient. */
        x2poly = -1.0 - nuf2;
        
        x3poly = -1.0 - 2 * tf2 - nuf2;
        
        x4poly = 5.0 + 3.0 * tf2 + 6.0 * nuf2 - 6.0 * tf2 * nuf2
        	- 3.0 * (nuf2 *nuf2) - 9.0 * tf2 * (nuf2 * nuf2);
        
        x5poly = 5.0 + 28.0 * tf2 + 24.0 * tf4 + 6.0 * nuf2 + 8.0 * tf2 * nuf2;
        
        x6poly = -61.0 - 90.0 * tf2 - 45.0 * tf4 - 107.0 * nuf2
        	+ 162.0 * tf2 * nuf2;
        
        x7poly = -61.0 - 662.0 * tf2 - 1320.0 * tf4 - 720.0 * (tf4 * tf2);
        
        x8poly = 1385.0 + 3633.0 * tf2 + 4095.0 * tf4 + 1575 * (tf4 * tf2);
        	
        /* Calculate latitude */
        philambda[0] = phif + x2frac * x2poly * (x * x)
        	+ x4frac * x4poly * Math.pow (x, 4.0)
        	+ x6frac * x6poly * Math.pow (x, 6.0)
        	+ x8frac * x8poly * Math.pow (x, 8.0);
        	
        /* Calculate longitude */
        philambda[1] = lambda0 + x1frac * x
        	+ x3frac * x3poly * Math.pow (x, 3.0)
        	+ x5frac * x5poly * Math.pow (x, 5.0)
        	+ x7frac * x7poly * Math.pow (x, 7.0);
        	
        return;
    }




    /*
    * LatLonToUTMXY
    *
    * Converts a latitude/longitude pair to x and y coordinates in the
    * Universal Transverse Mercator projection.
    *
    * Inputs:
    *   lat - Latitude of the point, in radians.
    *   lon - Longitude of the point, in radians.
    *   zone - UTM zone to be used for calculating values for x and y.
    *          If zone is less than 1 or greater than 60, the routine
    *          will determine the appropriate zone from the value of lon.
    *
    * Outputs:
    *   xy - A 2-element array where the UTM x and y values will be stored.
    *
    * Returns:
    *   The UTM zone used for calculating the values of x and y.
    *
    */
    function LatLonToUTMXY (lat, lon, zone, xy)
    {
        MapLatLonToXY (lat, lon, UTMCentralMeridian (zone), xy);

        /* Adjust easting and northing for UTM system. */
        xy[0] = xy[0] * UTMScaleFactor + 500000.0;
        xy[1] = xy[1] * UTMScaleFactor;
        if (xy[1] < 0.0)
            xy[1] = xy[1] + 10000000.0;

        return zone;
    }
    
    
    
   /*
    * UTMXYToLatLon
    *
    * Converts x and y coordinates in the Universal Transverse Mercator
    * projection to a latitude/longitude pair.
    *
    * Inputs:
    *	x - The easting of the point, in meters.
    *	y - The northing of the point, in meters.
    *	zone - The UTM zone in which the point lies.
    *	southhemi - True if the point is in the southern hemisphere;
    *               false otherwise.
    *
    * Outputs:
    *	latlon - A 2-element array containing the latitude and
    *            longitude of the point, in radians.
    *
    * Returns:
    *	The function does not return a value.
    *
    */
    function UTMXYToLatLon (x, y, zone, southhemi, latlon)
    {
        var cmeridian;
        	
        x -= 500000.0;
        x /= UTMScaleFactor;
        	
        /* If in southern hemisphere, adjust y accordingly. */
        if (southhemi)
        y -= 10000000.0;
        		
        y /= UTMScaleFactor;
        
        cmeridian = UTMCentralMeridian (zone);
        MapXYToLatLon (x, y, cmeridian, latlon);
        	
        return;
    }

    function toDistance(latitude1, longitude1, latitude2, longitude2) {
      var theta = longitude1 - longitude2;

      var distance = (Math.sin(latitude1.toRad()) * Math.sin(latitude2.toRad())) + (Math.cos(latitude1.toRad()) * Math.cos(latitude2.toRad()) * Math.cos(theta.toRad()));
      distance = Math.acos(distance);
      distance = distance.toDeg();
      distance = distance * 60 * 1.1515;

      return distance;
    } // toDistance

    function toElevation(lat1, lon1, lon2) {
      var dlon = (lon2-lon1).toRad();
      var lat1 = lat1.toRad();
      var lon1 = lon1.toRad();


      var x = (Math.cos(dlon) * Math.cos(lat1) - 0.1512);   
      var y = Math.sqrt(1 - Math.pow(Math.cos(dlon), 2.0) * Math.pow(Math.cos(lat1), 2.0));

      var e = Math.atan(x/y);

      return e.toDeg();
    } // toElevation

    Number.prototype.toGroundRange = function() {
      // calculations for range
      var ck = 1.609343999999998;

      var h = this;
      var hk = h * ck;

      var rh = 6375 + h;
      var theta_rad = Math.acos(6375 / rh);
      var theta = theta_rad * 57.2958;
      var theta = ((theta * 10) + 0.5) / 10;
      var range = 220 * theta;

      return range;
    } // toGroundRange

    Number.prototype.toKilometer = function() {
      return (this * 1.609343999999998);
    } // Number::toKilometer

    Number.prototype.toMiles = function() {
      return (this * 0.621371192);
    } // Number::toMiles

    function toElevation3(lat1, lon1, el1, lat2, lon2, el2) {
      var del = el2 - el1;
      var d = toDistance(lat1, lon1, lat2, lon2);
      var lambda = (180/Math.PI) * ( del / d - d / (2*3956) );

      //log('D: '+d+', R: '+el2.toGroundRange());
      //if (del == Math.abs(del))
      //  lambda = lambda * -1;

      return lambda;
    } // toElevation

    function toElevation2(eslat, eslon, esheight, slat, slon) {
	var DTOR, RTOD, A, B, F, RSAT, ESHEIGHT, ESLAT, ESLONG, SATLAT, SATLONG, XS, YS, ZS, EE, BETA, RHO;
	var TXS, TYS, TZS, DIST, AZ, XS2, YS2, ZS2, TXS2, TYS2, TZS2, DIST2, RANGE;

	DTOR=Math.PI/180; RTOD=180/Math.PI;	A=6378.3880;	B=6356.9120;	F=1/297;
	RSAT=Math.pow((6028.82*((24*60)-4)), 2/3);

	ESHEIGHT=esheight;
	ESLAT=eslat;
	ESLONG=eslon;
	SATLAT=slat;
	SATLONG=slon;

	XS=RSAT*Math.cos(DTOR*SATLAT)*Math.cos(DTOR*SATLONG);
	XS2=RSAT*Math.cos(-SATLAT*DTOR)*Math.cos(SATLONG*DTOR);
	YS=RSAT*Math.cos(DTOR*SATLAT)*Math.sin(DTOR*SATLONG);
	YS2=RSAT*Math.cos(-SATLAT*DTOR)*Math.sin(SATLONG*DTOR);
	ZS=RSAT*Math.sin(DTOR*SATLAT);
	ZS2=-RSAT*Math.sin(DTOR*SATLAT);
	EE=2*F - Math.pow(F, 2);
	BETA=Math.atan((1-EE)*Math.tan(ESLAT*DTOR));
	RHO=A*(1-F)/Math.sqrt(1-(2-F)*F*Math.cos(ESLAT*DTOR)*Math.cos(ESLAT*DTOR));
	TXS=(XS*Math.cos(ESLONG*DTOR)+YS*Math.sin(ESLONG*DTOR)-RHO*Math.cos(BETA))*Math.sin(ESLAT*DTOR)-(ZS-RHO*Math.sin(BETA))*Math.cos(ESLAT*DTOR);
	TXS2=(XS2*Math.cos(ESLONG*DTOR)+YS2*Math.sin(ESLONG*DTOR)-RHO*Math.cos(BETA))*Math.sin(ESLAT*DTOR)-(ZS2-RHO*Math.sin(BETA))*Math.cos(ESLAT*DTOR);
	TYS=-XS*Math.sin(ESLONG*DTOR)+YS*Math.cos(ESLONG*DTOR);
	TYS2=-XS2*Math.sin(ESLONG*DTOR)+YS2*Math.cos(ESLONG*DTOR);
	TZS=(XS*Math.cos(ESLONG*DTOR)+YS*Math.sin(ESLONG*DTOR)-RHO*Math.cos(BETA))*Math.cos(ESLAT*DTOR)+(ZS-RHO*Math.sin(BETA))*Math.sin(ESLAT*DTOR)-(ESHEIGHT/1000);
	TZS2=(XS2*Math.cos(ESLONG*DTOR)+YS2*Math.sin(ESLONG*DTOR)-RHO*Math.cos(BETA))*Math.cos(ESLAT*DTOR)+(ZS2-RHO*Math.sin(BETA))*Math.sin(ESLAT*DTOR)-(ESHEIGHT/1000);
	DIST=Math.sqrt(TXS*TXS+TYS*TYS+TZS*TZS);
	DIST2=Math.sqrt(TXS2*TXS2+TYS2*TYS2+TZS2*TZS2)
	AZ=180-RTOD*ATAN2(TXS,TYS);
	EL=Math.asin(TZS/DIST)*RTOD;
	RANGE=Math.max(DIST, DIST2);

      //window.document.Form.AZ.value = round(AZ, 3);
      //window.document.Form.EA.value = round(EL, 3);
      //window.document.Form.RANGE.value = round(RANGE, 3);

      return EL;
    } // toElevation2

    function ATAN2(x, y) {
      var tmp;

      if (y == 0) {
        if (x > 0) {
          tmp = 0;
        } else {
          if (x < 0) {
            tmp = Math.PI;
          } else {
            tmp = 1/0;
          }
        }
      } else {
        if (y > 0) {
          tmp = (Math.PI/2) - Math.atan(x/y);
        } else {
          tmp = -(Math.PI/2) - Math.atan(x/y);
        }
      } // ATAN2

      return tmp;
    }

    function round(val, places) {
      val = val * Math.pow(10, places)
      val = Math.round(val)
      val = val / Math.pow(10, places)
      return val;
    } // round

    function Elevation2(SatLon,SiteLat,SiteLon,Height_over_ocean) {
      var Rstation,f,r_eq,r_sat,Ra,Rz,alfa_r,alfa_rx,alfa_ry,refraction,alfa_rz,alfa_r_north,alfa_r_zenith,El_geometric,El_observed,Elevation;
      var x,a0,a1,a2,a3,a4;

      a0 = 0.58804392;
      a1 = -0.17941557;
      a2 = 0.29906946E-1;
      a3 = -0.25187400E-2;
      a4 = 0.82622101E-4;

      f = (1/298.257) ; // Earth flattning factor
      r_sat = 42164.57; // Distance from earth centre to satellite
      r_eq = 6378.14 ; // Earth radius


      Rstation = r_eq/( Math.sqrt( 1 - f*(2-f)*Math.sin(Radians(SiteLat))*Math.sin(Radians(SiteLat)) ) ) ;
      Ra = (Rstation+Height_over_ocean)*Math.cos(Radians(SiteLat)) ;
      Rz = Rstation*(1-f)*(1-f)*Math.sin(Radians(SiteLat));
      alfa_r = r_sat-Rstation;

      alfa_rx = r_sat*Math.cos(Radians(SatLon-SiteLon)) -Ra ;
      alfa_ry = r_sat*Math.sin(Radians(SatLon-SiteLon)) ;
      alfa_rz = -Rz;

      alfa_r_north = -alfa_rx*Math.sin(Radians(SiteLat)) + alfa_rz*Math.cos(Radians(SiteLat)) ;
      alfa_r_zenith = alfa_rx*Math.cos(Radians(SiteLat)) +alfa_rz*Math.sin(Radians(SiteLat)) ;

      El_geometric = Deg(Math.atan2( alfa_r_zenith , Math.sqrt(alfa_r_north*alfa_r_north+alfa_ry*alfa_ry)));

      x = Math.abs(El_geometric+0.589);
      refraction = Math.abs(a0+a1*x+a2*x*x+a3*x*x*x +a4*x*x*x*x) ;

      if (El_geometric > 10.2)
        El_observed = El_geometric+0.01617*(Math.cos(Radians(Math.abs(El_geometric)))/Math.sin(Radians(Math.abs(El_geometric))) );
      else
        El_observed = El_geometric+refraction; 

      //if (alfa_r_zenith<-3000) El_observed=-99;

      return (El_observed);
    } // Elevation2

    function ElevationRefraction(El_geometric) {
      var El_observed;
      var x,a0,a1,a2,a3,a4;
      a0 = 0.58804392;
      a1 = -0.17941557;
      a2 = 0.29906946E-1;
      a3= -0.25187400E-2;
      a4 = 0.82622101E-4;

      El_observed = El_geometric;

      x = Math.abs(El_geometric + 0.589);
      refraction = Math.abs(a0+a1*x+a2*x*x+a3*x*x*x +a4*x*x*x*x);

      if (El_geometric > 10.2)
        El_observed = El_geometric+0.01617*(Math.cos(Radians(Math.abs(El_geometric)))/Math.sin(Radians(Math.abs(El_geometric))) );
      else 
        El_observed =El_geometric+refraction;

      return (El_observed);
    } // ElevationRefraction

    function Rev(number) {
      var x;
      x = number -Math.floor(number/360.0)*360;

      return(x);
    } // Rev

    function JulianDayNumber(Day,Month,Year,Hour,Minute,Second) {
      //window.alert(Day+" "+Month+" "+Year+" "+Hour+" "+Minute+" "+Second);

      d = 367 * Year - Div(  (7*(Year+(Div((Month+9),12)))),4 ) + Div((275*Month),9) + Day - 730530;
      // d is correct
      //window.alert(d);
      d = d + Hour/24 + Minute/(60*24) + Second/(24*60*60);   // OK

      return(d);
    } // JulianDayNumber

    /* ----------------------------------------------------------------------------
     * Name: calcJulianDayNumber
     * Convert a Gregorian date to the corresponding Julian day number
     * Parameters:
     *  day: day number of the month with fractional hours
     *  month: month number of the year (january = 1, feb = 2, march = 3, etc.)
     *  year: the year
     * Returns: Julian day number
     * Note: The Gregorian calandar begining date considered is 1582 october 15th      
     */
    function calcJulianDayNumber(day, month, year) {
      var GREGORIAN_BEGIN_YEAR=1582;
      var GREGORIAN_BEGIN_MONTH=10;
      var GREGORIAN_BEGIN_DAY=15;
      var b = 0;
      var isgregorian = false;

      if (year > GREGORIAN_BEGIN_YEAR)
        isgregorian = true;
      else if (year == GREGORIAN_BEGIN_YEAR) {
        if (month > GREGORIAN_BEGIN_MONTH)
          isgregorian = true;
        else if ($month == $GREGORIAN_BEGIN_MONTH) {
           if (day >= $GREGORIAN_BEGIN_DAY)
             isgregorian = true;
        } // else if
      } // else if

      // if the month is 1 or 2 then we consider january and february
      // to be the 13th or 14th of the preceding year
      if (month < 3) {
        year -= 1;
        month += 12;
      } // if

      // if the date is in the gregorian calandar then
      if (isgregorian) {
        a = year / 100;
        b = 2 - a + (a / 4);
      } // if

      return (((365.25 * (year + 4716)) + (30.6001 * (month + 1)) +
             day + b - 1524.5));
    } // Sun::calcJulianDayNumber

    function Cal2JD(year,month,day,hour,minute,second) {
      //
      // Compute the Julian Date for a given day, month, year
      // See AFC, chapter 3.
      //
      var a = 0; var b = 0;
      var gregorian = false;

      if (month < 3) { year -= 1; month += 12; }

      // Check if date is in the Gregorian calendar.
      if (year > 1582) { gregorian = true; }
      if (year==1582)  {
        if (month > 10)              { gregorian = true; }
        if ((month==10)&&(day>=15))  { gregorian = true; }
      }
      if (gregorian==true) { a = intw(year/100); b = 2-a+intw(a/4); }

      return (parseInt(365.25 * year) + parseInt(30.6001 * (month + 1))
              + day + (hour/24) + (minute/1440) + (second/86400)
              + 1720994.5 + b);
    } // Calc2JD

    function intw(num) {
      return parseInt("0" + num,10);  // INT function (like TRUNC).
    } // intw


    function Div(a, b) {
      return ((a-a%b)/b);  //OK
    } // Div


    function Deg(n) {
      return n.toDeg();
    } // Deg

    function Radians(n) {
      return n.toRad();
    } // Radians

    Date.prototype.julianDate=function(){
      var j=parseInt((this.getTime()-new Date('Dec 30,'+(this.getFullYear()-1)+' 23:00:00').getTime())/86400000).toString(),i=3-j.length;

      while(i-->0)j=0+j;

      return j;
    }

    // This function is from Google's polyline utility.
    // Adapted to be "lat, lng, brng".
    function decodeLine (encoded) {
      var len = encoded.length;
      var index = 0;
      var array = [];
      var lat = 0;
      var lng = 0;

      while (index < len) {
        var b;
        var shift = 0;
        var result = 0;
        do {
          b = encoded.charCodeAt(index++) - 63;
          result |= (b & 0x1f) << shift;
          shift += 5;
        } while (b >= 0x20);
        var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
          b = encoded.charCodeAt(index++) - 63;
          result |= (b & 0x1f) << shift;
          shift += 5;
        } while (b >= 0x20);
        var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        shift = 0;
        result = 0;
        do {
          b = encoded.charCodeAt(index++) - 63;
          result |= (b & 0x1f) << shift;
          shift += 5;
        } while (b >= 0x20);
        var dbrng = ((result & 1) ? ~(result >> 1) : (result >> 1));
        brng += dbrng;

        array.push([lat * 1e-5, lng * 1e-5, brng * 1e-5]);
      }

      return array;
    }

    function isCoordinate(lat, lng) {
      if (lng > 180 || lng < -180)
        return false;

      if (lat > 90 || lat < -90) 
        return false;

      return true;
    } // isCoordinate
