// Zoom Additions
// --------------
function frameLayer(map, layer) {
  var minX, maxX, minY, maxY, size
  
  if (!layer) return 
  
  for (var i = 0; i < layer.length; i++) {
    var overlay = layer[i]
    // This will frame polylines
    if (( overlay._polygon ) && (overlay._polygon.getVertexCount()) ) {
      for (var j = 0; j < overlay._polygon.getVertexCount(); j++) {
        var x = overlay._polygon.getVertex(j).x
        var y = overlay._polygon.getVertex(j).y
        
        if (minX == null || x < minX) minX = x
        if (maxX == null || x > maxX) maxX = x
        if (minY == null || y < minY) minY = y
        if (maxY == null || y > maxY) maxY = y
      }
    }
    else {  
      var x = overlay.getPoint().x
      var y = overlay.getPoint().y
    
      if (minX == null || x < minX) minX = x
      if (maxX == null || x > maxX) maxX = x
      if (minY == null || y < minY) minY = y
      if (maxY == null || y > maxY) maxY = y
    }
  }

  var centerPoint = new GLatLng((minY + maxY) / 2, (minX + maxX) / 2);
  var sw = new GLatLng(maxY, minX)
  var ne = new GLatLng(minY, maxX)
  
  var zoom = map.getBoundsZoomLevel(new GLatLngBounds(sw, ne));
  map.setCenter(centerPoint, zoom);
}

function removeLayer(map, layer_name) {
  var layer = map._layers[layer_name]
  for (var i in layer) {
    map.removeOverlay(layer[i])
  }

  map._layers[layer_name] = []
}

function mapCenterToPolygon(map,polygon) {
  var lng = polygon.getCenter().lng();
  var lat =  polygon.getCenter().lat();
  cp = new GLatLng(lng,lat);
  console.log("lng is " + lng + " and lat is " + lat + " and cp is " + cp)
  polygon.setCenter(cp)
}

// StatusBar
// ---------
function setStatus(map, message){  
  var statusElement = document.getElementById(map._name + "_status")
  
  if (message && message.length > 0){
    statusElement.innerHTML = message
    statusElement.style.display = "inline"
  }
  else {
    statusElement.style.display = "none"
  }
}   

// Tooltip
// -------
function showTooltip(marker, html) {        
  var tooltipElement = $('map_tooltip')

  tooltipElement.innerHTML = html
  
  var position = getWindowAnchor(marker, tooltipElement)

  tooltipElement.style.left = (position.x) + 'px'
  tooltipElement.style.top = (position.y) + 'px'

  Element.show(tooltipElement)

  if (! marker._tooltipHider) {
    GEvent.addListener(marker, 'mouseout', function() {hideTooltip()})
    GEvent.addListener(marker, 'mousedown', function() {hideTooltip()})
    marker._tooltipHider = true
  }
}

function hideTooltip() {
  Element.hide($('map_tooltip'))
}

// Info Window
// -----------
function showInfoWindow(marker, html) { 
  hideTooltip() // Just do this first...

  var infoWindowElement = $('map_info_window')
  var infoWindowContentElement = $('map_info_window_content')
  var infoWindowCloseElement = $('map_info_window_close')

  infoWindowContentElement.innerHTML = html
  infoWindowElement.style.opacity = 0
  Element.show(infoWindowElement)

  var position = getWindowAnchor(marker, infoWindowContentElement)
  infoWindowElement.style.opacity = null

  infoWindowElement.style.left = (position.x) + 'px'
  infoWindowElement.style.top = (position.y) + 'px'
}

function updateInfoWindow(html) {
  $('map_info_window_content').innerHTML = html
}

function hideInfoWindow() {
  Element.hide($('map_info_window'))
}

