//////////////////////////////////////////////////////////////////
//                                                              //
// propertylistingmaps.com                                      //
//                                                              //
// David Tompkins -- 11/12/2005                                 //
// http://dt.org/                                               //
//                                                              //
// Copyright (c) 2006-2007 by David Tompkins.                   //
//                                                              //
//////////////////////////////////////////////////////////////////
//                                                              //
// This program is free software; you can redistribute it       //
// and/or modify it under the terms of the GNU General Public   //
// License as published by the Free Software Foundation.        //
//                                                              //
// This program is distributed in the hope that it will be      //
// useful, but WITHOUT ANY WARRANTY; without even the implied   //
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR      //
// PURPOSE. See the GNU General Public License for more details //
//                                                              //
// You should have received a copy of the GNU General Public    //
// License along with this program; if not, write to the Free   //
// Software Foundation, Inc., 59 Temple Place, Suite 330,       //
// Boston, MA 02111-1307 USA                                    //
//                                                              //
//////////////////////////////////////////////////////////////////

var listings = [];
var index = 0;

var map = null;
var icon = null;
var oldIcon = null;
var tooltip = null;
var message = null;
var legend = null;
var mapTypeNormal = null;
var mapTypeSatellite = null;
var mapTypeHybrid = null;

var legendOffset = 3;
var opacity = 0.80;
var IEopacity = 80;
var defaultMessage = null;
var defaultZoom = 13;
var defaultLatitude = 37.450413;
var defaultLongitude = -122.182551;
var zoomUpdateThreshold = 15;
var ignoreEvents = false;

var legendHTML = 'Last Data Update:<br><img src="/images/marker-small.png"/>Less Than 10 Days Ago<br><img src="/images/marker-old-small.png"/>More Than 10 Days Ago';

function load()
{
  if (GBrowserIsCompatible())
  {
    map = new GMap2(document.getElementById("map"));
    //map.addControl(new GSmallMapControl());
    //map.addControl(new GMapTypeControl());
    map.addControl(new CustomMapTypeControl());
    map.addControl(new CustomZoomControl());
    map.addControl(new CustomMoveControl());
    map.setCenter(new GLatLng(defaultLatitude, defaultLongitude), defaultZoom);
    map.setMapType(G_HYBRID_MAP);
    setMapTypeCellStyles();
  
    GEvent.addListener(map, "dragend", function() { mapResize(); });
    GEvent.addListener(map, "zoomend", function(oldzoom, newzoom) { mapResize(); });
  
    tooltip = document.createElement("div");
    map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
    tooltip.style.visibility="hidden";
    tooltip.style.padding    = "0";
    tooltip.style.margin     = "0";
    tooltip.style.MozOpacity = opacity;
    tooltip.style.filter     = "alpha(opacity=" + IEopacity + ")";
    tooltip.style.opacity    = opacity;
    tooltip.style.zIndex     = 50000;

    message = document.createElement("div");
    map.getContainer().appendChild(message);
    message.style.visibility="hidden";
    message.style.padding    = "0";
    message.style.margin     = "0";
    message.style.MozOpacity = opacity;
    message.style.filter     = "alpha(opacity=" + IEopacity + ")";
    message.style.opacity    = opacity;
    message.style.zIndex     = 50000;
  
    var size = map.getSize();
    var anchor = new GSize(size.width/2-message.offsetWidth/2, size.height-message.offsetHeight-3);
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, anchor); 
    pos.apply(message);

    legend = document.createElement("div");
    map.getContainer().appendChild(legend);
    legend.style.visibility="hidden";
    legend.style.padding    = "0";
    legend.style.margin     = "0";
    legend.style.MozOpacity = opacity;
    legend.style.filter     = "alpha(opacity=" + IEopacity + ")";
    legend.style.opacity    = opacity;
    legend.style.zIndex     = 50000;
  
    anchor = new GSize(legendOffset, legendOffset);
    pos = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, anchor); 
    pos.apply(legend);

    update();

    if (defaultMessage != null)
      showMessage(defaultMessage);

    showLegend();
  }
}

