var g_map;
var g_results = new Array();
var g_markers = new Array();
var g_popup   = new Array();
var g_lastMarkerIndex;
var g_origin_postal_code;
var g_markerColours = new Array("red", "orange", "yellow", "green", "paleblue", "blue", "purple", "pink", "brown", "darkgreen");

// create a base icon for all of our markers that specifies the shadow, icon dimensions, etc.
var baseIcon = new GIcon();
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);


/*------------------------------------------------------------------------------------------------*\ 
  Function: onPageLoad
  Purpose:  initializes the Google Map, centered on BC  
\*------------------------------------------------------------------------------------------------*/
function onPageLoad()
{
  if (GBrowserIsCompatible())
  {
    g_map = new GMap2(document.getElementById("map"));
    g_map.setCenter(new GLatLng(54.278111, -126.115307), 5); // focus on BC by default
    g_map.addControl(new GLargeMapControl());
    g_map.addControl(new GMapTypeControl());
  }
}


/*------------------------------------------------------------------------------------------------*\ 
  Function: resetMap
  Purpose:  called after a user search. Resets the map based on the geographical results of a 
            search. This function takes the top, left, bottom and right coordinates (lat & long),
            which form the the smallest rectangular box which contains all results found.            
\*------------------------------------------------------------------------------------------------*/
function resetMap(top, left, bottom, right)
{
  g_map = new GMap2(document.getElementById("map"));
  g_map.clearOverlays();

  // first, set up map
  g_map.setCenter(new GLatLng(0,0), 0);
  var sw = new GLatLng(left, bottom);
  var ne = new GLatLng(right, top);  
  var bounds = new GLatLngBounds(sw, ne);
  
  // never zoom REALLY close in, even if there's only one result
  var calculated_zoom = g_map.getBoundsZoomLevel(bounds);
  var actual_zoom = (calculated_zoom > 16) ? 16 : calculated_zoom;
  g_map.setZoom(actual_zoom);

  var center_lat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
  var center_lng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
  g_map.addControl(new GLargeMapControl());
  g_map.addControl(new GMapTypeControl());
  g_map.setCenter(new GLatLng(center_lat, center_lng));

  // now populate the sucker with the contents of g_results
  for (i=0; i<g_results.length; i++)
  {
    currMarker = _createMarker(g_results[i], i);
    g_markers.push(currMarker);
    g_map.addOverlay(currMarker);
  }
}