function dynamicInfoWindow(marker, uri) {
  Ajax._currentRequests = Ajax._currentRequests || {}
  
  if (Ajax._currentRequests.infoWindow) Ajax._currentRequests.infoWindow.transport.abort() // Cancel any previous requests!
  
  showInfoWindow(marker, "<div class='map_info_window_loading'>Downloading Information...</div>")
  
  Ajax._currentRequests.infoWindow = new Ajax.Request(uri, 
                   { method: 'get',
                     onComplete: function(response) {
                      updateInfoWindow(response.responseText)
                     },
                     onFailure: function() {
                      alert("Ajax Error")
                     }
                   })          
}

// Misc Functions
// --------------
function getWindowAnchor(marker, element) {
  var padding = 5
  var markerPoint = marker._map.fromLatLngToDivPixel(marker.getPoint())
  
  var nw = new GLatLng(marker._map.getBounds().getNorthEast().y, marker._map.getBounds().getSouthWest().x)        
  var mapPoint = marker._map.fromLatLngToDivPixel(nw)
  
  var xOffset = 0
  var yOffset = 0
  var icon
  if (icon = marker.getIcon && marker.getIcon()) {
    xOffset = -icon.iconAnchor.x + marker.getIcon().infoWindowAnchor.x + padding
    yOffset = -icon.iconAnchor.y + marker.getIcon().infoWindowAnchor.y
  }
  
  var x = Position.cumulativeOffset(marker._map.getContainer())[0] + markerPoint.x - mapPoint.x + xOffset
  var y = Position.cumulativeOffset(marker._map.getContainer())[1] + markerPoint.y - mapPoint.y + yOffset      
  
  // We have an overflow, toggle x to be on the other side
  if (x + Element.getDimensions(element).width >= (window.innerWidth || document.documentElement.clientWidth)) {
    x = x - Element.getDimensions(element).width - (2 * xOffset)
  }       
  
  return {x : x, y : y}
}

// Street View functions

STREET_VIEW = false;

function toggleStreetView(sender) {
  if (STREET_VIEW) {
    $('map_streetview').style.display = 'none';
    $('map').style.display = 'block';
    $(sender).innerHTML = 'Street View';
  } else {
    $('map').style.display = 'none';
    $('map_streetview').style.display = 'block'
    $(sender).innerHTML = 'Map View';
    setTimeout("pano.checkResize()", 5);
  }
  STREET_VIEW = !STREET_VIEW;
}

function openGMaps(q) {
	window.open("http://maps.google.com/maps?q=" + escape(q) + "&oe=utf-8um=1&ie=UTF-8&oi=geocode_result&ct=title&resnum=1&z=19");
}

function updateMap(map, uri, options, ajaxCallbacks) {
  options = Object.extend({
    updateDelay : 250,
    xUpdateThreshold: 0.33,
    yUpdateThreshold: 0.33
  }, options || {})
  
  if (map._savedMapCenter) {
    // If we have zoom zoomed, then update
    if (map._savedMapZoom == map.getZoom()) {
      // If we haven't moved the map far enough, then just ignore this move
      var mapCenter = map.getCenter()

      var xDelta = mapCenter.x - map._savedMapCenter.x
      var yDelta = mapCenter.y - map._savedMapCenter.y
      var bounds = map.getBounds().toSpan()

      if (Math.abs(xDelta) < (bounds.lng() * options.xUpdateThreshold) && Math.abs(yDelta) < (bounds.lat() * options.yUpdateThreshold)) {
        return
      }
    }
  }
  
  map._savedMapCenter = null
  map._savedMapZoom = null
  cancelUpdateMap(map)           
  
  var parameters = "name=" + map._name + "&" + 
                   "map[lon_min]=" + map.getBounds().getSouthWest().x + "&" +
                   "map[lon_max]=" + map.getBounds().getNorthEast().x + "&" +
                   "map[lat_min]=" + map.getBounds().getSouthWest().y + "&" +
                   "map[lat_max]=" + map.getBounds().getNorthEast().y + "&" +
                   "map[map_width]=" + map.getSize().width + "&" +
                   "map[map_height]=" + map.getSize().height + "&" +
                   "map[zoom]=" + map.getZoom()

  setStatus(map, "<blink>Loading...</blink>")

  ajax_options = {
    method: 'get',
    parameters: parameters,
    onComplete: function(response) {
      setStatus(map, "")
      if (response.responseText.length > 0) {                  
        // Save the new map center, unless this was an aborted request
        map._savedMapCenter = map.getCenter()
        map._savedMapZoom = map.getZoom()
        if (ajaxCallbacks.onComplete) ajaxCallbacks.onComplete()
      }
    },
    onFailure: function() {
      alert("Ajax Error")
    }
  }

  map._updateRequestTimeoutID = window.setTimeout(function() { map._updateRequest = new Ajax.Request(uri, ajax_options) }, options.updateDelay)
}   

