// Globals
var geocoder = null;
var detail_map = null;
var ptB = null;       // business origin
var stepdata = "";    // pipe seperated args, tab seperated steps
var directionsObj = null;  // GDirections object
var directions_enabled = false;
var fromaddress = null;

/**
 * Create a map at a coordinate.
 * @param lat Latitude
 * @param lon Longitude
 */
 function setupMap(lat,lon) {
  if (GBrowserIsCompatible()) {
    window.map = new GMap2(document.getElementById("map_canvas"));
    window.map.addControl(new GSmallMapControl());
    window.map.setCenter(new GLatLng(lat,lon), 10);
  }
}

/**
 * Google Maps unload.
 * Cleans up memory leaks in the google api.
 */
function mapsUnload() {
  if (google.maps != null) {
    google.maps.Unload();
    //alert("Google maps Unload() called");
  }
}

/**
 * Control the directions panels on the detail page.
 * @param mode Visibility mode.
 *  clear=hide both divs, show=show directions, hide=hide directions and
 *  show the 'show directions' link if directions are available.
 */
function controlDirections(mode) {
  if (mode == 'show')
    {
    document.getElementById('showDirections').style.display='none';
    document.getElementById('directions').style.display='block';
    }
  else if (mode == 'hide')
    {
    document.getElementById('showDirections').style.display='block';
    document.getElementById('directions').style.display='none';
    }
  else if (mode == 'clear')
    {
    document.getElementById('showDirections').style.display='none';
    document.getElementById('directions').style.display='none';
    }
}

/**
 * Print Coupon with driving directions.
 * cityguide_zoomcoupon.pbs template
 */
function mapsPrintCoupon(domain,id,type) {
  var site = '&site=MN';
  var moduleclass = '&module=99&class=999';
  var url = domain + '/dcce' + site + moduleclass + '&id=' + id;
  url += '&Date=20080801&type=' + type + '&category=cityguide&template=zoomcoupon';

  var printwindow = window.open(url,'print','width=600,height=600,resizable=yes,scrollbars=yes',0);
}

function openFromForm() {
  var fromdiv = document.getElementById('from');
  fromdiv.style.visibility = 'visible';
}

function onGDirectionsLoad(){ 
  // Use this function to access information about the latest load() results.
  var status = directionsObj.getStatus().code;
  if (status != 200)
    {
    alert("Directions load failed.");
    }
  return;
  /* not used... yet!
  var step;
  var latlng;
  var polyidx;
  var html;
  var dist;
  var dur;
  var route = directionsObj.getRoute(0);
  var n = route.getNumSteps();
  var j = 1;
  for(var i=0; i<n; i++) {
    step = route.getStep(i);
    latlng  = step.getLatLng();
    polyidx = step.getPolylineIndex();
    dist    = step.getDistance();  // .html
    dur     = step.getDuration();  // .html
    descr   = step.getDescriptionHtml();
    stepdata += j+'|'+descr+'\t';
    j += 1;
  }
  */
}

function geocoderCallBack(pointA) {
	if (!pointA) {
    alert("Unable to geocode this address:" + fromaddress);
  } else {
    try {
      directionsObj.load(pointA.y +","+ pointA.x +" to "+ ptB.y + "," + ptB.x);
    }
    catch(error) {
      alert(error.message);
    }
  }
}

function getDirections() {
  var routediv = document.getElementById('route');
  directionsObj = new GDirections(detail_map,routediv);
  GEvent.addListener(directionsObj, "load", onGDirectionsLoad);
  document.getElementById("directions").style.display = "block";

  // geocode the from address...
  fromaddress = document.getElementById('fromadrs').value;
  if (fromaddress == "")
    {
    alert("From address is required.");
    return;
    }
  document.getElementById('fromaddress').innerHTML = fromaddress;

  if (geocoder == null)
    {
    geocoder = new GClientGeocoder();
    }
  geocoder.getLatLng(fromaddress,geocoderCallBack);

  detail_map.closeInfoWindow();
}

/**
 * Create a map for the detail page.
 * @param canvas The map_canvas element
 * @param lat Latitude
 * @param lng Longitude
 * @param title Company name.
 * @param dd_flag Driving Directions flag.
 */
function createDetailMap(canvas,lat,lng,title,dd_flag)
  {
  var zoom = 14;
  if (GBrowserIsCompatible())
    {
    var map = new GMap2(canvas);
    detail_map = map;
    directions_enabled = dd_flag;
    var bubbleHtml = "";

    if (dd_flag)
      {
      bubbleHtml = '<div style="font-size:.8em;">';
      bubbleHtml += '<span style="font-size:.9em;">' + title + '</span>';
      bubbleHtml += '<br> <a href="#" onclick="openFromForm();">';
      bubbleHtml += 'Get Directions</a>&nbsp to this business.';
      bubbleHtml += '<br>';
      bubbleHtml += '<div id="from" style="font-size:.8em;visibility:hidden;">';
      bubbleHtml += 'From:&nbsp;<input type=text id="fromadrs" size=30 />';
      bubbleHtml += '&nbsp;&nbsp;<input type=button value="Go" style="font-size:11px;" onclick="getDirections();" /></div>';
      bubbleHtml += '</div>';
      }


    $(document).ready(function(){
      if (dd_flag)
        {
        map.openInfoWindowHtml(ptB,bubbleHtml);
        }
      else {
        //map.openInfoWindowHtml(ptB,title);
      }
     });

    ptB = new GLatLng(lat,lng);
    map.setCenter(ptB,zoom);
    var markerB = new GMarker(ptB);
    map.addOverlay(markerB);
    var mapControl = new GMapTypeControl();
    map.addControl(mapControl);
    map.addControl(new GSmallMapControl());
    GEvent.addListener(markerB, "click", function()
      {
      if (dd_flag)
        {
        map.openInfoWindowHtml(ptB,bubbleHtml);
        }
      else {
        map.openInfoWindowHtml(ptB,title);
      }
      });
    }
  }
