// Copyright 2008 Zilpy LLC. All Rights Reserved.

var zMap;
var zEw;
var zTimer;

function addEvent(elm,evType,fn,useCapture) { 
  if(elm.addEventListener){ 
    elm.addEventListener(evType,fn,useCapture); 
    return true;
  } else if(elm.attachEvent){ 
    var r=elm.attachEvent("on"+evType,fn); 
    return r; 
  }else{
   elm["on"+evType]=fn; 
  } 
} 
addEvent(window,"load",load,false); 
addEvent(window,"unload",GUnload,false);

function pretty(t,b){
  var text='<table border="0" cellpadding="0" cellspacing="0"><tr><td width="100%" class="etitle" nowrap>';
  text+=t;
  text+='<a href="javascript:zEw.hide()"><img width="12" height="11" src="/img/eclose.png" border=0 style="position:absolute;right:4px;top:4px"></a>'; 
  text+='</td></tr><tr><td nowrap>';
  text+=b;
  text+='</td></tr></table>';
  return text;
}

function getUrl(info,label){
  var url='';
  if(info){
    url='<a style="font-family:tahoma,sans-serif;font-size:11px;color:#00598c;text-align:left;" href="';
    url+=info;
    url+='">';
    url+=label;
    url+='</a>';
  }
  return url;
}

function getJSUrl(info,label){
  var url='';
  if(info){
    url+='<a style="font-family:tahoma,sans-serif;font-size:11px;color:#00598c;text-align:left;" href="javascript:{}" onclick=\"window.open(\'';
    url+=info;
    url+='\', \'_self\');">';
    url+=label;
    url+='</a>';
  }
  return url;
}

function info(data,url,prop,trla){
  var s='';
  if (data&&data.length>0){
    s='<ul style="padding:0px;">';
    for(var i=0;i<data.length;i++){
      var row=data[i];
      s+='<li style="font-family:tahoma,sans-serif; font-size:11px; color:#818181; text-align:left; margin-bottom: 2px;">';
      if(row.b==0){
        s+='Studio:';
      }else{
        s+=row.b;
        s+=' Bdr:&nbsp;&nbsp;';
      }
      s+='&nbsp;<span style="color: #00598c; font-family:tahoma,sans-serif;font-weight:bold; font-size:11px;">';
      s+=row.r;
      s+='</span>&nbsp;<span style="font-size:10px;">(';
	    s+=row.s;
	    s+=')</span></li>';
    }
    s+='</ul>';
  }
  if(url||prop){
    s+='<span style="text-align:left;">';
    if(url){
      s+='<img src="/img/blue_right_arrow.gif" />&nbsp;';
      s+=url;
    }
    if(prop){
      s+='&nbsp;&nbsp;<img src="/img/blue_right_arrow.gif" />&nbsp;';
      s+=prop;
    }
    if(trla){
      s+='&nbsp;&nbsp;<img src="/img/blue_right_arrow.gif" />&nbsp;';
      s+=trla;
    }
    s+='</span>';
  }
  return s;  
}

var zPolyIndex=0;
var zPolys=[];

function loadPolygon(){
  var ps=[];
  if(!zData||zData.length==0) return document.getElementById("loading").style.visibility='hidden';
  var row=zData[zPolyIndex];
  var coords=row.coords;
  var bounds=new GLatLngBounds();
  var size=coords.length/2;
  for(var i=0;i<size;i++){
    var index=i*2;
    var p=new GLatLng(coords[index],coords[index+1]);
    ps.push(p);
    bounds.extend(p);
  }
    var polygon=new ZPolygon(ps,"#000000",1,1,row.color,0.7,row.name,pretty(row.name,info(row.info,getUrl(row.url,'Facts'),getUrl(row.props,'Rentals'),getJSUrl(row.trla,'For sale'))));
    zMap.addOverlay(polygon);
    polygon.Bound=bounds;
    zPolys.push(polygon);
    zPolyIndex=zPolyIndex+1;
    if(zPolyIndex<=zData.length-1)zTimer=setTimeout(loadPolygon,1);
    else document.getElementById("loading").style.visibility='hidden';
}

function load(){
	if(GBrowserIsCompatible()){
		zMap=new GMap2(document.getElementById("map"));
		zMap.disableDoubleClickZoom();
		zMap.disableScrollWheelZoom();
    zMap.addControl(new GSmallZoomControl(),new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(2,2)));
    var mapControl=new GHierarchicalMapTypeControl();
    mapControl.addRelationship(G_SATELLITE_MAP,G_HYBRID_MAP,null,true);
    zMap.addControl(mapControl,new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(19,0)));
    zMap.addMapType(G_PHYSICAL_MAP);
    zMap.setCenter(zBounds.getCenter(),zMap.getBoundsZoomLevel(zBounds));
    zEw = new EWindow(zMap,E_STYLE);
    zMap.addOverlay(zEw);
    var isEditing=false;
    GEvent.addListener(zEw,"mouseover",function(){isEditing=true;});
    GEvent.addListener(zEw,"mouseout",function(){isEditing=false;});
    document.getElementById("loading").style.visibility='visible';
    zTimer=setTimeout(loadPolygon,10);
    GEvent.addListener(zMap,"click",function(o,p){
      if(p){
        for(var i=0;i<zPolys.length;i++){
          if(zPolys[i].Bound.contains(p)){
            if(zPolys[i].Contains(p)){
              if(!isEditing){
                zEw.openOnMap(p,zPolys[i].info);
              }
              break;
            }
          }
        }
      }
    });
    GEvent.addListener(zMap,"zoomend",function(oz,nz){
      clearTimeout(zTimer);
      document.getElementById("loading").style.visibility='visible';
      zPolyIndex=0;
      zMap.clearOverlays();
      zMap.addOverlay(zEw);
      loadPolygon();
      var ttt = zMap.getBounds();
      var zzzzz = 0;
    });
  }
	else {
	  alert("Sorry, the map is not compatible with your browser");
	}
}