function cancelUpdateMap(map) {
  if (map._updateRequest) {
    // Cancel any previous requests!
    map._updateRequest.transport.abort()
  }

  window.clearTimeout(map._updateRequestTimeoutID)
  setStatus(map, "")
}

function XPolygon(points, strokeColor, strokeWeight, strokeOpacity, fillColor, fillOpacity, options) {
  this._points = points;
  this._strokeColor = strokeColor;
  this._strokeWeight = strokeWeight;
  this._strokeOpacity = strokeOpacity;
  this._fillColor = fillColor;
  this._fillOpacity = fillOpacity;
  this._options = options || {};
}
XPolygon.prototype = new GOverlay();

var XPolygonIDCount = 0;
var XPolygonLabelDiv = null;
var XPolygonLabelShadowDiv = null;

XPolygon.prototype.initialize = function(map) {
  this._map = map;

  if (!XPolygonLabelDiv) {
    XPolygonLabelDiv = document.createElement("div");
    XPolygonLabelDiv.style.position = "absolute";
    XPolygonLabelDiv.style.display = "none";
    XPolygonLabelDiv.style.textAlign = "center";
    XPolygonLabelDiv.style.width = "200px";
    XPolygonLabelDiv.style.zIndex = 101;
    XPolygonLabelDiv.className = "map_polygon_label"
    XPolygonLabelDiv.innerHTML = "";
    this._map.getPane(G_MAP_MARKER_PANE).appendChild(XPolygonLabelDiv);
    
    XPolygonLabelShadowDiv = document.createElement("div");
    XPolygonLabelShadowDiv.style.position = "absolute";
    XPolygonLabelShadowDiv.style.display = "none";
    XPolygonLabelShadowDiv.style.textAlign = "center";
    XPolygonLabelShadowDiv.style.width = "200px";
    XPolygonLabelShadowDiv.style.zIndex = 100;
    XPolygonLabelShadowDiv.className = "map_polygon_label"
    XPolygonLabelShadowDiv.innerHTML = "";
    this._map.getPane(G_MAP_MARKER_PANE).appendChild(XPolygonLabelShadowDiv);
  }
  this._polygon = new GPolygon(this._points, this._strokeColor, this._strokeWeight, this._strokeOpacity, this._fillColor, this._fillOpacity);
  this._map.addOverlay(this._polygon);

  this._imgmap = document.createElement("map");
  this._imgmap.id = "polygon_map_" + (XPolygonIDCount++);
  this._imgmap.name = this._imgmap.id;
  this._imgmapArea = document.createElement("area");
  this._imgmapArea.shape = "poly";
  this._imgmapArea._xpolygon = this

  this.onClick = this.onMouseOver = this.onMouseOut = this.onMouseMove = this.onMouseDown = this.onMouseUp = function() {return true;};
  this._onClick     = function() {this.onClick();     GEvent.trigger(this, "click");}
  this._onMouseOver = function() {this.onMouseOver(); GEvent.trigger(this, "mouseover");}
  this._onMouseOut  = function() {this.onMouseOut();  GEvent.trigger(this, "mouseout");}
  this._onMouseMove = function() {this.onMouseMove(); GEvent.trigger(this, "mousemove");}
  this._onMouseDown = function() {this.onMouseDown(); GEvent.trigger(this, "mousedown");}
  this._onMouseUp   = function() {this.onMouseUp();   GEvent.trigger(this, "mouseup");}

  this._onMouseOver = function() {
    if (this._options.label) {
      XPolygonLabelDiv.innerHTML = "";
      XPolygonLabelDiv.style.visibility = "hidden";
      XPolygonLabelDiv.style.display = "";
      XPolygonLabelShadowDiv.innerHTML = "";
      XPolygonLabelShadowDiv.style.visibility = "hidden";
      XPolygonLabelShadowDiv.style.display = "";
      polygon = this;
      
      window.setTimeout(function() {
        XPolygonLabelDiv.innerHTML = polygon._options.label;
        XPolygonLabelShadowDiv.innerHTML = polygon._options.label;
    
        var point;
        var minX, minY, maxX, maxY;
        var coords;
        point = polygon._map.fromLatLngToDivPixel(polygon._polygon.getVertex(0));
        minX = maxX = point.x; minY = maxY = point.y;
        for (var i = 1; i < polygon._polygon.getVertexCount(); i++) {
          point = polygon._map.fromLatLngToDivPixel(polygon._polygon.getVertex(i));
          if (point.x < minX) {minX = point.x};
          if (point.y < minY) {minY = point.y};
          if (point.x > maxX) {maxX = point.x; polygon.eastmost = polygon._polygon.getVertex(i)};
          if (point.y > maxY) {maxY = point.y};
        }
        var offsetX = (XPolygonLabelDiv.clientWidth / 2) || 0;
        var offsetY = (XPolygonLabelDiv.clientHeight / 2) || 0;
    
        XPolygonLabelDiv.style.color = polygon._strokeColor; //"black";
        XPolygonLabelDiv.style.left = (minX + ((maxX - minX) / 2) - offsetX) + "px";
        XPolygonLabelDiv.style.top = (minY + ((maxY - minY) / 2) - offsetY) + "px";
        XPolygonLabelDiv.style.display = "";
        XPolygonLabelDiv.style.visibility = "visible";
        
        XPolygonLabelShadowDiv.style.color = "white";
        XPolygonLabelShadowDiv.style.left = (minX + ((maxX - minX) / 2) - offsetX + 1) + "px";
        XPolygonLabelShadowDiv.style.top = (minY + ((maxY - minY) / 2) - offsetY + 1) + "px";
        XPolygonLabelShadowDiv.style.display = "";
        XPolygonLabelShadowDiv.style.visibility = "visible";
      }, 0)
    }
    else {
      XPolygonLabelDiv.style.display = "none";
      XPolygonLabelDiv.innerHTML = "";
      XPolygonLabelShadowDiv.style.display = "none";
      XPolygonLabelShadowDiv.innerHTML = "";
    }
  }
  
  Event.observe(this._imgmapArea, "click",     this._onClick.bindAsEventListener(this), false);
  Event.observe(this._imgmapArea, "mouseover", this._onMouseOver.bindAsEventListener(this), false);
  Event.observe(this._imgmapArea, "mouseout",  this._onMouseOut.bindAsEventListener(this), false);
  Event.observe(this._imgmapArea, "mousemove", this._onMouseMove.bindAsEventListener(this), false);
  Event.observe(this._imgmapArea, "mousedown", this._onMouseDown.bindAsEventListener(this), false);
  Event.observe(this._imgmapArea, "mouseup",   this._onMouseUp.bindAsEventListener(this), false);

  this._imgmap.appendChild(this._imgmapArea);
  this._map.getPane(G_MAP_MARKER_SHADOW_PANE).appendChild(this._imgmap);

  this._img = document.createElement("img");
  this._img.style.position = "absolute";
  //img.style.border = "1px solid green";
  this._img.src = "/images/transp.png";
  this._img.useMap = "#" + this._imgmap.id;
  this._map.getPane(G_MAP_MARKER_SHADOW_PANE).appendChild(this._img);
}

