/*
* Extended GMaps API
*/

if (GMap2 == undefined)
{
    this.debug('Error: You must include the Google Maps API external javascript in your page with the correct key.');
}

GMap2.prototype.max_auto_zoom = 17;
GMap2.prototype.default_zoom = 13;
GMap2.prototype.zoom_level = GMap2.default_zoom;
GMap2.prototype.locations = [];
GMap2.prototype.enable_debug = false;


/**
 * GMap2::createMarker()
 */
GMap2.prototype.createMarker = function (point, info_html, icon_settings, label)
{
  if (icon_settings != null)
  {
    icon = new GIcon();
    icon.iconAnchor = G_DEFAULT_ICON.iconAnchor;
    icon.infoWindowAnchor = G_DEFAULT_ICON.infoWindowAnchor;

    for (s in icon_settings)
    {
        icon[s] = icon_settings[s];
    }

    if(icon['image'] != null)
    {
      img = new Image();
      img.src = icon['image'];
      if(img.width > 0 && img.height > 0)
      {
        icon.iconSize = new GSize(img.width, img.height);
      }
      else
      {
        icon.iconSize = new GSize(35, 42);
      }
    }
    else
    {
      icon.iconSize = G_DEFAULT_ICON.iconSize;
    }
  }
  else
  {
    icon = new GIcon(G_DEFAULT_ICON);
  }

  // --- The label parameter is not implemented for now. ---
  if(label != null)
  {
    is_center = false;
    if(icon != null)
    {
      is_center = true;
    }

    var marker = new LabeledMarker(point, {
      labelText: label,
      labelClass: 'gmap_markerlabel',
      labelCenter: is_center,
      icon: icon
      });
  }
  else
  {
    var marker = new GMarker(point, icon);
  }
  var tabs = new Array();

  for (var i=0; i<info_html.length; i++)
  {
     tabs.push(new GInfoWindowTab(info_html[i].label, info_html[i].html));
  }

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

  return marker;
}


/**
 * GMap2::addLocations()
 */
GMap2.prototype.addLocations = function (locations, auto_zoom)
{
  if (auto_zoom == null) auto_zoom = true;

  var center = this.getCenter();
  if (center == null)
  {
    this.debug("Error: Cannot add locations without a set center.");
    return false;
  }
  var bounds = this.getBounds();

  mm = new GMarkerManager(this);

  // Add each location to the designated map
  for (var i=0; i<locations.length; i++)
  {
    errors = new Array();
    if (locations[i].coordinates.lat == null) errors.push("Latitude is empty for location #");
    if (locations[i].coordinates.lng == null) errors.push("Longitude is empty for location #");
    if (errors.length > 0)
    {
        for (e=0; e<errors.length; e++)
        {
            this.debug(errors[e]);
        }
        return false;
    }

    loc = new GLatLng(locations[i].coordinates.lat,locations[i].coordinates.lng);

    if (auto_zoom == true)
    {
        if (i==0)
        {
            this.setCenter(loc, this.max_auto_zoom);
            bounds = this.getBounds();
        }
        bounds.extend(loc);
    }

    locations[i].marker = this.createMarker(loc, locations[i].info_html, locations[i].icon, locations[i].label);

    /*
    try {
      console.debug("created marker, loc=" + loc);
    }
    catch(e) {};
    */

    // Set zoom level for marker
    if (locations[i].options == null)
    {
        locations[i].options = { minZoom: 0, maxZoom: 17 };
    }
    else
    {
      if (locations[i].options.minZoom == null)
      {
        locations[i].options.minZoom = 0;
      }
      if (locations[i].options.maxZoom == null)
      {
        locations[i].options.maxZoom = 17;
      }
    }


    //this.addOverlay(locations[i].marker);
    mm.addMarker(locations[i].marker,
      locations[i].options.minZoom, locations[i].options.maxZoom);
  }


  this.locations = locations;
  mm.refresh();

  if (auto_zoom == true)
  {
    // Get the bounds zoomlevel for the current view area, and compensate for controls
    mapType = this.getCurrentMapType();
    viewSize_width = this.getSize().width - 45;
    viewSize_height = this.getSize().height - 25;
    zoom = mapType.getBoundsZoomLevel(bounds, new GSize(viewSize_width, viewSize_height));

    // make sure we aren't zoomed in to far (higher the zoom value, the more zoomed in you are)
	if (zoom > this.default_zoom) zoom = this.default_zoom;
    this.setCenter(bounds.getCenter(), zoom);
  }

}

/**
 * POI Overlay Functions  (Points of Interest Module - 12/17/2007)
 * -- for IE compatibility, this section must appear above addOverlays --
 */
function POI_Overlay(coords, title, content, image) {
    this.coords_ = coords;
    this.title_ = title;
    this.content_ = content;
    this.image_ = image;
}
POI_Overlay.prototype = new GOverlay();

