var map;
var marker_manager;
var batch = [];
var geocoder;
var data;
var lockZoom = false;

//origin
var lat1;
var lon1;
// destination
var lat2;
var lon2;

// array indexes
var a_airport 	= 0;
var a_trunc 	= 1;
var a_lat 		= 2;
var a_lng 		= 3;
var a_code 		= 4;
var a_mode 		= 5;
var a_obj 		= 6;

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Fixed the array problem
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

var markerData = new Array();
// arrays to store marker data
markerData[a_airport] = new Array();
markerData[a_trunc] = new Array();
markerData[a_lat] = new Array();
markerData[a_lng] = new Array();
markerData[a_code] = new Array();
markerData[a_mode] = new Array();
markerData[a_obj] = new Array();

// this is for selected markers
// so we can restore the selection
// if the map moves
var markerSelections = new Array();
markerSelections[a_airport] = new Array();
markerSelections[a_trunc] = new Array();
markerSelections[a_lat] = new Array();
markerSelections[a_lng] = new Array();
markerSelections[a_code] = new Array();
markerSelections[a_mode] = new Array();
markerSelections[a_obj] = new Array();

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

// This is defined at initialization in the layout
// through the default controller
//var country_code;

function initialize() {
  if (GBrowserIsCompatible()) {
  	geocoder = new GClientGeocoder();
    map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(userLat, userLng), userZoom);
    country_code = "GB";
    map.setUIToDefault();
    map.setMapType(G_PHYSICAL_MAP);
    map.enableContinuousZoom();
    map.disableScrollWheelZoom();
 
    
    //marker_manager = new MarkerManager(map);
    showCountryAirports();
    
    GEvent.addListener(map, "click", function(marker, point){
     	// only if it's an airport marker
     	if(marker.number || marker.number === 0){ 
     	// -  -  -  -  -  -  -  -  -  -  -  -  -  -  - 
     		if(!markerData[a_mode][marker.number]){
    		// this marker hasn't been clicked yet
    		selectMarker(marker);
	    	}else{
	    		deselectMarker(marker);
	    	}
     	// -  -  -  -  -  -  -  -  -  -  -  -  -  -  - 	
     	}
     	
      	
    });
    
    // Double click to show countries
    // -------------------------------------------------------------
    GEvent.addListener(map, "singlerightclick", function(point, src, overlay){ 
    	lockZoom = true;
    	showAddress(map.fromContainerPixelToLatLng(point));
    });
    
  }
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function selectMarker(marker){
	addToList(marker.number);
  	var marker_image = (mode == "leaving") ? "marker_up.png" : "marker_down.png";
	marker.setImage("/images/" + marker_image);
	markerData[a_mode][marker.number] = mode;
	
	// using push
	markerSelections[a_airport].push(markerData[a_airport][marker.number]);
	markerSelections[a_trunc].push(markerData[a_trunc][marker.number]);
	markerSelections[a_lat].push(markerData[a_lat][marker.number]);
	markerSelections[a_lng].push(markerData[a_lng][marker.number]);
	markerSelections[a_code].push(markerData[a_code][marker.number]);
	markerSelections[a_mode].push(markerData[a_mode][marker.number]);
	markerSelections[a_obj].push(marker);	
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function deselectMarker(marker){
	// change icon
	marker.setImage("images/marker_default.png");
    //	markerData[a_mode][marker.number] = false;
    // remove from list
    var list_item = "#" + markerData[a_code][marker.number];
    $(list_item).remove();
	
	var index = markerSelections[a_airport].contains(markerData[a_airport][marker.number]);
	
	markerSelections[a_airport].splice(index, 1);
	markerSelections[a_trunc].splice(index, 1);
	markerSelections[a_lat].splice(index, 1);
	markerSelections[a_lng].splice(index, 1);
	markerSelections[a_code].splice(index, 1);
	markerSelections[a_mode].splice(index, 1);
	markerSelections[a_obj].splice(index, 1);  
	markerData[a_mode][marker.number] = "";  
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function showAddress(address) {
	stopThinking();
	startThinking()
	geocoder.getLocations( address, moveMapTo );
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function moveMapTo(response) {

  var current_country = country_code;
  if (!response || response.Status.code != 200) {
    alert("\"" + address + "\" not found");
  } else {
    place = response.Placemark[0];
    //country_code = place.AddressDetails.Country.CountryNameCode;
    updateCacheCountryValues(place.AddressDetails.Country.CountryNameCode);
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
     
              
    $("#search_string").attr("value", place.address);
    
    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    // update coordinates for the midpoint calculation among other things
    if(mode == "leaving"){
    	lat1 = point.y;
    	lon1 = point.x;
    }else if (mode == "going_to"){
    	lat2 = point.y;
    	lon2 = point.x;
    }
    
    // OK: If the user right clicks the map, we don't want
    // to change the zoom level as it would be disorientating
    if(lockZoom == true){
    	 map.setCenter(point, map.getZoom());
    	 lockZoom = false;
    }else{
    	 map.setCenter(point, 9);
    }
    
   	showCountryAirports(current_country);
   	showOriginDestination();
    
  }
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function showCountryAirports(){
		// we're moving to a different country!
		// Perhaps this should account for movement when
		// the country hasn't changed. To save some 
		// CPU usage. 
		map.clearOverlays();
		//alert("/ajax/getCountryAirportsJson/" + leaving_cache[3] +"/"+ going_to_cache[3] +"/"+ generateSelectedString(), displayMarkers);
		$.getJSON("/ajax/getCountryAirportsJson/" + leaving_cache[3] +"/"+ going_to_cache[3] +"/"+ generateSelectedString(), displayMarkers);
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function generateSelectedString(){
	var string = "";
	for(var x = 0; x < markerSelections[a_airport].length; x++){

		string += markerSelections[a_code][x] + "-";

	}
	return string;
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function displayMarkers(data){
	var i = 0;
	
	// we need to remember which markers have been selected
	// so compare the number and the code. If it's the same
	// simply update it, if it's different, we need to add another. 
	
	for(i = 0; i < data.Lat.length - 1; i++){
				
		// Put the data for each marker in Assoc Array
		var point = new GLatLng(data.Lat[i],data.Lng[i]);
		var markerObject = createMarker(point, i);
		
		markerData[a_airport][i] 		= data.Name[i];
		markerData[a_trunc][i] 			= data.TruncName[i];
		markerData[a_lat][i] 			= data.Lat[i];
		markerData[a_lng][i] 			= data.Lng[i];
		markerData[a_code][i] 			= data.Code[i];
		markerData[a_obj][i]			= markerObject;
		
		map.addOverlay(markerObject);
		
		// has the marker been selected
		if(data.Selected[i] == 1){
			// yes it has
			
			var markerSIndex = markerSelections[a_code].contains(data.Code[i]);
		
			// is it a leaving_to marker
			if(markerSelections[a_mode][markerSIndex] == "leaving"){
				markerObject.setImage("/images/marker_up.png");
			}else{
				markerObject.setImage("/images/marker_down.png");
			}
			
			
		}
		
	}	
	stopThinking();
	
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-


function createMarker(latlng,i) {
      var marker = new GMarker(latlng);
      
      marker.number = i;
      
      GEvent.addListener(marker, "mouseover", function(){
      	airportHint(markerData[a_trunc][marker.number]);
      });
      
      GEvent.addListener(marker, "mouseout", function(){
      	removeAirportHint();
      });
      
      return marker;
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function airportHint(airportName){
	$(".airport_hint").stop();
	$(".airport_list").css("padding-top", "0px");
	$(".airport_hint").remove();
	var hint = "<p class='airport_hint'<span>"+airportName+"</span></p>"
	$(".airport_list").prepend(hint);
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function removeAirportHint(){
	$(".airport_hint").fadeOut("fast", function(){
		$(".airport_list").css("padding-top", "20px");
		$(".airport_list").css("height", "329px");
		$(".airport_list").animate({ 
	        paddingTop: "0px",
	        height: "347px"
	      }, 100 );
	});
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function addToList(number){
	
	$(".airport_hint").remove();
	
	// this way, the element jumps back to the
	// top of the list, and then flashes
	var dupe = 0;
	var thisMarker = "#"+markerData[a_code][number];
	if($(thisMarker).length > 0){
		dupe = 1;
	}
	
	// remove the text tip
	if(mode == "leaving"){
		$("#leaving_airports .tip").remove();
		var tag = airportListItem(number);
		$("#leaving_airports").prepend(tag);
	}else{
		$("#going_to_airports .tip").remove();
		var tag = airportListItem(number);
		$("#going_to_airports").prepend(tag);
	}
	
	// Delete button funcitonality
	$(thisMarker+(" .delete")).click(function(){
		$(thisMarker).remove();	
		deselectMarker(markerData[a_obj][number]);
	})
	
	// infor button functionality
	$(thisMarker+(" .info")).click(function(){
		map.setCenter(new GLatLng(markerData[a_lat][number], markerData[a_lng][number]), 13);	
	})
	
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function airportListItem(number){
	var thisMarker = "#"+markerData[a_code][number];
	$(thisMarker).remove();
	//var airport = "<p class='airport' id='"+markerData[a_code][number]+"'><span class='meta'><span class='airport_name'>"+markerData[a_trunc][number]+"</span><a class='icon delete' href='#remove'><span>Remove</span></a><a class='icon info' href='#info'><span>Info</span><span></a></p>";
	var airport = "<p class='airport' id='"+markerData[a_code][number]+"'><span class='meta'><span class='airport_name'>"+markerData[a_trunc][number]+"</span><a class='icon delete' href='#remove'><span>Remove</span></a></span></p>";
	//alert(airport);
	return airport;
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function updateCacheCountryValues(code){
	if(mode == "leaving"){
		leaving_cache[3] = code;
	}else{
		going_to_cache[3] = code;
	}
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function showOriginDestination(){
	// add the origins and arrival markers 
	if(lat1 && lat1 != userLat) {
		var originMarker = new GMarker(new GLatLng(lat1, lon1));
		map.addOverlay(originMarker);
		originMarker.setImage("/images/origin_marker.png");
	}
	

	if (lat2){
		var destinationMarker = new GMarker(new GLatLng(lat2, lon2));
		map.addOverlay(destinationMarker);
		destinationMarker.setImage("/images/destination_marker.png");
	}
}


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */


// Complicated Map Calculations Below: DO NOT TOUCH!

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */







// -------------------------------------------------------------------------------------

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/*  Latitude/longitude spherical geodesy formulae & scripts (c) Chris Veness 2002-2009            */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

/*
 * Use Haversine formula to Calculate distance (in km) between two points specified by 
 * latitude/longitude (in numeric degrees)
 *
 * from: Haversine formula - R. W. Sinnott, "Virtues of the Haversine",
 *       Sky and Telescope, vol 68, no 2, 1984
 *       http://www.census.gov/cgi-bin/geo/gisfaq?Q5.1
 *
 * example usage from form:
 *   result.value = LatLon.distHaversine(lat1.value.parseDeg(), long1.value.parseDeg(), 
 *                                       lat2.value.parseDeg(), long2.value.parseDeg());
 * where lat1, long1, lat2, long2, and result are form fields
 */
LatLon.distHaversine = function(lat1, lon1, lat2, lon2) {
  var R = 6371; // earth's mean radius in km
  var dLat = (lat2-lat1).toRad();
  var dLon = (lon2-lon1).toRad();
  lat1 = lat1.toRad(), lat2 = lat2.toRad();

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(lat1) * Math.cos(lat2) * 
          Math.sin(dLon/2) * Math.sin(dLon/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
  return d;
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

/*
 * Use Law of Cosines to calculate distance (in km) between two points specified by latitude/longitude 
 * (in numeric degrees).
 */
LatLon.distCosineLaw = function(lat1, lon1, lat2, lon2) {
  var R = 6371; // earth's mean radius in km
  var d = Math.acos(Math.sin(lat1.toRad())*Math.sin(lat2.toRad()) +
                    Math.cos(lat1.toRad())*Math.cos(lat2.toRad())*Math.cos((lon2-lon1).toRad())) * R;
  return d;
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
/*
 * 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 midpoint of great circle line between p1 & p2.
 *   see http://mathforum.org/library/drmath/view/51822.html for derivation
 */
LatLon.midPoint = function(lat1, lon1, lat2, lon2) {
  lat1 = lat1.toRad(); 
  lat2 = lat2.toRad();
  var dLon = (lon2-lon1).toRad();

  var Bx = Math.cos(lat2) * Math.cos(dLon);
  var By = Math.cos(lat2) * Math.sin(dLon);

  lat3 = Math.atan2(Math.sin(lat1)+Math.sin(lat2),
                    Math.sqrt((Math.cos(lat1)+Bx)*(Math.cos(lat1)+Bx) + By*By ) );
  lon3 = lon1.toRad() + Math.atan2(By, Math.cos(lat1) + Bx);

  if (isNaN(lat3) || isNaN(lon3)) return null;
  return new LatLon(lat3.toDeg(), lon3.toDeg());
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
/*
 * calculate destination point given start point, initial bearing (deg) and distance (km)
 *   see http://williams.best.vwh.net/avform.htm#LL
 */
LatLon.prototype.destPoint = function(brng, d) {
  var R = 6371; // earth's mean radius in km
  var lat1 = this.lat.toRad(), lon1 = this.lon.toRad();
  brng = brng.toRad();

  var lat2 = Math.asin( Math.sin(lat1)*Math.cos(d/R) + 
                        Math.cos(lat1)*Math.sin(d/R)*Math.cos(brng) );
  var lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(lat1), 
                               Math.cos(d/R)-Math.sin(lat1)*Math.sin(lat2));
  lon2 = (lon2+Math.PI)%(2*Math.PI) - Math.PI;  // normalise to -180...+180

  if (isNaN(lat2) || isNaN(lon2)) return null;
  return new LatLon(lat2.toDeg(), lon2.toDeg());
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
/*
 * calculate final bearing arriving at destination point given start point, initial bearing and distance
 */
LatLon.prototype.finalBrng = function(brng, d) {
  var p1 = this, p2 = p1.destPoint(brng, d);
  // get reverse bearing point 2 to point 1
  var rev = LatLon.bearing(p2.lat, p2.lon, p1.lat, p1.lon);
  // & reverse it by adding 180°
  var brng = (rev + 180) % 360;
  return brng;
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
/*
 * calculate distance, bearing, destination point on rhumb line
 *   see http://williams.best.vwh.net/avform.htm#Rhumb
 */
LatLon.distRhumb = function(lat1, lon1, lat2, lon2) {
  var R = 6371; // earth's mean radius in km
  var dLat = (lat2-lat1).toRad(), dLon = Math.abs(lon2-lon1).toRad();
  var dPhi = Math.log(Math.tan(lat2.toRad()/2+Math.PI/4)/Math.tan(lat1.toRad()/2+Math.PI/4));
  var q = (Math.abs(dLat) > 1e-10) ? dLat/dPhi : Math.cos(lat1.toRad());
  // if dLon over 180° take shorter rhumb across 180° meridian:
  if (dLon > Math.PI) dLon = 2*Math.PI - dLon;
  var d = Math.sqrt(dLat*dLat + q*q*dLon*dLon); 
  return d * R;
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

LatLon.brngRhumb = function(lat1, lon1, lat2, lon2) {
  var dLon = (lon2-lon1).toRad();
  var dPhi = Math.log(Math.tan(lat2.toRad()/2+Math.PI/4)/Math.tan(lat1.toRad()/2+Math.PI/4));
  if (Math.abs(dLon) > Math.PI) dLon = dLon>0 ? -(2*Math.PI-dLon) : (2*Math.PI+dLon);
  return Math.atan2(dLon, dPhi).toBrng();
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

LatLon.prototype.destPointRhumb = function(brng, dist) {
  var R = 6371; // earth's mean radius in km
  var d = parseFloat(dist)/R;  
  // d = angular distance covered on earth's surface
  var lat1 = this.lat.toRad(), lon1 = this.lon.toRad();
  brng = brng.toRad();

  var lat2 = lat1 + d*Math.cos(brng);
  var dLat = lat2-lat1;
  var dPhi = Math.log(Math.tan(lat2/2+Math.PI/4)/Math.tan(lat1/2+Math.PI/4));
  var q = (Math.abs(dLat) > 1e-10) ? dLat/dPhi : Math.cos(lat1);
  var dLon = d*Math.sin(brng)/q;
  // check for some daft bugger going past the pole
  if (Math.abs(lat2) > Math.PI/2) lat2 = lat2>0 ? Math.PI-lat2 : -(Math.PI-lat2);
  lon2 = (lon1+dLon+Math.PI)%(2*Math.PI) - Math.PI;
 
  if (isNaN(lat2) || isNaN(lon2)) return null;
  return new LatLon(lat2.toDeg(), lon2.toDeg());
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
/*
 * 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();
}

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// 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).

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;
}

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


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

Number.prototype.toDMS = function() {  // convert numeric degrees to deg/min/sec
  var d = Math.abs(this);  // (unsigned result ready for appending compass dir'n)
  d += 1/7200;  // add ½ second for rounding
  var deg = Math.floor(d);
  var min = Math.floor((d-deg)*60);
  var sec = Math.floor((d-deg-min/60)*3600);
  // 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() {  // convert numeric degrees to deg/min/sec latitude
  return this.toDMS().slice(1) + (this<0 ? 'S' : 'N');  // knock off initial '0' for lat!
}

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

Number.prototype.toPrecision = function(fig) {  // override toPrecision method with one which displays 
  if (this == 0) return 0;                      // trailing zeros in place of exponential notation
  var scale = Math.ceil(Math.log(this)*Math.LOG10E);
  var mult = Math.pow(10, fig-scale);
  return Math.round(this*mult)/mult;
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

		