XPolygon.prototype.setLabel = function(newLabel) {
  this._options.label = newLabel;
}

XPolygon.prototype.remove = function() {
  if (this._polygon) { this._polygon.remove(); this._polygon = null; }
  if (this._img && this._img.parentNode) { this._img.parentNode.removeChild(this._img); this._img = null}
  if (this._imgmap && this._imgmap.parentNode) { this._imgmap.parentNode.removeChild(this._imgmap); this._imgmap = null}
}

XPolygon.prototype.copy = function() {
  return new XPolygon(this._points, this._strokeColor, this._strokeWeight, this._strokeOpacity, this._fillColor, this._fillOpacity);
}

XPolygon.prototype.redraw = function(force) {
  if (!force) return;

  var point;
  var minX, minY, maxX, maxY;
  var coords;
  point = this._map.fromLatLngToDivPixel(this._polygon.getVertex(0));
  minX = maxX = point.x; minY = maxY = point.y;
  for (var i = 1; i < this._polygon.getVertexCount(); i++) {
    point = this._map.fromLatLngToDivPixel(this._polygon.getVertex(i));
    if (point.x < minX) {minX = point.x};
    if (point.y < minY) {minY = point.y};
    if (point.x > maxX) {maxX = point.x; this.eastmost = this._polygon.getVertex(i)};
    if (point.y > maxY) {maxY = point.y};
  }

  coords = "";
  for (var i = 1; i < this._polygon.getVertexCount(); i++) {
    point = this._map.fromLatLngToDivPixel(this._polygon.getVertex(i));
    coords += (point.x - minX) + "," + (point.y - minY) + ","
  }
  coords = coords.substr(0, coords.length - 1)
  //coords = minX + "," + minY + "," + minX + "," + maxY + "," + maxX + "," + maxY + "," + maxX + "," + minY + "," + minX + "," + minY
  
  this._img.style.left = minX + "px";
  this._img.style.top = minY + "px";
  this._img.width = maxX - minX;
  this._img.height = maxY - minY;
  this._imgmapArea.coords = coords;
}