function update()
{
  if (GBrowserIsCompatible())
  {
    for (i = 0 ; i < index ; i++)
      map.addOverlay(listings[i]);
  }
}

function mapResize()
{
  if (ignoreEvents == true)
    return;

  //if (map.getZoom() < zoomUpdateThreshold)
  //  return;

  showMessage("Loading...");
  bounds = map.getBounds();
  sw = bounds.getSouthWest();
  ne = bounds.getNorthEast();
  params = 'w_lat='+sw.lat()+'&s_lng='+sw.lng()+'&e_lat='+ne.lat()+'&n_lng='+ne.lng()+'&authenticity_token='+encodeURIComponent(AUTH_TOKEN);
  new Ajax.Updater('markers', '/site/update_markers_event', {asynchronous:true, evalScripts:true, parameters:params});
  new Ajax.Updater('sitemeter', '/site/update_sitemeter', {asynchronous:true, evalScripts:true, parameters:params});
  new Ajax.Updater('quantcast', '/site/update_quantcast', {asynchronous:true, evalScripts:true, parameters:params});
}

function addMarker(latitude, longitude, address, tooltip, isCurrent)
{
  if (icon == null)
  {
    icon = new GIcon();
    icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    icon.iconSize = new GSize(20, 34);
    icon.shadowSize = new GSize(37, 34);
    icon.iconAnchor = new GPoint(9, 34);
    icon.infoWindowAnchor = new GPoint(9, 2);
    icon.infoShadowAnchor = new GPoint(18, 25);
    icon.image = "/images/marker.png";

    oldIcon = new GIcon();
    oldIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    oldIcon.iconSize = new GSize(20, 34);
    oldIcon.shadowSize = new GSize(37, 34);
    oldIcon.iconAnchor = new GPoint(9, 34);
    oldIcon.infoWindowAnchor = new GPoint(9, 2);
    oldIcon.infoShadowAnchor = new GPoint(18, 25);
    oldIcon.image = "/images/marker-old.png";
  }

  var point = new GLatLng(latitude, longitude);
  var marker = new GMarker(point, ((isCurrent=='true')?icon:oldIcon));

  marker.tooltip = '<div class="markerTooltip">'+tooltip+'</div>';

  GEvent.addListener(marker, "click", function()
  {
    marker.openInfoWindowHtml(address);
  });
    
  GEvent.addListener(marker,"mouseover", function()
  {
    showTooltip(marker);
  });        
  
  GEvent.addListener(marker,"mouseout", function()
  {
    hideTooltip(marker);
  });        

  listings[index++] = marker;
}

function clearAllMarkers()
{
  map.clearOverlays();
  listings = [];
  index = 0;
}

function panTo(latitude, longitude)
{
  if (map == null)
  {
    // create pending panTo location
    defaultLatitude = latitude;
    defaultLongitude = longitude;
    return;
  }

  window.setTimeout(function() {
    ignoreEvents = true;
    map.setZoom(defaultZoom);
    map.panTo(new GLatLng(latitude, longitude));
    ignoreEvents = false;
  }, 1000);
}

function showTooltip(marker)
{
  tooltip.innerHTML = marker.tooltip;
  var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
  var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
  var anchor=marker.getIcon().iconAnchor;
  var width=marker.getIcon().iconSize.width;
  var height=tooltip.clientHeight;
  var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
  pos.apply(tooltip);
  tooltip.style.visibility="visible";
}

function hideTooltip(marker)
{
  tooltip.style.visibility="hidden";
}

function showMessage(msg)
{
  if (message == null)
  {
    defaultMessage = msg;
    return;
  }
  message.style.visibility="hidden";
  message.innerHTML = '<div class="message">'+msg+'</div>';
  var size = map.getSize();
  var anchor = new GSize(size.width/2-message.offsetWidth/2, size.height-message.offsetHeight-3);
  var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, anchor); 
  pos.apply(message);
  message.style.visibility="visible";
}