// Creates the DIV representing this rectangle.
POI_Overlay.prototype.initialize = function(map) {
    
    // Create the Overlay container
    var div = document.createElement("div");
    div.style.backgroundColor = "#f9f7b3";
    div.style.border = "1px solid #888";
    div.style.position = "absolute";
    
    // Add Overlay contents
    divHTML = '<table width="" cellpadding="2"><tr>';
    if (this.image_ != null && this.image_ != '')
    {
        divHTML += '<td width="1%" valign="middle"><img class="gmaps-overlay-image" src="images/display.php?id='+this.image_+'&max_width=60&max_height=60" /></td>';
    }
    divHTML += '<td valign="middle"><div style="padding: 2px; border: 1px solid #888888;">';
    divHTML += '<span class="poi_title" id="poi_title">'+this.title_+"</span><br />";
    divHTML += '<span class="poi_content" id="poi_content">'+this.content_+"</span>";
    divHTML += '</div></td>';
    divHTML += '</tr></table>';
    div.innerHTML = divHTML;
    

    // Our rectangle is flat against the map, so we add our selves to the
    // MAP_PANE pane, which is at the same z-index as the map itself (i.e.,
    // below the marker shadows)
    map.getPane(G_MAP_MAP_PANE).appendChild(div);

    // set the max width for the parent div (css attribute doesn't work in IE6)
    var max_width = 200;
    if (div.offsetWidth > max_width)
    {        
        var spanTags = div.getElementsByTagName("span");
        
        for (var i = 0 ; i < spanTags.length ; ++i)
        {           
            var spanTag = spanTags[i];
            if (spanTag.id == "poi_title"
                || spanTag.id == "poi_content") 
            {
                spanTag.style.whiteSpace = "normal";
            }
        }
        
        // set to the max width
        div.style.width = max_width+"px";
    }
    
    this.map_ = map;
    this.div_ = div;
}

// Remove the main DIV from the map pane
POI_Overlay.prototype.remove = function() {
    this.div_.parentNode.removeChild(this.div_);
}

// Copy our data to a new Rectangle
POI_Overlay.prototype.copy = function() {
    return new POI_Overlay(this.coords_, this.title_, this.content_, this.image_, this.backgroundColor_, this.opacity_);
}

// Redraw the rectangle based on the current projection and zoom level
POI_Overlay.prototype.redraw = function(force) {
    // We only need to redraw if the coordinate system has changed
    if (!force) return;

    var pixel_coords = this.map_.fromLatLngToDivPixel(new GLatLng(this.coords_.lat,this.coords_.lng));
      
    // Now position our DIV based on the DIV coordinates of our bounds
    this.div_.style.left = (pixel_coords.x - 210)  + "px";
    this.div_.style.top = (pixel_coords.y + 5) + "px";
}

/**
 * GMap2::addOverlays()
 */
GMap2.prototype.addOverlays = function (overlays, auto_zoom)
{
  if (auto_zoom == null) auto_zoom = true;

  var center = this.getCenter();
  if (center == null)
  {
    this.debug("Error: Cannot add locations without a set center.");
    return false;
  }
  var bounds = this.getBounds();

  // Add each location to the designated map
  for (var i=0; i<overlays.length; i++)
  {
    errors = new Array();
    if (overlays[i].coordinates.lat == null) errors.push("Latitude is empty for overlay #");
    if (overlays[i].coordinates.lng == null) errors.push("Longitude is empty for overlay #");
    if (errors.length > 0)
    {
        for (e=0; e<errors.length; e++)
        {
            this.debug(errors[e]);
        }
        return false;
    }
    
    this.addOverlay(new POI_Overlay(overlays[i].coordinates, overlays[i].title, overlays[i].content, overlays[i].image));
    
  }

  this.overlays = overlays;

  if (auto_zoom == true)
  {
    // Get the bounds zoomlevel for the current view area, and compensate for controls
    mapType = this.getCurrentMapType();
    viewSize_width = this.getSize().width - 45;
    viewSize_height = this.getSize().height - 25;
    zoom = mapType.getBoundsZoomLevel(bounds, new GSize(viewSize_width, viewSize_height));

    if (zoom > this.default_zoom) zoom = this.default_zoom;
    this.setCenter(bounds.getCenter(), zoom);
  }

}


// override setCenter to use max_auto_zoom
/*
GMap2.prototype._setCenter = GMap2.prototype.setCenter;

GMap2.prototype.setCenter = function(center, zoom, type)
{
  if (zoom == null) zoom = this.max_auto_zoom;
  this._setCenter(center, zoom, type);
}
*/


/**
 * GMap2::debug()
 */
GMap2.prototype.debug = function(txt)
{
    if (this.enable_debug)
    {
        GLog.write(txt);
    }
}
