
var map;
var startMarker;
var stopMarker;
var flightPath;

function initialize() {
  var centerLatLng = new google.maps.LatLng(centerLat, centerLon);
  var zeroLatLng = new google.maps.LatLng(0.0, 0.0);

  var mapOptions = {
    zoom: 4,
    center: centerLatLng,
    mapTypeId: mapType,
    disableDoubleClickZoom: true,
    streetViewControl: false
  };

  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
 
  var adUnitDiv = document.createElement('div');
  var adUnitOptions = {
    format: google.maps.adsense.AdFormat.VERTICAL_BANNER,
    position: google.maps.ControlPosition.RIGHT_BOTTOM,
    map: map,
    visible: true,
    publisherId: 'pub-8466955175431017'
  }

  adUnit = new google.maps.adsense.AdUnit(adUnitDiv, adUnitOptions);
  
  flightPath = new google.maps.Polyline({
    path: flightPlanCoordinates,
    strokeColor: "#CC0000",
    strokeOpacity: 0.6,
    strokeWeight: 5,
    clickable: false
  });

  flightPath.setMap(map);

  var pathLength = flightPath.getPath().getLength();
  var startLatLng = (pathLength) ? flightPath.getPath().getAt(0) : zeroLatLng;
  var stopLatLng  = (pathLength) ? flightPath.getPath().getAt(pathLength - 1) : zeroLatLng;

  startMarker = new google.maps.Marker({
      position: startLatLng,
      map: map,
      title: "Start",
      visible: (pathLength > 0),
      icon: "http://www.google.com/mapfiles/dd-start.png"
  });

  stopMarker = new google.maps.Marker({
      position: stopLatLng,
      map: map,
      title: "Stop",
      visible: (pathLength > 1),
      icon: "http://www.google.com/mapfiles/dd-end.png"
  });

  if(pathLength > 1) {
    // create a new viewpoint bound
    var bounds = new google.maps.LatLngBounds(centerLatLng, centerLatLng);

    // go through each...
    for (var i = 0; i < pathLength; i++) {
      // and increase the bounds to take this point
      bounds.extend(flightPath.getPath().getAt(i));
    }

    // fit these bounds to the map
    map.fitBounds(bounds);
  }
  google.maps.event.addListener(map, 'click', clickHandler);
  google.maps.event.addListener(map, 'dragend', dragendHandler);

  updateDistanceMetrics(flightPath.getPath());
}

function clickHandler(mEvent)
{
  flightPath.getPath().push(mEvent.latLng);
  updateRoute();
}

function dragendHandler()
{
  centerLat = map.getCenter().lat();
  centerLon = map.getCenter().lng();
  //alert(map.getZoom());
}

function undo()
{
  flightPath.getPath().pop();
  updateRoute();
}

function updateRoute()
{
  var pathLength = flightPath.getPath().getLength();
  startMarker.setVisible(pathLength > 0);
  stopMarker.setVisible(pathLength > 1);

  if (pathLength > 0) {
    startMarker.setPosition(flightPath.getPath().getAt(0));

    if (pathLength > 1) {
      var stopLatLng = flightPath.getPath().getAt(pathLength - 1);
      stopMarker.setPosition(stopLatLng);
    }
  }

  document.getElementById('hyperlinkDisplay').innerHTML = "";
  updateDistanceMetrics(flightPath.getPath());
}

function updateDistanceMetrics(path)
{
  var KM_TO_MI = 0.621371192;
  var KM_TO_FT = 3280.8399;
  var distKm = 0;

  for (var i=0;i<path.getLength()-1;i++)
    distKm += calculateDistance(path.getAt(i), path.getAt(i+1));

  if (path.getLength() == 0) {
    document.getElementById('miles').value = "";
    document.getElementById('kilometers').value = "";
    document.getElementById('feet').value = "";
    document.getElementById('waypoints').value = "";
  }
  else {
    var decimalPlaces = (distKm > 1000) ? 0 : 2;

    document.getElementById('kilometers').value =
      addCommas(distKm.toFixed(decimalPlaces));
    document.getElementById('miles').value =
      addCommas((distKm * KM_TO_MI).toFixed(decimalPlaces));
    document.getElementById('feet').value =
      addCommas((distKm * KM_TO_FT).toFixed(0));
    document.getElementById('waypoints').value = addCommas(path.getLength());
  }

  document.getElementById('waypoints').style.color =
    (path.getLength() > 500) ? "#f00" : "#000";
}

function createHyperlink()
{
  var clat = map.getCenter().lat();
  var clon = map.getCenter().lng();
  var zoom = map.getZoom();
  var type = map.getMapTypeId();

  var theURL = "service.createhyperlink.php?";
  var args = "";

  for(var i=0;i<flightPath.getPath().getLength();i++) {
    args += "pts[]=" + encode(flightPath.getPath().getAt(i)) + "&";
  }

  args += "clat=" + encode(clat) + "&clon=" + encode(clon) + "&zm=" + encode(zoom);

  if (type == google.maps.MapTypeId.ROADMAP)
    args += "&type=Map";
  else if (type == google.maps.MapTypeId.HYBRID)
    args += "&type=Hybrid";
  else
    args += "&type=Satellite";
  //alert(args);
  loadXMLDoc("service.createhyperlink.php", args, processHyperlinkRequest);

  //document.getElementById("geoResults").innerHTML = theURL;
  //document.getElementById("geoResults").style.visibility = 'visible';
}

/*
* Calculate distance (in km) between two points specified by latitude/longitude
* using law of cosines.
*/
function calculateDistance(p1, p2)
{
  if (p1.lat() == p2.lat() && p1.lng() == p2.lng())
    return 0;

  var R = 6371; // earth's mean radius in km
  var p1Lat = toRadians(p1.lat());
  var p2Lat = toRadians(p2.lat());
  var p1Lon = toRadians(p1.lng());
  var p2Lon = toRadians(p2.lng());

  var d = Math.acos(Math.sin(p1Lat) * Math.sin(p2Lat) + Math.cos(p1Lat)
    * Math.cos(p2Lat) * Math.cos(p2Lon - p1Lon)) * R;
  return d;
}

function toRadians(deg)
{
  return deg * Math.PI / 180;
}

function addCommas(nStr)
{
  nStr += '';
  var x = nStr.split('.');
  var x1 = x[0];
  var x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

function clearRoute()
{
  if (flightPath.getPath().getLength() != 0) {
    if (!confirm("Are you sure you want to start over?"))
      return;
  }

  flightPath.getPath().clear()
  startMarker.setVisible(false);
  stopMarker.setVisible(false);

  document.getElementById('hyperlinkDisplay').innerHTML = "";
  document.getElementById('miles').value = "";
  document.getElementById('kilometers').value = "";
  document.getElementById('feet').value = "";
  document.getElementById('waypoints').value = "";
  document.getElementById('locationSearchTextBox').value = "";

  clearResults();
}

function GeoCode(address)
{
  if (trim(address) == '') {
    return;
  }

  loadXMLDoc("service.geocode.php", "address=" + encode(address),
    processGeoCodeRequest);
}

function popup(url)
{
  popupwin = window.open(url,
    "mywindow","resizable=1,status=1,scrollbars=0,width=465,height=475");
}