function hideMessage()
{
  message.style.visibility="hidden";
}

function showLegend()
{
  legend.style.visibility="hidden";
  legend.innerHTML = '<div class="legend">'+legendHTML+'</div>';
  legend.style.visibility="visible";
}

function hideLegend()
{
  legend.style.visibility="hidden";
}

function setMapType(mapType)
{
  map.setMapType(mapType);
  setMapTypeCellStyles();
}

function setMapTypeCellStyles()
{
  mapType = map.getCurrentMapType();
  mapTypeNormal.className = (mapType == G_NORMAL_MAP) ? "mapTypeCellSelected" : "mapTypeCell";
  mapTypeSatellite.className = (mapType == G_SATELLITE_MAP) ? "mapTypeCellSelected" : "mapTypeCell";
  mapTypeHybrid.className = (mapType == G_HYBRID_MAP) ? "mapTypeCellSelected" : "mapTypeCell";
}

// --- custom map control -- //

function CustomMapTypeControl() { }

CustomMapTypeControl.prototype = new GControl();

CustomMapTypeControl.prototype.initialize = function(map)
{
  var mapTypeControl = document.createElement("div");
  mapTypeControl.className = "mapTypeControl";
  mapTypeControl.style.padding    = "0";
  mapTypeControl.style.margin     = "0";
  mapTypeControl.style.MozOpacity = opacity;
  mapTypeControl.style.opacity    = opacity;
  mapTypeControl.style.filter     = "alpha(opacity=" + IEopacity + ")";
  mapTypeControl.style.zIndex     = 50000;

  mapTypeControl.appendChild(document.createTextNode("Map Type"));
  var table = document.createElement("table");
  mapTypeControl.appendChild(table);
  var tbody = document.createElement("tbody");
  table.appendChild(tbody);

  var row = document.createElement("tr");
  tbody.appendChild(row);
  mapTypeNormal = document.createElement("td");
  row.appendChild(mapTypeNormal);
  mapTypeNormal.title = "Switch to Normal Map Type";
  mapTypeNormal.appendChild(document.createTextNode("Map"));
  GEvent.addDomListener(row, "click", function() { setMapType(G_NORMAL_MAP); });

  row = document.createElement("tr");
  tbody.appendChild(row);
  mapTypeSatellite = document.createElement("td");
  row.appendChild(mapTypeSatellite);
  mapTypeSatellite.title = "Switch to Satellite Map Type";
  mapTypeSatellite.appendChild(document.createTextNode("Satellite"));
  GEvent.addDomListener(row, "click", function() { setMapType(G_SATELLITE_MAP); });

  row = document.createElement("tr");
  tbody.appendChild(row);
  mapTypeHybrid = document.createElement("td");
  row.appendChild(mapTypeHybrid);
  mapTypeHybrid.title = "Switch to Hybrid Map Type";
  mapTypeHybrid.appendChild(document.createTextNode("Hybrid"));
  GEvent.addDomListener(row, "click", function() { setMapType(G_HYBRID_MAP); });

  map.getContainer().appendChild(mapTypeControl);
  return mapTypeControl;
}

CustomMapTypeControl.prototype.getDefaultPosition = function()
{
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(legendOffset, legendOffset));
}

// --- custom zoom control -- //

function CustomZoomControl() { }

CustomZoomControl.prototype = new GControl();