function EStyle(stemImage, stemSize, boxClass, boxOffset) {
  this.stemImage = stemImage;
  this.stemSize = stemSize;
  this.boxClass = boxClass;
  this.boxOffset = boxOffset;
  var agent = navigator.userAgent.toLowerCase();
  var fudge = 3;  // assume Netscape if no match found
  if (agent.indexOf("opera") > -1) {
    fudge = 3;
  }   
  if (agent.indexOf("firefox") > -1) {
    fudge = 3;
  }   
  if (agent.indexOf("safari") > -1) {
    fudge = 3;
  }   
  if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){
    fudge = 0;
  }
  this.fudge = fudge;
}

var E_STYLE = new EStyle("/img/stem.png", new GSize(24,24),  "estyle", new GPoint(-10,23));

function EWindow(map,estyle) {
  this.map=map;
  this.estyle=estyle;
  this.visible = false;
  this.ie = false;
  var agent = navigator.userAgent.toLowerCase();
  if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){ this.ie = true} else {this.ie = false}} 
  EWindow.prototype = new GOverlay();
  EWindow.prototype.initialize = function(map) {
  var div1 = document.createElement("div");
  div1.style.position = "absolute";
  map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div1);
  var div2 = document.createElement("div");
  div2.style.position = "absolute";
  div2.style.width = this.estyle.stemSize.width+"px";
  map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div2);
  this.div1 = div1;
  this.div2 = div2;
}
EWindow.prototype.openOnMap = function(point, html, offset) {
  this.offset = offset||new GPoint(0,0);
  this.point = point;
  this.div1.innerHTML = '<div class="' + this.estyle.boxClass + '"><nobr>' + html + '</nobr></div>';
  if (this.ie && this.estyle.stemImage.toLowerCase().indexOf(".png")>-1) {
    var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this.estyle.stemImage+"', sizingMethod='scale');";
    this.div2.innerHTML = '<div style="height:' +this.estyle.stemSize.height+ 'px; width:'+this.estyle.stemSize.width+'px; ' +loader+ '" ></div>';
  } else {
    this.div2.innerHTML = '<img src="' + this.estyle.stemImage + '" width="' + this.estyle.stemSize.width +'" height="' + this.estyle.stemSize.height +'">';
  }
  var z = GOverlay.getZIndex(this.point.lat());
  this.div1.style.zIndex = z;
  this.div2.style.zIndex = z+1;
  this.visible = true;
  this.show();
  this.redraw(true);
}
EWindow.prototype.openOnMarker = function(marker,html) {
  var vx = marker.getIcon().iconAnchor.x - marker.getIcon().infoWindowAnchor.x;
  var vy = marker.getIcon().iconAnchor.y - marker.getIcon().infoWindowAnchor.y;
  this.openOnMap(marker.getPoint(), html, new GPoint(vx,vy));
}
EWindow.prototype.redraw = function(force) {
  if (!this.visible) {return;}
  var p = this.map.fromLatLngToDivPixel(this.point);
  this.div2.style.left   = (p.x + this.offset.x) + "px";
  this.div2.style.bottom = (-p.y + this.offset.y -this.estyle.fudge) + "px";
  this.div1.style.left   = (p.x + this.offset.x + this.estyle.boxOffset.x) + "px";
  this.div1.style.bottom = (-p.y + this.offset.y + this.estyle.boxOffset.y) + "px";
  this.div1.style.cursor = "default";
  this.div2.style.cursor = "default";
  var eover = GEvent.callback(this,this.onOver);
  var eout = GEvent.callback(this,this.onOut);
  GEvent.clearInstanceListeners(this.div1);//safety 
  GEvent.addDomListener(this.div1,"mouseover",function(){eover();});
  GEvent.addDomListener(this.div1,"mouseout",function(){eout();});
}
EWindow.prototype.remove = function() {
  this.div1.parentNode.removeChild(this.div1);
  this.div2.parentNode.removeChild(this.div2);
  this.visible = false;
}
EWindow.prototype.copy = function() {
  return new EWindow(this.map, this.estyle);
}
EWindow.prototype.show = function() {
  this.div1.style.display="";
  this.div2.style.display="";
  this.visible = true;
}
EWindow.prototype.hide = function() {
  this.div1.style.display="none";
  this.div2.style.display="none";
  this.visible = false;
}
EWindow.prototype.isHidden = function() {
  return !this.visible;
}
EWindow.prototype.supportsHide = function() {
  return true;
}
EWindow.prototype.zindex = function(zin) {
  var z = GOverlay.getZIndex(this.point.lat());
  this.div1.style.zIndex = z+zin;
  this.div2.style.zIndex = z+1+zin;
}
EWindow.prototype.onOver = function(){
  GEvent.trigger(this,"mouseover");
}
EWindow.prototype.onOut = function(){
  GEvent.trigger(this,"mouseout");
}