XPolygon.prototype.getPoint = function(i) {
  //return this.eastmost;
  return this._polygon.getVertex(i);
}

XPolygon.prototype.getNumPoints = function() {
  return this._polygon.getVertexCount();
}






function XLabel(bounds, content, opt_opacity) {
  GOverlay.call(this);
  
  this.bounds = bounds;
  this.content = content;
  this.opacity = opt_opacity || 0.9;
}
XLabel.prototype = new GOverlay();

XLabel.prototype.initialize = function(map) {
  var div = document.createElement("div")
  var p = this._map_.fromLatLngToDivPixel(this.bounds);
  
  div.innerHTML = this.content;
  div.style.position = "absolute";
  div.style.left = (p.x) + "px";
  div.style.top = (p.y) + "px";
  div.style.border = "3px solid red;"
  div.style.backgroundColor = "white"
  if (typeof(div.style.filter) == 'string') { div.style.filter='alpha(opacity:' + this.opacity + ')'; }
  if (typeof(div.style.KHTMLOpacity) == 'string') { div.style.KHTMLOpacity = this.opacity; }
  if (typeof(div.style.MozOpacity) == 'string') { div.style.MozOpacity = this.opacity;}
  if (typeof(div.style.opacity) == 'string') { div.style.opacity = this.opacity;}
  
  map.getPane(G_MAP_MAP_PANE).appendChild(div);

  this._map_ = map;
  this._div_ = div;
}

XLabel.prototype.remove = function() {
  alert(1);
  this._div_.parentNode.removeChild(this._div_);
}

XLabel.prototype.redraw = function(force) {
  if (!force) return;

  var p = this._map_.fromLatLngToDivPixel(this.bounds);
  this._div_.style.display = "none";
  this._div_.style.left = (p.x) + "px";
  this._div_.style.top = (p.y) + "px";
  this._div_.style.display = "";
}