CustomZoomControl.prototype.initialize = function(map)
{
  var mapZoomControl = document.createElement("div");
  mapZoomControl.className = "mapZoomControl";
  mapZoomControl.style.padding    = "0";
  mapZoomControl.style.margin     = "0";
  mapZoomControl.style.MozOpacity = opacity;
  mapZoomControl.style.opacity    = opacity;
  mapZoomControl.style.filter     = "alpha(opacity=" + IEopacity + ")";
  mapZoomControl.style.zIndex     = 50000;

  mapZoomControl.appendChild(document.createTextNode("Zoom"));
  var table = document.createElement("table");
  mapZoomControl.appendChild(table);
  var tbody = document.createElement("tbody");
  table.appendChild(tbody);
  var row = document.createElement("tr");
  tbody.appendChild(row);

  var cell = document.createElement("td");
  row.appendChild(cell);
  cell.title = "Zoom Out";
  cell.className = "mapZoomControlButton";
  var img = document.createElement("img");
  img.src = "/images/zoom-out.png";
  cell.appendChild(img);
  GEvent.addDomListener(cell, "click", function() { map.zoomOut(); });

  cell = document.createElement("td");
  row.appendChild(cell);
  cell.title = "Zoom In";
  cell.className = "mapZoomControlButton";
  img = document.createElement("img");
  img.src = "/images/zoom-in.png";
  cell.appendChild(img);
  GEvent.addDomListener(cell, "click", function() { map.zoomIn(); });

  map.getContainer().appendChild(mapZoomControl);
  return mapZoomControl;
}

CustomZoomControl.prototype.getDefaultPosition = function()
{
  return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(legendOffset, legendOffset));
}

// --- custom move control -- //

function CustomMoveControl() { }

CustomMoveControl.prototype = new GControl();

CustomMoveControl.prototype.initialize = function(map)
{
  var mapMoveControl = document.createElement("div");
  mapMoveControl.className = "mapMoveControl";
  mapMoveControl.style.padding    = "0";
  mapMoveControl.style.margin     = "0";
  mapMoveControl.style.MozOpacity = opacity;
  mapMoveControl.style.opacity    = opacity;
  mapMoveControl.style.filter     = "alpha(opacity=" + IEopacity + ")";
  mapMoveControl.style.zIndex     = 50000;

  mapMoveControl.appendChild(document.createTextNode("Move"));
  var table = document.createElement("table");
  mapMoveControl.appendChild(table);
  var tbody = document.createElement("tbody");
  table.appendChild(tbody);

  var row = document.createElement("tr");
  tbody.appendChild(row);
  row.appendChild(document.createElement("td"));
  var cell = document.createElement("td");
  row.appendChild(cell);
  cell.title = "Move North";
  cell.className = "mapMoveControlButton";
  var img = document.createElement("img");
  img.src = "/images/pan-up.png";
  cell.appendChild(img);
  GEvent.addDomListener(cell, "click", function() { map.panDirection(0,1); });
  row.appendChild(document.createElement("td"));

  row = document.createElement("tr");
  tbody.appendChild(row);
  cell = document.createElement("td");
  row.appendChild(cell);
  cell.title = "Move West";
  cell.className = "mapMoveControlButton";
  img = document.createElement("img");
  img.src = "/images/pan-left.png";
  cell.appendChild(img);
  GEvent.addDomListener(cell, "click", function() { map.panDirection(1,0); });
  row.appendChild(document.createElement("td"));
  cell = document.createElement("td");
  row.appendChild(cell);
  cell.title = "Move East";
  cell.className = "mapMoveControlButton";
  img = document.createElement("img");
  img.src = "/images/pan-right.png";
  cell.appendChild(img);
  GEvent.addDomListener(cell, "click", function() { map.panDirection(-1,0); });

  row = document.createElement("tr");
  tbody.appendChild(row);
  row.appendChild(document.createElement("td"));
  cell = document.createElement("td");
  row.appendChild(cell);
  cell.title = "Move South";
  cell.className = "mapMoveControlButton";
  img = document.createElement("img");
  img.src = "/images/pan-down.png";
  cell.appendChild(img);
  GEvent.addDomListener(cell, "click", function() { map.panDirection(0,-1); });
  row.appendChild(document.createElement("td"));

  map.getContainer().appendChild(mapMoveControl);
  return mapMoveControl;
}

CustomMoveControl.prototype.getDefaultPosition = function()
{
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(legendOffset, legendOffset));
}