/*------------------------------------------------------------------------------------------------*\ 
  Function: _createMarker
  Purpose:  helper function to create a single marker on the map, complete with popup window
\*------------------------------------------------------------------------------------------------*/
function _createMarker(info, index)
{
  var colour = g_markerColours[info.marker_colour_id - 1];
  var point = new GPoint(info.x_coord, info.y_coord);
  var letter = String.fromCharCode("A".charCodeAt(0) + index);
  var icon = new GIcon(baseIcon);
  icon.image = "http://probonomap.bc.ca/images/icons/" + colour + "_Marker" + letter + ".png";
  var marker = new GMarker(point, icon);

  var location_email = (info.location_email != "") ? "Email: <a href=\"mailto:" + info.location_email + "\" class=\"gmap_link\">" + info.location_email + "</a><br />" : "Email: N/A<br />";
  var phone = (info.phone != "") ? "Phone: " + info.phone + "<br />" : "";
  var fax   = (info.fax != "") ? "Fax: " + info.fax + "<br />" : "";
  var service_restrictions = (info.service_restrictions != "") ? "<div class='gmap_section'><b>Service Restrictions:</b> " + info.service_restrictions + "</div>" : "";
  var online_booking = (info.online_booking_available == "yes" && info.website_booking_url != "") ? "<div class='gmap_section'><a href='" + info.website_booking_url + "'>Click here for online booking information</a></div>" : "";
  var website = "";
  if (info.website != "")
  {
    // check that the URL starts with http://
    var clean_website_link = info.website;
    if (!info.website.match(/http:\/\//))
      clean_website_link = "http://" + info.website;

    website = "<div class='gmap_section'><br/><b>Website:</b> <a href='" + clean_website_link + "' class=\"gmap_link\">" + info.website + "</a></div>";
  }

  // if this is an advanced search (based on zip), build a "GET DIRECTIONS TO/FROM" link. Otherwise,
  // display a form to get directions from a particular postal code
  directions_link = "";
  if (!g_origin_postal_code)
  {
    link_url = "http://maps.google.com/maps?daddr=" + info.street_address + ", " + info.city + ", " + "BC, Canada";
    directions_link = "<br /><div>GET DIRECTIONS:</div>"
           + "<div>Postal Code: <input type='text' class='gmap_textfield' size='6' maxlength='7' id='basic_postal_code_" + index + "' name='basic_postal_code_" + index + "' />"
           + "<input type='button' value='Submit' class='gmap_button' onclick='get_basic_directions(" + index + ", \"" + link_url + "\")' /></div>";
  }
  else
  {
    link_url = "http://maps.google.com/maps?saddr=" + g_origin_postal_code + "&daddr=" + info.street_address + ", " + info.city + ", " + "BC, Canada"; // info.postal_code
    directions_link = "<br /><div class='gmap_section'><a href='" + link_url + "' target='_blank'>GET DIRECTIONS</a></div>";
  }

  // generate the popup content
  var tab1_content = "<div class='gmap_tab_content'>"
                     + "<span class='gmap_organization_name'>" + info.organization_name + "</span><br/><br/>"
                     + "<span class='gmap_location_name'>" + info.location_name + "</span><br/><br/>"
                     + info.street_address + "<br/>" 
                     + info.city + "<br/>" 
                     + info.postal_code + "<br/>"
                     + location_email
                     + phone
                     + fax
                     + website
                     + directions_link
                   + "</div>";

  var tab2_content = "<div class='gmap_tab_content'>"
                     + "<div class='gmap_section'><b>Service(s) Provided:</b> " + info.services_provided + "</div>"
                     + "<div class='gmap_section'><b>Service Providers:</b> " + info.service_providers + "</div>"
                     + "<div class='gmap_section'><b>Area(s) of Law:</b> " + info.area_of_law + "</div>"
                     + "<div class='gmap_section'><b>Clientele:</b> " + info.clientele + "</div>"
                     + "<div class='gmap_section'><b>Language(s):</b> " + info.languages + "</div>"
                     + service_restrictions
                   + "</div>";

  // build the date s trings
  var date_string = ""; 
  for (k=0; k<info.date_strings.length; k++)
  {
    if (info.date_strings[k] != "")
      date_string += info.date_strings[k] + "<br />";
  }

  if (online_booking != "")
    online_booking += "<br />";
  if (date_string != "")
    date_string += "<br />";

  var tab3_content = "<div class='gmap_tab_content'>"
                     + online_booking
                     + date_string
                     + phone
                   + "</div>";

  var tab1 = new GInfoWindowTab("Main", tab1_content);
  var tab2 = new GInfoWindowTab("Services", tab2_content);
  var tab3 = new GInfoWindowTab("Times", tab3_content);

  var tabs = new Array();
  tabs.push(tab1);
  tabs.push(tab2);
  tabs.push(tab3);

  g_popup[index] = new Array(tab1_content, tab2_content, tab3_content);

  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowTabsHtml(tabs);
  });

  return marker;
}


/*------------------------------------------------------------------------------------------------*\ 
  Function: panToMarker
  Purpose:  
\*------------------------------------------------------------------------------------------------*/
function panToMarker(index)
{
  var destinationPoint = g_markers[index].getPoint();
  g_map.panTo(destinationPoint);
  g_lastMarkerIndex = index;

/*  if (!g_map.getCenter().equals(destinationPoint))
    GEvent.addListener(g_map, "moveend", _displayMarkerPopup);
  else
    _displayMarkerPopup();
    */
  _displayMarkerPopup();
}


/*------------------------------------------------------------------------------------------------*\ 
  Function: _displayMarkerPopup
  Purpose:  
\*------------------------------------------------------------------------------------------------*/
function _displayMarkerPopup()
{
  var tab1_content = g_popup[g_lastMarkerIndex][0];
  var tab2_content = g_popup[g_lastMarkerIndex][1];
  var tab3_content = g_popup[g_lastMarkerIndex][2];
  var tab1 = new GInfoWindowTab("Main", tab1_content);
  var tab2 = new GInfoWindowTab("Services", tab2_content);
  var tab3 = new GInfoWindowTab("Times", tab3_content);
  var tabs = new Array();
  tabs.push(tab1);
  tabs.push(tab2);
  tabs.push(tab3);

  g_markers[g_lastMarkerIndex].openInfoWindowTabsHtml(tabs);
  g_lastMarkerIndex = "";
}


/*------------------------------------------------------------------------------------------------*\ 
  Function: clearLastSearch
  Purpose:  called from child page. Resets the variables storing the search values. 
\*------------------------------------------------------------------------------------------------*/
function clearLastSearch()
{
  parent.g_results.length = 0;
  parent.g_markers.length = 0;
  parent.g_popup.length = 0;
}


function get_basic_directions(index, link_url)
{
  val = document.getElementById("basic_postal_code_" + index).value;

  window.location = link_url + "&saddr=" + val;
}