var ZPolygonId;
function ZPolygon(points, strokeColor, strokeWeight, strokeOpacity, fillColor, fillOpacity, tooltip, info) {	
    this.info = info;
    this.tooltip = tooltip;
    this.strokeColor = strokeColor;
    this.strokeWeight = strokeWeight;
    this.strokeOpacity = strokeOpacity;
    this.fillColor = fillColor;
    this.fillOpacity = fillOpacity;
    if(ZPolygonId == null)
        ZPolygonId = 0;
    else
        ZPolygonId += 1;
    this.domid = "ZPolygonId" + ZPolygonId.toString();
    var agent=navigator.userAgent.toLowerCase();
    this.useTooltip=agent.indexOf("firefox")>-1||agent.indexOf("msie")>-1;
    this.usesVml = (agent.indexOf("msie") != -1);
    GPolygon.call(this,points,strokeColor,strokeWeight,strokeOpacity,fillColor,fillOpacity,{clickable:false});
}
ZPolygon.prototype = new GPolygon(new Array(new GLatLng(0,0)));

ZPolygon.prototype.initialize = function(map) {
    GPolygon.prototype.initialize.call(this,map);
}

ZPolygon.prototype.remove = function() {
    GPolygon.prototype.remove.call(this);
}

ZPolygon.prototype.copy = function(map) {
    return new ZPolygon(this.points,this.strokeColor,this.strokeWeight,this.strokeOpacity,this.fillColor,this.fillOpacity,this.tooltip);
}

ZPolygon.prototype.redraw = function(force) {
   GPolygon.prototype.redraw.call(this,force);
   if(this.useTooltip){
   var dom;
   if(this.usesVml){
        try{        
            var shps = document.getElementsByTagName("shape"); 
            dom = shps[shps.length-1];//assume ours is the most recently added by the superclass redraw
            if(this.tooltip != null){
                dom.style.cursor = "pointer";
                dom.title = this.tooltip;
            }
            dom.id = this.domid;//assign unique DOM id so we can modify attributes later   
        }
        catch (ex)
        {
		    if(ZPolygonId == 0)
			    alert("The designer of this Google Maps web page has attempted to use VML graphics without including the necessary header material.");
        }
   }
   else{
        var shps = document.getElementsByTagName("path"); 
        dom = shps[shps.length-1];//assume ours is the most recently added by the superclass redraw
        if(this.tooltip != null){
          dom.style.cursor = "pointer";
          dom.setAttribute("title",this.tooltip);
        }
        dom.setAttribute("id",this.domid);//assign unique DOM id so we can modify attributes later
   }
   //set up event handlers
   var cclick = GEvent.callback(this,this.onClick);
   var cover = GEvent.callback(this,this.onOver);
   var cout = GEvent.callback(this,this.onOut);
   GEvent.clearInstanceListeners(dom);//safety 
   GEvent.addDomListener(dom,"click",function(event){cclick();});
   GEvent.addDomListener(dom,"mouseover",function(){cover();});
   GEvent.addDomListener(dom,"mouseout",function(){cout();});
   }
}

//event handlers
ZPolygon.prototype.onClick = function(point){
    GEvent.trigger(this,"click");
}
ZPolygon.prototype.onOver = function(){
    GEvent.trigger(this,"mouseover");
}
ZPolygon.prototype.onOut = function(){
    GEvent.trigger(this,"mouseout");
}
ZPolygon.prototype.Contains = function(point) {
  var j = 0;
  var oddNodes = false;
  var x = point.lng();
  var y = point.lat();
  for (var i = 0; i < this.getVertexCount(); i++) {
    j++;
    if (j == this.getVertexCount()) {j = 0;}
    if (((this.getVertex(i).lat() < y) && (this.getVertex(j).lat() >= y))
    || ((this.getVertex(j).lat() < y) && (this.getVertex(i).lat() >= y))) {
      if ( this.getVertex(i).lng() + (y - this.getVertex(i).lat())
      /  (this.getVertex(j).lat() - this.getVertex(i).lat())
      *  (this.getVertex(j).lng() - this.getVertex(i).lng()) < x) {
        oddNodes = !oddNodes
      }
    }
  }
  return oddNodes;
}

ZPolygon.prototype.Bounds = function() {
  var bounds = new GLatLngBounds();
  for (var i = 0; i < this.getVertexCount(); i++) {
    bounds.extend(this.getVertex(i));
  }
  return bounds;
}