
function BNMap() {
	this.map = null;
	this.markerMgr = null;
	this.cachedMarkers = null;
	this.jsonRequests = { };
	this.options = [];
	this.drawers = { };
	this.drawerIds = [ ];
	this.LastAutosetMapType = G_PHYSICAL_MAP;
	this.mapDivId = null;
	this.shapeTool = null;
	return this;
};
BNMap.prototype.CacheMarker = function(zoomLevel,id,marker) {
	if( this.cachedMarkers==null )
		this.cachedMarkers = [];
	if( this.cachedMarkers[zoomLevel] == null )
		this.cachedMarkers[zoomLevel] = [];
	if( this.cachedMarkers[zoomLevel][id] == null )
		this.cachedMarkers[zoomLevel][id] = marker;
};
BNMap.prototype.GetCachedMarker = function(zoomLevel,id) {
	if( this.cachedMarkers==null )
		return null;
	if( this.cachedMarkers[zoomLevel] == null )
		return null;
	return this.cachedMarkers[zoomLevel][id]; // may be null if not cached
};
BNMap.prototype.RemoveFilteredMarkers = function(markerFilterFunc) {
	if (this.cachedMarkers) {
		for(var i=0;i<30;i++) {
			if( this.cachedMarkers[i] ) {
				for( var id in this.cachedMarkers[i] ) {
					var m = this.cachedMarkers[i][id];
					if( m && markerFilterFunc(m) ) {
						this.markerMgr.removeMarker(m);
						this.cachedMarkers[i][id] = null;
					}
				}
			}
		}
	}
};
BNMap.prototype.makeAllMarkersUnclickable = function() {
	//alert("DEBUG:**UN**CLICKABLE");
	//var dbg = 0;
	if (this.cachedMarkers) {
		for(var i=0;i<30;i++) {
			if( this.cachedMarkers[i] ) {
				for( var id in this.cachedMarkers[i] ) {
					var m = this.cachedMarkers[i][id];
					if(m && m.BN_TYPE) { // check BN_TYPE to ignore non-marker entries by mootools
						if(m["BN_MASKMARKER"]) {
							//m["BN_MASKMARKER"].show();
						}
						else {
							var maskMarker = new google.maps.Marker(m.getLatLng(),{
								icon: m.getIcon(), 	
								title: m.getTitle(),
								clickable: false,
								draggable: false,
								zIndexProcess: function(mrkr,b){
									return google.maps.Overlay.getZIndex(mrkr.getPoint().lat()) + 10000001;
								}
							});
							m["BN_MASKMARKER"] = maskMarker;
							this.markerMgr.addMarker(maskMarker,i,i);
							//dbg++;
							m.hide();
							var _markerMgr = this.markerMgr;
							google.maps.Event.addListener(m,'remove',function() {
								if(m["BN_MASKMARKER"]!=null)
									_markerMgr.removeMarker(m["BN_MASKMARKER"]);												  
							});
						}
					}
				}
			}
		}
	}
	//alert('added ' + dbg + ' mask markers');
};
BNMap.prototype.makeAllMarkersClickable = function() {
	//alert("DEBUG:CLICKABLE");
	//var dbg = 0;
	if (this.cachedMarkers) {
		for(var i=0;i<30;i++) {
			if( this.cachedMarkers[i] ) {
				for( var id in this.cachedMarkers[i] ) {
					var m = this.cachedMarkers[i][id];
					if(m && m.BN_TYPE) { // check BN_TYPE to ignore non-marker entries by mootools
						if(m["BN_MASKMARKER"]) {
							//dbg++;
							this.markerMgr.removeMarker(m["BN_MASKMARKER"]);
							m["BN_MASKMARKER"] = null;
						}
						m.show();
					}
				}
			}
		}
	}
	//alert('removed ' + dbg + ' mask markers');
};
BNMap.prototype.RefreshData = function(bClearAllMarkers) {
	this.onMapLocationChanged(bClearAllMarkers);
};
BNMap.prototype.onMapLocationChanged = function(optClearAllMarkersOnComplete) {
	optClearAllMarkersOnComplete = optClearAllMarkersOnComplete || false;
	var bounds = this.map.getBounds();
	var zoom = this.map.getZoom();	
	var shape = this.shapeTool.currentPolygon==null ? null : this.shapeTool.getShapeParamString();
	
	BNDebugLog("MapLocationChanged: " + bounds + " : " + zoom);
	
	// let drawers handle the potential zoom change first, it may have an impact on the parameters used in the json request below.
	if( this.prevZoomLevel!=zoom ) {			
		for(var i=0;i<this.drawerIds.length;i++) {
			this.drawers[this.drawerIds[i]].onMapZoomChanged(zoom);
		}
		
		// if the map is stil in the last automatically-set map type (user didn't interactively switch to something else)
		// "help the user by automatically setting the map to standard type when zoom>=13 and back to terrain when zoom<=12
		var currMapType = this.map.getCurrentMapType();
		if( currMapType == this.LastAutosetMapType ) {
			if( zoom>=13 ) {
				if(currMapType!=G_NORMAL_MAP) {
					this.map.setMapType(G_NORMAL_MAP);
					this.LastAutosetMapType = G_NORMAL_MAP;
				}
			}
			else {
				if(currMapType!=G_PHYSICAL_MAP) {
					this.map.setMapType(G_PHYSICAL_MAP);
					this.LastAutosetMapType = G_PHYSICAL_MAP;
				}	
			}
		}
	}
	
	var jsonParam = { 
		bounds: { NELat: bounds.getNorthEast().lat(), NELng: bounds.getNorthEast().lng(), SWLat: bounds.getSouthWest().lat(), SWLng: bounds.getSouthWest().lng() },
		zoom: zoom,
		search: this.drawers.PropertySearch.searchParameters,
		layers: [],
		shape: shape
	};
	for(var i=0;i<this.drawerIds.length;i++) {
		jsonParam.layers.merge(this.drawers[this.drawerIds[i]].getDrawerEnabledLayers());
	}
	
	var _bnmap = this; // create enclosure
	if( this.jsonRequests.MapLocationChangedRequest!=null ) {
		this.jsonRequests.MapLocationChangedRequest.cancel();
		if(this.jsonRequests.MapLocationChangedRequest.statusIndicator) {
			this.jsonRequests.MapLocationChangedRequest.statusIndicator.remove();
			this.jsonRequests.MapLocationChangedRequest.statusIndicator=null;
		}
	}
	
	this.jsonRequests.MapLocationChangedRequest = new Json.Remote(this.options.baseUrl + "AdvSearchJSON.aspx?Cmd=GetMarkers", {
	 onComplete: function(response){
	 	_bnmap.statusControl.hide();
	 	BNDebugLog("COMPLETE");	 		 	
	 	//BNDebugLog(odump(response));	 	
		
		var bShowStatusResultsCount = true;
		if(_bnmap.statusControl && response.warnings && response.warnings!='') {
			if((','+response.warnings+',').indexOf(',NO_PROPS_ZOOM,')>=0) {
				_bnmap.statusControl.setStatus("<strong>Properties are not shown at this zoom level</strong>.<br /><a rel='zoom_in'>Zoom in</a> or jump to a <a rel='location'>location</a>.",'');	
				bShowStatusResultsCount = false;
			}
			else if((','+response.warnings+',').indexOf(',MAX_PROPS_EXCEEDED,')>=0) {
				_bnmap.statusControl.setStatus("<strong>Over 500 Results</strong>.<br /><span style='font-size:9px'>(prohibited by MLS rules)</span><br /><br />Suggestions:<br />- Change your <a rel='criteria'>search criteria</a><br />- <a rel='zoom_in'>Zoom in</a>.<br />- Jump to a smaller <a rel='location'>location</a>.",'');	
				optClearAllMarkersOnComplete = true;
				bShowStatusResultsCount = false;
			}
			else if((','+response.warnings+',').indexOf(',NO_PROPS_FOUND,')>=0) {
				_bnmap.statusControl.setStatus("<strong>No Results Found</strong>.<br /><br />Suggestions:<br />- Expand your <a rel='criteria'>search criteria</a><br />- Reset your <a rel='criteria_reset'>search criteria</a><br />- <a rel='zoom_out'>Zoom out</a>.<br />",'');	
				bShowStatusResultsCount = false;
			}			
		}		
		
		if( optClearAllMarkersOnComplete ) {
			_bnmap.markerMgr.clearMarkers();
			_bnmap.cachedMarkers = [];
		}

		_bnmap.drawers["FilmStrip"].resetMarkers();
		if(_bnmap.drawers["ResultsGrid"]) {
			_bnmap.drawers["ResultsGrid"].resetMarkers();	
		}

		var propertyMarkerCount = 0;
	 	for(var i=0;i<response.markers.length;i++) {
	 		if( _bnmap.GetCachedMarker(zoom,response.markers[i].uid)==null ) {
	 			if( response.markers[i].type.substring(0,5)=="Prop:" ) {	 				
					var propIconOptions = null;
					var typeLwr = response.markers[i].type.substring(5).toLowerCase();
					var isPending = ((',' + (response.markers[i].flags || '').toLowerCase() + ',').indexOf(",s:pending,") >= 0);
					var isOpen = ((',' + (response.markers[i].flags || '').toLowerCase() + ',').indexOf(",open,") >= 0);
					var isREO = ((',' + (response.markers[i].flags || '').toLowerCase() + ',').indexOf(",reo,") >= 0);
					
					var activeIcon = _bnmap.options.propertyIcons.Default;
					var pendIcon = _bnmap.options.propertyIcons.Default_Pending || _bnmap.options.propertyIcons.Default;
					var openIcon = _bnmap.options.propertyIcons.Default_Open || activeIcon;
					var pendOpenIcon = _bnmap.options.propertyIcons.Default_Pending_Open || pendIcon;
					var reoIcon = _bnmap.options.propertyIcons.Default_REO || activeIcon;
					var pendReoIcon = _bnmap.options.propertyIcons.Default_Pending_REO || pendIcon;
					var openReoIcon = _bnmap.options.propertyIcons.Default_Open_REO || openIcon;
					var pendOpenReoIcon = _bnmap.options.propertyIcons.Default_Pending_Open_REO || pendOpenIcon;
					
					if(typeLwr=="residentialproperty") {
						activeIcon   = _bnmap.options.propertyIcons.Residential || activeIcon;
						pendIcon     = _bnmap.options.propertyIcons.Residential_Pending || activeIcon || pendIcon;
						openIcon     = _bnmap.options.propertyIcons.Residential_Open || activeIcon;
					 	pendOpenIcon = _bnmap.options.propertyIcons.Residential_Pending_Open || pendIcon;
					 	reoIcon      = _bnmap.options.propertyIcons.Residential_REO || activeIcon;
					 	pendReoIcon  = _bnmap.options.propertyIcons.Residential_Pending_REO || pendIcon;
					 	openReoIcon  = _bnmap.options.propertyIcons.Residential_Open_REO || openIcon;
					 	pendOpenReoIcon = _bnmap.options.propertyIcons.Residential_Pending_Open_REO || pendOpenIcon;					
					} else if(typeLwr=="commoninterest") {
						activeIcon   = _bnmap.options.propertyIcons.Condo || activeIcon;
						pendIcon     = _bnmap.options.propertyIcons.Condo_Pending || activeIcon || pendIcon;
						openIcon     = _bnmap.options.propertyIcons.Condo_Open || activeIcon;
					 	pendOpenIcon = _bnmap.options.propertyIcons.Condo_Pending_Open || pendIcon;
					 	reoIcon      = _bnmap.options.propertyIcons.Condo_REO || activeIcon;
					 	pendReoIcon  = _bnmap.options.propertyIcons.Condo_Pending_REO || pendIcon;
					 	openReoIcon  = _bnmap.options.propertyIcons.Condo_Open_REO || openIcon;
					 	pendOpenReoIcon = _bnmap.options.propertyIcons.Condo_Pending_Open_REO || pendOpenIcon;	
					} else if(typeLwr=="lotsandland") {
						activeIcon   = _bnmap.options.propertyIcons.Lot || activeIcon;
						pendIcon     = _bnmap.options.propertyIcons.Lot_Pending || activeIcon || pendIcon;
						openIcon     = _bnmap.options.propertyIcons.Lot_Open || activeIcon;
					 	pendOpenIcon = _bnmap.options.propertyIcons.Lot_Pending_Open || pendIcon;
					 	reoIcon      = _bnmap.options.propertyIcons.Lot_REO || activeIcon;
					 	pendReoIcon  = _bnmap.options.propertyIcons.Lot_Pending_REO || pendIcon;
					 	openReoIcon  = _bnmap.options.propertyIcons.Lot_Open_REO || openIcon;
					 	pendOpenReoIcon = _bnmap.options.propertyIcons.Lot_Pending_Open_REO || pendOpenIcon;	
					} else if(typeLwr=="residentialrental" || typeLwr=="rental")  {
						activeIcon   = _bnmap.options.propertyIcons.Rent || activeIcon;
						pendIcon     = _bnmap.options.propertyIcons.Rent_Pending || activeIcon || pendIcon;
						openIcon     = _bnmap.options.propertyIcons.Rent_Open || activeIcon;
					 	pendOpenIcon = _bnmap.options.propertyIcons.Rent_Pending_Open || pendIcon;
					 	reoIcon      = _bnmap.options.propertyIcons.Rent_REO || activeIcon;
					 	pendReoIcon  = _bnmap.options.propertyIcons.Rent_Pending_REO || pendIcon;
					 	openReoIcon  = _bnmap.options.propertyIcons.Rent_Open_REO || openIcon;
					 	pendOpenReoIcon = _bnmap.options.propertyIcons.Rent_Pending_Open_REO || pendOpenIcon;	
					} else if(typeLwr=="multifamily") {
						activeIcon   = _bnmap.options.propertyIcons.Multi || activeIcon;
						pendIcon     = _bnmap.options.propertyIcons.Multi_Pending || activeIcon || pendIcon;
						openIcon     = _bnmap.options.propertyIcons.Multi_Open || activeIcon;
					 	pendOpenIcon = _bnmap.options.propertyIcons.Multi_Pending_Open || pendIcon;
					 	reoIcon      = _bnmap.options.propertyIcons.Multi_REO || activeIcon;
					 	pendReoIcon  = _bnmap.options.propertyIcons.Multi_Pending_REO || pendIcon;
					 	openReoIcon  = _bnmap.options.propertyIcons.Multi_Open_REO || openIcon;
					 	pendOpenReoIcon = _bnmap.options.propertyIcons.Multi_Pending_Open_REO || pendOpenIcon;	
					} else if(typeLwr=="mobilehome") {
						activeIcon   = _bnmap.options.propertyIcons.Mobile || activeIcon;
						pendIcon     = _bnmap.options.propertyIcons.Mobile_Pending || activeIcon || pendIcon;
						openIcon     = _bnmap.options.propertyIcons.Mobile_Open || activeIcon;
					 	pendOpenIcon = _bnmap.options.propertyIcons.Mobile_Pending_Open || pendIcon;
					 	reoIcon      = _bnmap.options.propertyIcons.Mobile_REO || activeIcon;
					 	pendReoIcon  = _bnmap.options.propertyIcons.Mobile_Pending_REO || pendIcon;
					 	openReoIcon  = _bnmap.options.propertyIcons.Mobile_Open_REO || openIcon;
					 	pendOpenReoIcon = _bnmap.options.propertyIcons.Mobile_Pending_Open_REO || pendOpenIcon;	
					} else if(typeLwr=="commercial") {
						activeIcon   = _bnmap.options.propertyIcons.Comm || activeIcon;
						pendIcon     = _bnmap.options.propertyIcons.Comm_Pending || activeIcon || pendIcon;
						openIcon     = _bnmap.options.propertyIcons.Comm_Open || activeIcon;
					 	pendOpenIcon = _bnmap.options.propertyIcons.Comm_Pending_Open || pendIcon;
					 	reoIcon      = _bnmap.options.propertyIcons.Comm_REO || activeIcon;
					 	pendReoIcon  = _bnmap.options.propertyIcons.Comm_Pending_REO || pendIcon;
					 	openReoIcon  = _bnmap.options.propertyIcons.Comm_Open_REO || openIcon;
					 	pendOpenReoIcon = _bnmap.options.propertyIcons.Comm_Pending_Open_REO || pendOpenIcon;	
					}  										
					
					if(isPending) {
						if(isOpen) {
							if(isREO) 
								propIconOptions = pendOpenReoIcon;
							else
								propIconOptions = pendOpenIcon;
						}
						else {
							if(isREO) 
								propIconOptions = pendReoIcon;
							else
								propIconOptions = pendIcon;
						}
					}
					else {
						if(isOpen) {
							if(isREO) 
								propIconOptions = openReoIcon;
							else
								propIconOptions = openIcon;
						}
						else {
							if(isREO) 
								propIconOptions = reoIcon;
							else
								propIconOptions = activeIcon;
						}
					}
					
					if( propIconOptions.cachedGIcon == null ) {
						propIconOptions.cachedGIcon = new google.maps.Icon();
						propIconOptions.cachedGIcon.image = propIconOptions.main;
						propIconOptions.cachedGIcon.transparent = propIconOptions.transparent;
						propIconOptions.cachedGIcon.shadow = propIconOptions.shadow;
						propIconOptions.cachedGIcon.iconSize = new google.maps.Size(propIconOptions.width,propIconOptions.height);
						propIconOptions.cachedGIcon.shadowSize = new google.maps.Size(propIconOptions.width,propIconOptions.height);
						propIconOptions.cachedGIcon.iconAnchor = new google.maps.Point(propIconOptions.anchorX,propIconOptions.anchorY);
						propIconOptions.cachedGIcon.infoWindowAnchor = new google.maps.Point(propIconOptions.infoWindowAnchorX,propIconOptions.infoWindowAnchorY);	
					}
					
					var m = new google.maps.Marker(		 		
			 			new google.maps.LatLng(response.markers[i].lat,response.markers[i].lng),
			 			{ 
			 				title: response.markers[i].title,
							icon: propIconOptions.cachedGIcon,
							zIndexProcess: function(mrkr,b) 
								{
        							return google.maps.Overlay.getZIndex(mrkr.getPoint().lat()) + 1000000;
      							}
			 		  	} 
			 		);
					m.BN_standardIconImage = propIconOptions.main;
					m.BN_selectedIconImage = propIconOptions.selected;					
			 		m.BN_UID = response.markers[i].uid;
			 		m.BN_TYPE = response.markers[i].type;
			 		google.maps.Event.addListener(m,'click',function() { _bnmap.DisplayMarkerInfo(this); });
					google.maps.Event.addListener(m, "infowindowclose", function() {this.BN_SelectImage('standard'); this.BN_InfoWindowShowing = false;} );
			 		_bnmap.markerMgr.addMarker(m,zoom,zoom);
			 		_bnmap.CacheMarker(zoom,response.markers[i].uid,m);
					
	 			}
				else if( response.markers[i].type=="Office" ) {
					if( _bnmap.drawers["Offices"] ) {
						var m = new google.maps.Marker(		 		
							new google.maps.LatLng(response.markers[i].lat,response.markers[i].lng),
							{ 
								title: response.markers[i].title,
								icon: _bnmap.drawers["Offices"].getIcon(),
								zIndexProcess: function(mrkr,b) 
									{
										return google.maps.Overlay.getZIndex(mrkr.getPoint().lat()) + 10000000;
									}
							} 
						);
						m.BN_UID = response.markers[i].uid;
						m.BN_TYPE = response.markers[i].type;
						m.BN_INFODIV = new Element('div');
						m.BN_INFODIV.innerHTML = '<strong>' + response.markers[i].title.replace(/[\r\n]+/,'</strong><br />').replace(/[\r\n]+/g,"<br />");					
						var oid = m.BN_UID.split('$')[1];
						m.BN_INFODIV.innerHTML  += "<br /><br /><a href='officeDetail.aspx?lid="+ escape(oid)+ "&ps=500&pg=0'>More details</a>";
						google.maps.Event.addListener(m,'click',function() { _bnmap.DisplayMarkerInfo(this); });
						_bnmap.markerMgr.addMarker(m,zoom,zoom);
						_bnmap.CacheMarker(zoom,response.markers[i].uid,m);
					}
				}
				else if( response.markers[i].type=="School" ) {
					var m = new google.maps.Marker(		 		
			 			new google.maps.LatLng(response.markers[i].lat,response.markers[i].lng),
			 			{ 
			 				title: response.markers[i].title,
			 				icon: _bnmap.drawers["Schools"].getIcon(),
							zIndexProcess: function(mrkr,b) 
								{
        							return google.maps.Overlay.getZIndex(mrkr.getPoint().lat()) + 900000;
      							}
				 		} 
			 		);
			 		m.BN_UID = response.markers[i].uid;
			 		m.BN_TYPE = response.markers[i].type;					
					
					google.maps.Event.addListener(m,'click',function() { var schoolId = this.BN_UID.split("$")[1]; _bnmap.iBoxOpenFrame(_bnmap.options.baseUrl + "AdvSchool.aspx?uid=" + escape(schoolId), "School Information", {width: 700, height:600 }); return false;});
			 		_bnmap.markerMgr.addMarker(m,zoom,zoom);
			 		_bnmap.CacheMarker(zoom,response.markers[i].uid,m);
				}
	 			else {
		 			var icon = new google.maps.Icon();
		 			icon.image = _bnmap.options.baseUrl + 'MapIcon.aspx/default/' + escape(response.markers[i].uid.replace(/\|/g,'/')) + '/icon.png' ;
					icon.transparent = _bnmap.options.baseUrl + 'Images/MapIcons/Transparent.png';
					icon.shadow = _bnmap.options.baseUrl + 'Images/MapIcons/Shadow.png';
		 			//var maxDim = (response.markers[i].type=='Region' ? 200 : (response.markers[i].type=='AreaGroup' ? 170 : 140) );
					var maxDim = 100;
					if(response.markers[i].type=='Region') {
						maxDim = zoom < 9 ? 80 : 110;
					}
					else if (response.markers[i].type=='AreaGroup') {
						maxDim = zoom < 11 ? 75 : 105;	
					}
					else {
						maxDim = zoom < 11 ? 70 : 90;
					}		
					var minDim = 60
					/*var iconW = 0.25 *_bnmap.map.getSize().width * response.markers[i].dx / (bounds.getNorthEast().lng()-bounds.getSouthWest().lng()); 
		 			var iconH = 0.25 *_bnmap.map.getSize().height * response.markers[i].dy / (bounds.getNorthEast().lat()-bounds.getSouthWest().lat()); 		 			
		 			iconH = iconW = Math.max(40,Math.min(maxDim,Math.max(iconW,iconH)));		 			
					*/
					var iconSz = minDim + response.markers[i].sz * (maxDim-minDim); //sz is [0-1] ratio
					var iconW, iconH;
					iconW=iconH=iconSz;
					icon.iconSize = new google.maps.Size(iconW,iconH);					
					icon.shadowSize = new google.maps.Size(iconW *1.1,iconH *1.1);
					icon.iconAnchor = new google.maps.Point(iconW/2,iconH/2);
					icon.infoWindowAnchor = new google.maps.Point(iconW/2,iconH/2);
			 		var m = new google.maps.Marker(		 		
			 			new google.maps.LatLng(response.markers[i].lat,response.markers[i].lng),
			 			{ 
			 				title: response.markers[i].title,
			 				icon: icon,
							clickable: (_bnmap.options.communityInfoEnabled ? true:false)
				 		} 
			 		);
			 		m.BN_UID = response.markers[i].uid;
			 		m.BN_TYPE = response.markers[i].type;
			 		if( _bnmap.options.communityInfoEnabled ) {
						google.maps.Event.addListener(m,'click',function() { _bnmap.DisplayMarkerInfo(this); });
					}
			 		_bnmap.markerMgr.addMarker(m,zoom,zoom);
			 		_bnmap.CacheMarker(zoom,response.markers[i].uid,m);
			 	}
		 	}
			
			if( response.markers[i].type.substring(0,5)=="Prop:" ) {
				// needs to be re-done for cached markers too
 				propertyMarkerCount++;
				_bnmap.drawers["FilmStrip"].addMarker(response.markers[i]);
				if(_bnmap.drawers["ResultsGrid"]) {
					_bnmap.drawers["ResultsGrid"].addMarker(response.markers[i]);
				}
			}
	 	}
		
		if(propertyMarkerCount>0 && bShowStatusResultsCount && _bnmap.statusControl){
			var countMsg = "<strong>" + propertyMarkerCount + " Results</strong>.";
			if(_bnmap.drawers["TopTools"] && _bnmap.drawers["TopTools"].isButtonTypeSupported('savealert')) {
				countMsg = "<a style='float:right' rel='savealert'><img src='"+ _bnmap.options.imageResources.statusSaveAlertBtn +"' border='0' style='display:block'></a>" + countMsg;
			}
			_bnmap.statusControl.setStatus(countMsg);
		}
		
		if(_bnmap.shapeTool && _bnmap.shapeTool.isDrawing() ){
			_bnmap.makeAllMarkersUnclickable();
		}
		
		_bnmap.drawers["FilmStrip"].validateDisplay();
		if(_bnmap.drawers["ResultsGrid"]) {
			_bnmap.drawers["ResultsGrid"].validateDisplay();
		}
	 },
	 onFailure: function(response){
		var msgHtml = 'An error occured';
		if(response.responseText && response.responseText!='')
			msgHtml += ':<br />' + response.responseText
		_bnmap.statusControl.setStatus(msgHtml,'error');
		BNDebugLog("FAILED:");	
	 	BNDebugLog(response.statusText);
	 	BNDebugShowHTML(response.responseText);
	 }
	});
	_bnmap.statusControl.setStatus('Updating Map','wait');
	this.jsonRequests.MapLocationChangedRequest.send(jsonParam);
};
BNMap.prototype.onResize = function() {
	var map = this;
	for(var i=0;i<this.drawerIds.length;i++) {
		this.drawers[this.drawerIds[i]].onMapResized();
	}
	this.RefreshData(false);		
};
BNMap.prototype.DisplayMarkerInfo = function(marker) {		
	if(this.shapeTool && this.shapeTool.isDrawing()) {
		return;
	}
	marker.BN_SelectImage("selected");	
	if(this.drawers["TopTools"]) {
		this.drawers["TopTools"].retractAnyOpenSlider(true, null);
	}
	if( marker.BN_INFODIV ) {
		marker.openInfoWindow(marker.BN_INFODIV);
		marker.BN_InfoWindowShowing = true;
	}
	else {
		marker.BN_INFODIV = new Element('div');
		marker.BN_INFODIV.innerHTML = "<center><img src='"+ this.options.waitIcon+"' /></center>";
		marker.openInfoWindow(marker.BN_INFODIV);
		marker.BN_InfoWindowShowing = true;
		var _bnmap = this;
		var infoReq = new Json.Remote(this.options.baseUrl + "AdvSearchJSON.aspx?Cmd=GetMarkerInfo", {
			onComplete: function(response) {
					marker.closeInfoWindow();				
					marker.BN_INFODIV.innerHTML = response;						
					if( marker.BN_TYPE.indexOf("Prop:")==0 ) {
						if(_bnmap.options.imageResources.moreDetailsBtn) {
							var detailLink = marker.BN_INFODIV.getElement('.MapLink_Details a');
							if(detailLink) {
								detailLink.setText('');
								detailLink.adopt(new Element('img',{src: _bnmap.options.imageResources.moreDetailsBtn, border: 0, alt:'More Details'}));	
							}
						}
						
						var d = marker.BN_INFODIV.getElement('.MapLink_Buttons');
						if(d==null) {
							d = new Element('div');
							$(marker.BN_INFODIV).adopt(d);
						}
						var l = new Element('a', { 
							'href': '#',
							'events': {
								'click': function(event) {
									var event = new Event(event);
									event.stop();
									var latlng = marker.getLatLng();
									//alert('open street view:' + latlng.lat() + ',' + latlng.lng());
									var myPano = new GStreetviewPanorama($('mapDrawer_StreetView_canvas'), {'latlng': latlng } );
									google.maps.Event.addListener(myPano, "error", function(errorCode) {
										  if (errorCode == FLASH_UNAVAILABLE) {
											alert("Error: Flash doesn't appear to be supported by your browser");
											return;
										  }
									});
									$('mapDrawer_StreetView').setStyle('display','block');
									return false;
								}
							},
							styles: {float: 'left', 'margin-right': '4px'}
						});
						if(_bnmap.options.imageResources.streetViewIcon) {
							l.adopt(new Element('img',{src: _bnmap.options.imageResources.streetViewIcon, border: 0, alt:'Street View'}));	
						}
						else {
							l.setText('Street view');
						}
						d.adopt(l);
						var lz = new Element('a', { 
							'href': '#',
							'events': {
								'click': function(event) {
									var event = new Event(event);
									event.stop();
									var latlng = marker.getLatLng();
									_bnmap.map.setCenter(latlng);
									_bnmap.map.setZoom(18);
									return false;
								}
							},
							styles: {float: 'left', 'margin-right': '4px'}
						});
						if(_bnmap.options.imageResources.zoomInIcon) {
							lz.adopt(new Element('img',{src: _bnmap.options.imageResources.zoomInIcon, border: 0, alt: 'Zoom In' }));	
						}
						else {
							lz.setText('Zoom In');
						}
						/*(new Element('img'), {
							src: _bnmap.options.imageResources.zoomInIcon,
							border: 0,
							valign: 'absmiddle'
						}).injectTop(lz);*/						
						d.adopt(lz);
						
					}
					// hook up ibox links to a elements with class MapIboxLink
					$(marker.BN_INFODIV).getElements(".MapIboxLink").each(function(linkEl) {
						linkEl.addEvent('click', function(event) {
							var event = new Event(event);
							_bnmap.iBoxOpenFrame(linkEl.href, linkEl.title, {width: 850, height:700 });
							event.stop();
							return false;								  
						});
					});
					
					// need to wait for any/all images to be loaded before we open the info window
					var _marker = marker;
					marker.BN_INFODIV.check_state_and_open = function() {
						var waitImages = $(_marker.BN_INFODIV).getElements('img');
						var loaded = true;
						for(var i=0;waitImages!=null && i<waitImages.length;i++) {
							if (waitImages[i].naturalHeight == 0 || waitImages[i].naturalWidth == 0 || waitImages[i].complete == false) {      
								loaded = false;
								break;
							}
						}
						if( loaded ) {
							_marker.openInfoWindow(_marker.BN_INFODIV); // reopen to set size properly
							_marker.BN_InfoWindowShowing = true;
							_marker.BN_SelectImage("selected");
						}
						else {
							_marker.BN_INFODIV.check_state_and_open.delay(300);	
						}
					}
					
					marker.BN_INFODIV.check_state_and_open();					
			},
			onFailure: function(response) {				 	
				BNDebugLog("FAILED:");	
				BNDebugLog(response.statusText);
				BNDebugShowHTML(response.responseText);
				marker.BN_INFODIV.innerHTML = "An error occurred";
		  }
		});
		infoReq.send({ 'type': marker.BN_TYPE, 'uid': marker.BN_UID });
	}
};
BNMap.prototype.RegisterDrawer = function(drawer) {
	drawer._bnmap = this;
	this.drawerIds.push(drawer.id);
	this.drawers[drawer.id] = drawer;
};
BNMap.prototype.iBoxOpenFrame = function(url, title, param) {
    if(param==null)
    	param={height:500, width:900};
	if(param.height > window.getHeight()-90) {
		param.height = window.getHeight()-90;
	}
    var htm = "<iframe frameborder=\"0\" id=\"tmFrame\" style=\"width:"+(param.width-0)+"px;height:"+(param.height-0)+"px\" src=\""+url+"\"></iframe>"
    iBox.show(htm, title, param);	
};

// ShapeTool
var BNShapeTool = new Class({
	initialize: function(bnmap,options) {
		this._bnmap = bnmap;
		this.options = options;
		this.drawingMode = 'NOT_DRAWING';
		this.currentPolygon = null;
		this.vertexAnchorIcon = new google.maps.Icon();
		this.vertexAnchorIcon.image = options.vertexIcon.url; //"mapIcons/vertexAnchor.png";
		this.vertexAnchorIcon.iconSize =  new google.maps.Size(options.vertexIcon.width,options.vertexIcon.height);
		this.vertexAnchorIcon.iconAnchor = new google.maps.Point(Math.ceil(options.vertexIcon.width/2),Math.ceil(options.vertexIcon.height/2));	
	},
	startDrawing: function(mode) {
		if(this.drawingMode!=mode || this.currentPolygon==null) {
			this.resetDrawing_internal(false);
			
			this.currentPolygon = new google.maps.Polygon([],'blue',3,0.7,'blue',0.2,null);
			this._bnmap.map.addOverlay(this.currentPolygon);
			
			this.drawingMode = mode;
			
			var shapeTool = this;
	
			this.currentPolygon.isInInteractiveDrawing = true;
			this.currentPolygon.drawShadowRectOnMoveHandler = null;
			
			this._bnmap.makeAllMarkersUnclickable();
			
			if(mode=='POLYGON') {
				this.currentPolygon.enableDrawing();
			}
			else if(mode=="RECTANGLE") {
				this.currentPolygon.enableDrawing({maxVertices: 2});
		
				this.currentPolygon.drawShadowRectOnMoveHandler = GEvent.addListener(this._bnmap.map,"mousemove",function(latLng) {
					shapeTool.drawPolyRectShadow(shapeTool.currentPolygon,latLng);
				});
			}
			
			GEvent.addListener(this.currentPolygon,'endline',function() {	
				if(shapeTool.drawingMode == "RECTANGLE") {															   
					GEvent.removeListener(shapeTool.currentPolygon.drawShadowRectOnMoveHandler);
					shapeTool.currentPolygon.drawShadowRectOnMoveHandler = null;
					shapeTool.currentPolygon.isInInteractiveDrawing = false;
					shapeTool._bnmap.makeAllMarkersClickable();
					shapeTool.CommitShadowRectToEditableRect(shapeTool.currentPolygon);
					shapeTool.fireEvent('shapeCreated');
				}
				else {
					(function() {
						GEvent.clearListeners(shapeTool.currentPolygon,'endline');
						GEvent.clearListeners(shapeTool.currentPolygon,'cancelline');
						shapeTool.currentPolygon.enableEditing();
						shapeTool.currentPolygon.isInInteractiveDrawing = false;
						shapeTool._bnmap.makeAllMarkersClickable();
						GEvent.addListener(shapeTool.currentPolygon,'lineupdated',function() {
							shapeTool.fireEvent('shapeModified');														  
						});	
						shapeTool.fireEvent('shapeCreated');
						shapeTool.fireEvent('shapeModified');
					}).delay(1);	
				}
			});
			GEvent.addListener(this.currentPolygon,'cancelline',function() {
				if(shapeTool.drawingMode == "RECTANGLE") {			
					GEvent.removeListener(shapeTool.currentPolygon.drawShadowRectOnMoveHandler);
					shapeTool.currentPolygon.drawShadowRectOnMoveHandler = null;
					if(shapeTool.currentPolygon.getVertexCount()<=2) {
						// a shape is not defined, we only have one corner or less
						shapeTool.resetDrawing();	
					}
					else {
						shapeTool.currentPolygon.isInInteractiveDrawing = false;
						shapeTool._bnmap.makeAllMarkersClickable();
						shapeTool.CommitShadowRectToEditableRect(shapeTool.currentPolygon);						
						shapeTool.fireEvent('shapeCreated');
					}
				}
				else {
					shapeTool.resetDrawing();	
				}
			});
		}
		else {
			// nothing to do, just resuming an existing drawing	
		}
	},
	isDrawing: function() {
		return (this.drawingMode=="NOT_DRAWING" || this.currentPolygon==null || this.currentPolygon.isInInteractiveDrawing==false ? false : true);	
	},
	abortInteractiveDrawing: function() {
		if(this.currentPolygon!=null && this.currentPolygon.isInInteractiveDrawing==true) {
			this.resetDrawing_internal(false);	
		}
	},
	resetDrawing: function() {
		this.resetDrawing_internal(true);	
	},
	resetDrawing_internal: function(withEvent) {
		if(this.currentPolygon!=null) {
			if(this.currentPolygon.shadowRect!=null) {
				this._bnmap.map.removeOverlay(this.currentPolygon.shadowRect);	
				this.currentPolygon.shadowRect = null;
			}
			if(this.currentPolygon.vertexAnchors!=null) {
				for(var i=0;i<this.currentPolygon.vertexAnchors.length;i++){
					this._bnmap.map.removeOverlay(this.currentPolygon.vertexAnchors[i]);					
				}
				this.currentPolygon.vertexAnchors = null;
			}
			if(this.currentPolygon.drawShadowRectOnMoveHandler!=null) {
				GEvent.removeListener(this.currentPolygon.drawShadowRectOnMoveHandler);
				this.currentPolygon.drawShadowRectOnMoveHandler = null;
			}
			GEvent.clearListeners(this.currentPolygon,'endline');
			GEvent.clearListeners(this.currentPolygon,'cancelline');
			GEvent.clearListeners(this.currentPolygon,'lineupdated');
			this.currentPolygon.disableEditing();
			this._bnmap.map.removeOverlay(this.currentPolygon);
			this.currentPolygon = null;			
		}
		this.drawingMode = "NOT_DRAWING";	
		this._bnmap.makeAllMarkersClickable();
		if(withEvent) {
			this.fireEvent('reset');	
		}
	},
	clearShape: function() {
		var saveMode = this.drawingMode;
		this.resetDrawing_internal(false);
		this.startDrawing(saveMode);
		this.fireEvent('shapeModified');
	},
	drawPolyRectShadow: function(poly,latLng) {
		// do not swamp the browser with redraws
		if(poly.drawRectTimeout) {
			window.clearTimeout(poly.drawRectTimeout);
		}
		var shapeTool = this;
		poly.drawRectTimeout = window.setTimeout(function() { shapeTool.drawPolyRectShadow_immediate(poly,latLng); },30);
	},
	drawPolyRectShadow_immediate: function(poly,latLng) {		
		var vCount = poly.getVertexCount()		
				
		if(vCount>0) {
			if(poly.shadowRect!=null)
				this._bnmap.map.removeOverlay(poly.shadowRect);
			
			poly.shadowRect = new google.maps.Polygon([
				poly.getVertex(0), 
				new google.maps.LatLng(poly.getVertex(0).lat(), latLng.lng()),
				latLng,
				new google.maps.LatLng(latLng.lat(), poly.getVertex(0).lng()),
				poly.getVertex(0)
			],'blue',0,0,'blue',0.2,null);
			this._bnmap.map.addOverlay(poly.shadowRect);
		}
	},
	drawPolyRectDragShadow: function(draggedAnchor,poly,latLng) {
		if(poly.shadowRect!=null)
			this._bnmap.map.removeOverlay(poly.shadowRect);

		var movedIndex = -1;
		for(var i=0;i<4;i++) {
			if(this.currentPolygon.vertexAnchors[i]==draggedAnchor) {
				movedIndex = i;
			}
		}
		if(movedIndex>=0) {
			var vertices = [];
			
			for(var i=0;i<4;i++) {
				if(i==movedIndex) {
					vertices[i] = latLng;
				}
				else if(i==((movedIndex+4+1)%4) || i==((movedIndex+4-1)%4)) {
					var vLatLng = poly.getVertex(i);
					var mLatLng = poly.getVertex(movedIndex);
					if(vLatLng.lat()==mLatLng.lat()) {
						vertices[i] = new GLatLng(latLng.lat(),vLatLng.lng());
						poly.vertexAnchors[i].setLatLng(vertices[i]);
					}
					else {
						vertices[i] = new GLatLng(vLatLng.lat(),latLng.lng());
						poly.vertexAnchors[i].setLatLng(vertices[i]);
					}
				}
				else {
					vertices[i] = poly.getVertex(i);
				}
			}	
			vertices.push(vertices[0]);		
			poly.shadowRect = new google.maps.Polygon(vertices,'blue',1,0.5,'blue',0.1,null);
			this._bnmap.map.addOverlay(poly.shadowRect);
		}
	},
	CommitShadowRectToEditableRect: function(poly) {
		var shapeTool = this;
		(function() {
			shapeTool._bnmap.map.removeOverlay(poly);
			if(poly.vertexAnchors) {
				for(var i=0;i<poly.vertexAnchors.length;i++) {
					shapeTool._bnmap.map.removeOverlay(poly.vertexAnchors[i]);				
				}
				poly.vertexAnchors=null;
			} 
		}).delay(10);
		
		// save properties set on current polygon and reapply after copying shadowRect
		var save_isInInteractiveDrawing = shapeTool.currentPolygon.isInInteractiveDrawing;
		
		shapeTool.currentPolygon = poly.shadowRect;
		
		// restore saved properties
		shapeTool.currentPolygon.isInInteractiveDrawing = save_isInInteractiveDrawing;
				
		shapeTool.currentPolygon.shadowRect = null;
		shapeTool.currentPolygon.setStrokeStyle({color:'blue',weight:3,opacity:0.7});
		shapeTool.currentPolygon.setFillStyle({color:'blue',opacity:0.2});
		shapeTool.currentPolygon.vertexAnchors = [];
		for(var i=0;i<4;i++) {
			var ancMarker = new GMarker(shapeTool.currentPolygon.getVertex(i), {
				icon: shapeTool.vertexAnchorIcon,
				dragCrossMove: false,
				draggable: true,
				bouncy: false,
				zIndexProcess: function(mrkr,b) 
				{
					return google.maps.Overlay.getZIndex(ancMarker.getPoint().lat()) + 1000000000;
				}
			})
			shapeTool.currentPolygon.vertexAnchors[i]=ancMarker;
			shapeTool._bnmap.map.addOverlay(ancMarker);
			GEvent.addListener(ancMarker,'drag',function(latLng) {
				shapeTool.drawPolyRectDragShadow(this,shapeTool.currentPolygon,latLng);
			});
			GEvent.addListener(ancMarker,'dragend',function() {
					shapeTool.CommitShadowRectToEditableRect(shapeTool.currentPolygon);
			});
		}
		shapeTool.fireEvent('shapeModified');
	},
	getShapeParamString: function() {
		if(this.currentPolygon==null || this.currentPolygon.isInInteractiveDrawing==true)
			return null;
			
		switch(this.drawingMode) {
			case "RECTANGLE":				
				var bounds = this.currentPolygon.getBounds();
				if(bounds) {
				return "#RECT#[(" + bounds.getNorthEast().lat() + "," + bounds.getNorthEast().lng() + ")::(" + bounds.getSouthWest().lat() + "," + bounds.getSouthWest().lng() + ")]";
				}
				else
					return null;
				break;
			case "POLYGON":
				if(this.currentPolygon.getVertexCount()<4) {
					return null; // gPolygon's last vertex is the first, les than 3 actual corners is not good.	
				}
				var s = "#POLY#";
				for(var i=0;i<this.currentPolygon.getVertexCount()-1;i++) { // ignore closing vertex
					s+= "(" + this.currentPolygon.getVertex(i).lat() + "," + this.currentPolygon.getVertex(i).lng() + ")";	
				}
				return s;
				break;			
		}
		return null;
	}
});	
BNShapeTool.implement(new Events);
	
// Map Drawers
var BNMapDrawer = new Class({
	initialize: function(id, elem, title, options) {
		this._bnmap = null;
		this.id = id;
		this.elem = elem;
		this.title = title;
		this.options = options;
	},
	onMapResized: Class.empty,
	onMapZoomChanged: Class.empty,	
	getDrawerEnabledLayers: function() { return []; },
	initHelp: function() {
		if( this.options!=null && this.options.callout!=null ) {
			var trgImg = $(this.getDrawerElemId(this.options.callout.triggerImgId));
			var contentDivId = this.getDrawerElemId(this.options.callout.contentDivId);
			var templateDivId = this.getDrawerElemId(this.options.callout.templateDivId);
			var handlePosition = this.options.callout.handlePosition;
			var title = this.options.callout.title;
			var _bnmap = this._bnmap;
			var _drawer = this;
			trgImg.ShowCallout = function() {
				var calloutDivId = _bnmap.mapDivId + '__' + contentDivId + "__calloutDiv";
				var mapDiv = $(_bnmap.mapDivId);
				var d = new Element('div', {
					id: calloutDivId,
					styles: {
						position: 'absolute',
						top: '0px',
						left: '0px',
						color: 'black',
						opacity: 0,
						'z-index': 2147483647
					},
					className: 'AdvMapCalloutDiv'
				});
				d.closeCallout = function() {
					d.effect('opacity', {
						duration: 100,
						transition: Fx.Transitions.linear,
						wait: false,
						onComplete: function() {
							d.remove();
						}
					}).start(1,0);
					_drawer.ACTIVE_CALLOUT_DIV = null;
				}
				d.setHTML($(templateDivId).innerHTML);
				
				if(_drawer.options.callout && _drawer.options.callout.wide==true) {
					var mainCell = d.getElement('td[id=mapTemplate_callout_mainCell]');
					var bottomCell = d.getElement('td[id=mapTemplate_callout_bottomCell]');
					if(mainCell) {
						mainCell.setStyle('background-image', 'url(' + mainCell.getAttribute("BN_WIDEIMG") +')');
						mainCell.setStyle('width', parseInt(mainCell.getAttribute("BN_WIDEWIDTH")));																				
					}
					if(bottomCell) {
						bottomCell.setStyle('background-image', 'url(' + bottomCell.getAttribute("BN_WIDEIMG") +')');							
					}
				}
				else {
					if(mainCell) {
						mainCell.setStyle('background-image', 'url(' + mainCell.getAttribute("BN_BASEIMG") +')');
						mainCell.setStyle('width', parseInt(mainCell.getAttribute("BN_BASEWIDTH")));																				
					}
					if(bottomCell) {
						bottomCell.setStyle('background-image', 'url(' + bottomCell.getAttribute("BN_BASEIMG") +')');							
					}	
				}
				d.getElement('*[class=AdvMapCalloutTitle]').setText(title);		
				d.getElement('*[class=AdvMapCalloutContent]').setHTML($(contentDivId).innerHTML);
				d.getElement('*[id=mapTemplate_callout_handleCell]').setStyle('verticalAlign',handlePosition); 
				
				var oldCalloutDiv = $(document.body).getElement('div[id='+calloutDivId+']')
				if( oldCalloutDiv ) {
					oldCalloutDiv.closeCallout();	
				}				
				d.injectInside($(document.body));

				var handleImgCoords = d.getElement('img[id=mapTemplate_callout_handleImg]').getCoordinates();				
				var trgImageCoords = trgImg.getCoordinates();
				var topPos = trgImageCoords.top + Math.ceil(trgImageCoords.height/2) - (handleImgCoords.top + Math.ceil(handleImgCoords.height/2));
				var leftPos = trgImageCoords.left + trgImageCoords.width;
				d.setStyles({ top: topPos + 'px', left: leftPos + 'px'});
				_drawer.ACTIVE_CALLOUT_DIV = d;
				d.effect('opacity', {duration: 100,transition: Fx.Transitions.linear, wait: false}).start(0,1);				
			};
			trgImg.addEvent('click',trgImg.ShowCallout);
			if( this.options.callout.autoShow == true ) {
				var cookieName = "callout_"+contentDivId+"_autoshown";
				if( Cookie.get(cookieName) == false ) {
					window.setTimeout(trgImg.ShowCallout,1000);
					Cookie.set(cookieName,"true"); // session cookie
				}
			}
		}
	},
	getDrawerElemId: function(elemId) {
		return elemId.replace("~",this.elem.id);
	}
});


var BNMapPropertySearchDrawer = BNMapDrawer.extend({
    initialize: function(id, elem, title, options) {
		this.parent(id, elem, title, options);
		this.searchParameters = {
			PropertyTypes: [ 'RES' ],
			Price: {'min': -1, 'max': -1},
			Bed: {'min': -1, 'max': -1},
			Bath: {'min': -1, 'max': -1},
			SqFt: {'min': -1, 'max': -1},
			LotSize: {'min': -1, 'max': -1},
			YearBuilt: {'min': -1, 'max': -1},
			Parking: {'min': -1, 'max': -1},
			Open: false,
			REO: false,
			NoShort: false,
			Status: ''
		}
	},
	onMapZoomChanged: function(zoom) {
		if(this.ACTIVE_CALLOUT_DIV && this.ACTIVE_CALLOUT_DIV.closeCallout)
			this.ACTIVE_CALLOUT_DIV.closeCallout();
			
		/*if( zoom < 14 ) {
			if( this.elem.style.display== 'block' )
				this.elem.style.display='none';
		}
		else { // if( zoom >= 14 ) */
			this.elem.style.display = 'block';
			if( !this.UIInitialized ) {
				var baseElemId = this.elem.id;	
				this.initHelp();
				var searchDrawer = this; // create enclosure for event handlers
				// assign type cb event handlers				
				$(baseElemId + '_cbRES').addEvent('click',function() { searchDrawer.setSearchPropertyType('RES', $(baseElemId + '_cbRES').checked); });
				$(baseElemId + '_cbCOND').addEvent('click',function() { searchDrawer.setSearchPropertyType('COND', $(baseElemId + '_cbCOND').checked); });
				$(baseElemId + '_cbLAND').addEvent('click',function() { searchDrawer.setSearchPropertyType('LAND', $(baseElemId + '_cbLAND').checked); });
				$(baseElemId + '_cbRENT').addEvent('click',function() {	searchDrawer.setSearchPropertyType('RENT', $(baseElemId + '_cbRENT').checked); });
				
				if($(baseElemId + '_cbMULT')) {
					$(baseElemId + '_cbMULT').addEvent('click',function() {	searchDrawer.setSearchPropertyType('MULT', $(baseElemId + '_cbMULT').checked); });
				}
				if($(baseElemId + '_cbMOB')) {
					$(baseElemId + '_cbMOB').addEvent('click',function() {	searchDrawer.setSearchPropertyType('MOB', $(baseElemId + '_cbMOB').checked); });
				}
				if($(baseElemId + '_cbCOMM')) {
					$(baseElemId + '_cbCOMM').addEvent('click',function() {	searchDrawer.setSearchPropertyType('COMM', $(baseElemId + '_cbCOMM').checked); });
				}
						
				// beds
				this.BedSlider = new RangePicker( 
					$(baseElemId + '_BedSlider_Container'),
					$(baseElemId + '_BedSlider_MinKnob'),
					{
						mode: 'horizontal',
						offset: 0,
						start: 0,
						end: 8,
						steps: 8,
						onChange: function(value) {
							var lbl = '';
							if( value.minpos==this.options.start && value.maxpos==this.options.end )
								lbl = "Any";
							else if( value.minpos==this.options.start )
								lbl = value.maxpos + " or fewer";
							else if( value.maxpos==this.options.end )
								lbl = value.minpos + " or more";
							else
								lbl = value.minpos + ' to ' + value.maxpos;
								
							$(baseElemId +"_BedLabel").innerHTML = lbl;
						},
						onComplete: function(value) {	
							searchDrawer.setSearchSliderVal('Bed', value.minpos==this.options.start ? -1 : value.minpos, value.maxpos==this.options.end ? -1 : value.maxpos);
							BNDebugLog('bed slider update: ' +  value.minpos + ',' + value.maxpos);
						}
					},
					$(baseElemId + '_BedSlider_MaxKnob')
				);
				this.BedSlider.setMin(0);
				this.BedSlider.setMax(9);
				
				// baths
				this.BathSlider = new RangePicker( 
					$(baseElemId + '_BathSlider_Container'),
					$(baseElemId + '_BathSlider_MinKnob'),
					{
						mode: 'horizontal',
						offset: 0,
						start: 0,
						end: 8,
						steps: 8,
						onChange: function(value) {
							var lbl = '';
							if( value.minpos==this.options.start && value.maxpos==this.options.end )
								lbl = "Any";
							else if( value.minpos==this.options.start )
								lbl = value.maxpos + " or fewer";
							else if( value.maxpos==this.options.end )
								lbl = value.minpos + " or more";
							else
								lbl = value.minpos + ' to ' + value.maxpos;
								
							$(baseElemId +"_BathLabel").innerHTML = lbl;
						},
						onComplete: function(value) {	
							searchDrawer.setSearchSliderVal('Bath', value.minpos==this.options.start ? -1 : value.minpos, value.maxpos==this.options.end ? -1 : value.maxpos);
							//BNDebugLog('bath slider update: ' +  value.minpos + ',' + value.maxpos);
						}
					},
					$(baseElemId + '_BathSlider_MaxKnob')
				);
				this.BathSlider.setMin(0);
				this.BathSlider.setMax(9);
				
				// price
				this.PriceSlider = new RangePicker( 
					$(baseElemId + '_PriceSlider_Container'),
					$(baseElemId + '_PriceSlider_MinKnob'),
					{
						mode: 'horizontal',
						offset: 0,
						start: 0,
						end: 71,
						steps: 72,
						stepValueMap: [0,500,600,700,800,900,1000,1250,1500,1750,2000,2250,2500,2750,3000,3250,3500,3750,4000,4500,5000,6000,7000,8000,100000,125000,150000,175000,200000,225000,250000,275000,300000,325000,350000,375000,400000,425000,450000,475000,500000,550000,600000,650000,700000,750000,800000,850000,900000,950000,1000000,1250000,1500000,1750000,2000000,2250000,2500000,2750000,3000000,3250000,3500000,3750000,4000000,4250000,4500000,4750000,5000000,6000000,7000000,8000000,9000000,10000000],
						valueToDisplayFormat: function(num) {
							num = num.toString().replace(/\$|\,/g,'');
							if(isNaN(num))
								num = "0";
							var mod="";
							if(num>=1000) {
								num=num/1000;
								mod="k";
							}
							if(num>=1000) {
								num=num/1000;
								mod="M";
							}
							sign = (num == (num = Math.abs(num)));
							num = Math.floor(num*100+0.50000000001);
							cents = num%100;
							num = Math.floor(num/100).toString();
							if(cents<10)
								cents = "0" + cents;
							for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
								num = num.substring(0,num.length-(4*i+3))+','+
							num.substring(num.length-(4*i+3));
							return (((sign)?'':'-') + '$' + num + (cents>0 ? '.' + cents : '') + mod);
						},
						onChange: function(value) {
							var lbl = '';
							if( value.minpos==this.options.start && value.maxpos==this.options.end )
								lbl = "Any";
							else if( value.minpos==this.options.start )
								lbl = this.options.valueToDisplayFormat(this.options.stepValueMap[value.maxpos]) + " or less";
							else if( value.maxpos==this.options.end )
								lbl = this.options.valueToDisplayFormat(this.options.stepValueMap[value.minpos]) + " or more";
							else
								lbl = this.options.valueToDisplayFormat(this.options.stepValueMap[value.minpos]) + ' to ' + this.options.valueToDisplayFormat(this.options.stepValueMap[value.maxpos]);
								
							$(baseElemId +"_PriceLabel").innerHTML = lbl;
						},
						onComplete: function(value) {	
							searchDrawer.setSearchSliderVal('Price', value.minpos==this.options.start ? -1 : this.options.stepValueMap[value.minpos], value.maxpos==this.options.end ? -1 : this.options.stepValueMap[value.maxpos]);						
							//BNDebugLog('price slider update: ' +  value.minpos + ',' + value.maxpos);
						}
					},
					$(baseElemId + '_PriceSlider_MaxKnob')
				);
				this.PriceSlider.hideRange(1,24);
				this.PriceSlider.setMin(0);
				this.PriceSlider.setMax(72);
				
				// advanced search panel
				// SqFt
				if($(baseElemId + '_SqFtSlider_Container')) {
					this.SqFtSlider = new RangePicker( 
						$(baseElemId + '_SqFtSlider_Container'),
						$(baseElemId + '_SqFtSlider_MinKnob'),
						{
							mode: 'horizontal',
							offset: 0,
							start: 0,
							end: 31,
							steps: 32,
							stepValueMap: [0,500,750,1000,1250,1500,1750,2000,2150,2500,2750,3000,3250,3500,3750,4000,4150,4500,4750,5000,5250,5500,5750,6000,6150,6500,6750,7000,7250,7500,7750,8000],
							valueToDisplayFormat: function(num) {
								num = num.toString().replace(/\$|\,/g,'');
								if(isNaN(num))
									num = "0";								
								sign = (num == (num = Math.abs(num)));
								num = Math.floor(num*100+0.50000000001);
								cents = num%100;
								num = Math.floor(num/100).toString();
								if(cents<10)
									cents = "0" + cents;
								for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
									num = num.substring(0,num.length-(4*i+3))+','+
								num.substring(num.length-(4*i+3));
								return (((sign)?'':'-') + num + (cents>0 ? '.' + cents : ''));
							},
							onChange: function(value) {
								var lbl = '';
								if( value.minpos==this.options.start && value.maxpos==this.options.end )
									lbl = "Any";
								else if( value.minpos==this.options.start )
									lbl = this.options.valueToDisplayFormat(this.options.stepValueMap[value.maxpos]) + " or less";
								else if( value.maxpos==this.options.end )
									lbl = this.options.valueToDisplayFormat(this.options.stepValueMap[value.minpos]) + " or more";
								else
									lbl = this.options.valueToDisplayFormat(this.options.stepValueMap[value.minpos]) + ' to ' + this.options.valueToDisplayFormat(this.options.stepValueMap[value.maxpos]);
									
								$(baseElemId +"_SqFtLabel").innerHTML = lbl;
							},
							onComplete: function(value) {	
								searchDrawer.setSearchSliderVal('SqFt', value.minpos==this.options.start ? -1 : this.options.stepValueMap[value.minpos], value.maxpos==this.options.end ? -1 : this.options.stepValueMap[value.maxpos]);						
							}
						},
						$(baseElemId + '_SqFtSlider_MaxKnob')
					);
					this.SqFtSlider.setMin(0);
					this.SqFtSlider.setMax(32);
				}

				// Lot Size
				if($(baseElemId + '_LotSizeSlider_Container')) {
					this.LotSizeSlider = new RangePicker( 
						$(baseElemId + '_LotSizeSlider_Container'),
						$(baseElemId + '_LotSizeSlider_MinKnob'),
						{
							mode: 'horizontal',
							offset: 0,
							start: 0,
							end: 11,
							steps: 12,
							stepValueMap: [0,2000,4500,6500,8000,10890,21780,43560,87120,130680,174240,217800],
							valueToDisplayFormat: function(num) {
								switch(num) {
									case 0: return "0";
									case 2000: return "2,000 SqFt";
									case 4500: return "4,500 SqFt";
									case 6500: return "6,500 SqFt";
									case 8000: return "8,000 SqFt";
									case 10890: return "10,890 SqFt (0.25 Acre)";
									case 21780: return "21,780 SqFt (0.5 Acre)";
									case 43560: return "1 Acre";
									case 87120: return "2 Acres";
									case 130680: return "3 Acres";
									case 174240: return "4 Acres";
									case 217800: return "5 Acres";
									default: return "?";									
								}
							},
							onChange: function(value) {
								var lbl = '';
								if( value.minpos==this.options.start && value.maxpos==this.options.end )
									lbl = "Any";
								else if( value.minpos==this.options.start )
									lbl = this.options.valueToDisplayFormat(this.options.stepValueMap[value.maxpos]) + " or less";
								else if( value.maxpos==this.options.end )
									lbl = this.options.valueToDisplayFormat(this.options.stepValueMap[value.minpos]) + " or more";
								else
									lbl = this.options.valueToDisplayFormat(this.options.stepValueMap[value.minpos]) + ' to ' + this.options.valueToDisplayFormat(this.options.stepValueMap[value.maxpos]);
									
								$(baseElemId +"_LotSizeLabel").innerHTML = lbl;
							},
							onComplete: function(value) {	
								searchDrawer.setSearchSliderVal('LotSize', value.minpos==this.options.start ? -1 : this.options.stepValueMap[value.minpos], value.maxpos==this.options.end ? -1 : this.options.stepValueMap[value.maxpos]);						
							}
						},
						$(baseElemId + '_LotSizeSlider_MaxKnob')
					);
					this.LotSizeSlider.setMin(0);
					this.LotSizeSlider.setMax(12);
				}

				
				// Parking
				if($(baseElemId + '_ParkingSlider_Container')) {		
					this.ParkingSlider = new RangePicker( 
						$(baseElemId + '_ParkingSlider_Container'),
						$(baseElemId + '_ParkingSlider_MinKnob'),
						{
							mode: 'horizontal',
							offset: 0,
							start: 0,
							end: 6,
							steps: 6,
							onChange: function(value) {
								var lbl = '';
								if( value.minpos==this.options.start && value.maxpos==this.options.end )
									lbl = "Any";
								else if( value.minpos==this.options.start )
									lbl = value.maxpos + " or fewer";
								else if( value.maxpos==this.options.end )
									lbl = value.minpos + " or more";
								else
									lbl = value.minpos + ' to ' + value.maxpos;
									
								$(baseElemId +"_ParkingLabel").innerHTML = lbl;
							},
							onComplete: function(value) {	
								searchDrawer.setSearchSliderVal('Parking', value.minpos==this.options.start ? -1 : value.minpos, value.maxpos==this.options.end ? -1 : value.maxpos);
								BNDebugLog('parking slider update: ' +  value.minpos + ',' + value.maxpos);
							}
						},
						$(baseElemId + '_ParkingSlider_MaxKnob')
					);
					this.ParkingSlider.setMin(0);
					this.ParkingSlider.setMax(7);
				}
				
				// Year Built
				if($(baseElemId + '_YearBuiltSlider_Container')) {					
					var aYearBuiltOptions = []
					var currYear = (new Date()).getFullYear();
					var optYear = currYear;
					while(aYearBuiltOptions.length<3 || (aYearBuiltOptions.length>=3 && optYear%5!=0)) {
						aYearBuiltOptions.unshift(optYear);
						optYear--;
					}
					while(optYear>=currYear-30 || optYear%10!=0) {
						aYearBuiltOptions.unshift(optYear);
						optYear-=5;						
					}
					while(optYear>=1900) {
						aYearBuiltOptions.unshift(optYear);
						optYear-=10;						
					}
					
					this.YearBuiltSlider = new RangePicker( 
						$(baseElemId + '_YearBuiltSlider_Container'),
						$(baseElemId + '_YearBuiltSlider_MinKnob'),
						{
							mode: 'horizontal',
							offset: 0,
							start: 0,
							end: aYearBuiltOptions.length-1,
							steps: aYearBuiltOptions.length,
							stepValueMap: aYearBuiltOptions,
							valueToDisplayFormat: function(num) {
								return num;
							},
							onChange: function(value) {
								var lbl = '';
								if( value.minpos==this.options.start && value.maxpos==this.options.end )
									lbl = "Any";
								else if( value.minpos==this.options.start )
									lbl = this.options.valueToDisplayFormat(this.options.stepValueMap[value.maxpos]) + " or less";
								else if( value.maxpos==this.options.end )
									lbl = this.options.valueToDisplayFormat(this.options.stepValueMap[value.minpos]) + " or more";
								else
									lbl = this.options.valueToDisplayFormat(this.options.stepValueMap[value.minpos]) + ' to ' + this.options.valueToDisplayFormat(this.options.stepValueMap[value.maxpos]);
									
								$(baseElemId +"_YearBuiltLabel").innerHTML = lbl;
							},
							onComplete: function(value) {	
								searchDrawer.setSearchSliderVal('YearBuilt', value.minpos==this.options.start ? -1 : this.options.stepValueMap[value.minpos], value.maxpos==this.options.end ? -1 : this.options.stepValueMap[value.maxpos]);						
							}
						},
						$(baseElemId + '_YearBuiltSlider_MaxKnob')
					);
					this.YearBuiltSlider.setMin(0);
					this.YearBuiltSlider.setMax(aYearBuiltOptions.length);
				}
                
                
				if($(baseElemId + '_IncludeOnlyCB_Active')) {
					$(baseElemId + '_IncludeOnlyCB_Active').addEvent('click',function() { searchDrawer.setSearchParamVal('Status', $(baseElemId + '_IncludeOnlyCB_Active').checked ? 'Active' : ''); });
				}
				if($(baseElemId + '_IncludeOnlyCB_OpenHouse')) {
					$(baseElemId + '_IncludeOnlyCB_OpenHouse').addEvent('click',function() { searchDrawer.setSearchParamVal('Open', $(baseElemId + '_IncludeOnlyCB_OpenHouse').checked); });
				}
				if($(baseElemId + '_IncludeOnlyCB_REO')) {
					$(baseElemId + '_IncludeOnlyCB_REO').addEvent('click',function() { searchDrawer.setSearchParamVal('REO', $(baseElemId + '_IncludeOnlyCB_REO').checked); });
				}
				if($(baseElemId + '_IncludeOnlyCB_ExcludeShort')) {
					$(baseElemId + '_IncludeOnlyCB_ExcludeShort').addEvent('click',function() { searchDrawer.setSearchParamVal('NoShort', $(baseElemId + '_IncludeOnlyCB_ExcludeShort').checked); });
				}
				
				 // Check if Open house is checked
                if($(baseElemId + '_IncludeOnlyCB_OpenHouse').checked)
                {
                  	this.searchParameters.Open = true;
                }
                
               	// initialize property types to selection only after sliders so that steps can be hidden (rent)
				searchDrawer.setSearchPropertyType('RES', $(baseElemId + '_cbRES').checked);
				searchDrawer.setSearchPropertyType('COND', $(baseElemId + '_cbCOND').checked);
				searchDrawer.setSearchPropertyType('LAND', $(baseElemId + '_cbLAND').checked);
				searchDrawer.setSearchPropertyType('RENT', $(baseElemId + '_cbRENT').checked);

				if($(baseElemId + '_cbMOB'))
					searchDrawer.setSearchPropertyType('MOB', $(baseElemId + '_cbMOB').checked);
				if($(baseElemId + '_cbCOMM'))
					searchDrawer.setSearchPropertyType('COMM', $(baseElemId + '_cbCOMM').checked);
				if($(baseElemId + '_cbMULT'))
					searchDrawer.setSearchPropertyType('MULT', $(baseElemId + '_cbMULT').checked);					

				if($(baseElemId+"_advanced") && $(baseElemId+"_advancedToggler")){
					var advPnl = $(baseElemId+"_advanced");
					var linkEl = $(baseElemId+"_advancedToggler").getElement('img');
					linkEl.setStyle('cursor','pointer');
					advPnl.BN_fClosePanel = function() {
						advPnl.setStyles({
								visibility: 'visible',
								overflow: 'hidden'
						});
						new Fx.Style(advPnl, 'width', { duration: 125, transition: Fx.Transitions.linear } ).start(advPnl.offsetWidth,0).chain(function() {
							advPnl.setStyles({	
								display: 'none'									
							});						
							linkEl.src = linkEl.src.replace(/_fewer_/,"_more_");
						});
					}
					
					// hook up expander
					linkEl.addEvent('click',function(event) {
						var event = new Event(event);
						event.stop();
						
						if(advPnl.getStyle('display')=="none") {
							searchDrawer.showAdvancedSearchPanel();
						}
						else {	
							advPnl.BN_fClosePanel();							
						}
					});
					
					var closeIcon = $(advPnl.id + '_closeIcon');
					if(closeIcon)  {
						closeIcon.setStyle('cursor','pointer');										   
						closeIcon.addEvent('click',function(event) {
							var event = new Event(event);
							event.stop();
							advPnl.BN_fClosePanel();
						});
					}										
				}
				
				if($(baseElemId+"_resetBtn")){
					$(baseElemId+"_resetBtn").addEvent('click',function(event) {
						var event = new Event(event);
						event.stop();
						searchDrawer.resetCriteria();													
					});
				}
				
				this.UIInitialized = true;
			}
		/*}  zoom level*/ 		
	},
	hideAdvancedSearchPanel: function() {
		var baseElemId = this.elem.id;	
		var advPnl = $(baseElemId+"_advanced");
		if(advPnl.getStyle('display')!="none") {
			advPnl.BN_fClosePanel();
		}
	},
	showAdvancedSearchPanel: function() {
		var baseElemId = this.elem.id;	
		var advPnl = $(baseElemId+"_advanced");
		if(advPnl && advPnl.getStyle('display')=="none") {
			var linkEl = $(baseElemId+"_advancedToggler").getElement('img');
						
			// measure dest width;
			advPnl.setStyles({
				'white-space': 'nowrap',
				visibility: 'hidden',
				overflow: 'visible',
				width: 'auto',
				height: 'auto',
				display: 'block'
			});						
			var dstWidth = advPnl.offsetWidth;
			advPnl.setStyles({
				visibility: 'visible',
				overflow: 'hidden',
				width: 0
			});
			new Fx.Style(advPnl, 'width', { duration: 125, transition: Fx.Transitions.linear } ).start(0,dstWidth).chain(function() {				
				linkEl.src = linkEl.src.replace(/_more_/,"_fewer_");
			});
		}
	},
	resetCriteria: function() {
		this.searchParameters = {
			PropertyTypes: [ 'RES' ],
			Price: {'min': -1, 'max': -1},
			Bed: {'min': -1, 'max': -1},
			Bath: {'min': -1, 'max': -1},
			SqFt: {'min': -1, 'max': -1},
			LotSize: {'min': -1, 'max': -1},
			YearBuilt: {'min': -1, 'max': -1},
			Parking: {'min': -1, 'max': -1},
			Open: false,
			REO: false,
			NoShort: false,
			Status: ''
		}
		this.applySearchParametersToUI();
	},	
	applySearchParametersToUI: function() {
		this.BlockRefreshData = true;
		
		var baseElemId = this.elem.id;	
		$(baseElemId + '_cbRES').checked = (this.searchParameters.PropertyTypes.indexOf('RES') >= 0);
		$(baseElemId + '_cbCOND').checked = (this.searchParameters.PropertyTypes.indexOf('COND') >= 0);
		$(baseElemId + '_cbLAND').checked = (this.searchParameters.PropertyTypes.indexOf('LAND') >= 0);
		$(baseElemId + '_cbRENT').checked = (this.searchParameters.PropertyTypes.indexOf('RENT') >= 0);

		if($(baseElemId + '_cbMULT')) {
			$(baseElemId + '_cbMULT').checked = (this.searchParameters.PropertyTypes.indexOf('MULT') >= 0);
		}
		if($(baseElemId + '_cbMOB')) {
			$(baseElemId + '_cbMOB').checked = (this.searchParameters.PropertyTypes.indexOf('MOB') >= 0);
		}
		if($(baseElemId + '_cbCOMM')) {
			$(baseElemId + '_cbCOMM').checked = (this.searchParameters.PropertyTypes.indexOf('COMM') >= 0);
		}
		
		// Price
		this.PriceSlider.setMin(this.searchParameters.Price.min==-1? 0 : this.PriceSlider.getStepForValue(this.searchParameters.Price.min));
		this.PriceSlider.setMax(this.searchParameters.Price.max==-1? this.PriceSlider.getMaxStep() : this.PriceSlider.getStepForValue(this.searchParameters.Price.max));
		
		// Bed
		this.BedSlider.setMin(this.searchParameters.Bed.min==-1? 0 : this.BedSlider.getStepForValue(this.searchParameters.Bed.min));
		this.BedSlider.setMax(this.searchParameters.Bed.max==-1? this.BedSlider.getMaxStep() : this.BedSlider.getStepForValue(this.searchParameters.Bed.max));
		
		// Bath
		this.BathSlider.setMin(this.searchParameters.Bath.min==-1? 0 : this.BathSlider.getStepForValue(this.searchParameters.Bath.min));
		this.BathSlider.setMax(this.searchParameters.Bath.max==-1? this.BathSlider.getMaxStep() : this.BathSlider.getStepForValue(this.searchParameters.Bath.max));
		
		// SqFt
		if(this.SqFtSlider) {
			this.SqFtSlider.setMin(this.searchParameters.SqFt.min==-1? 0 : this.SqFtSlider.getStepForValue(this.searchParameters.SqFt.min));
			this.SqFtSlider.setMax(this.searchParameters.SqFt.max==-1? this.SqFtSlider.getMaxStep() : this.SqFtSlider.getStepForValue(this.searchParameters.SqFt.max));
		}
		
		//LotSize
		if(this.LotSizeSlider) {
			this.LotSizeSlider.setMin(this.searchParameters.LotSize.min==-1? 0 : this.LotSizeSlider.getStepForValue(this.searchParameters.LotSize.min));
			this.LotSizeSlider.setMax(this.searchParameters.LotSize.max==-1? this.LotSizeSlider.getMaxStep() : this.LotSizeSlider.getStepForValue(this.searchParameters.LotSize.max));
		}
		
		//Parking
		if(this.ParkingSlider) {
			this.ParkingSlider.setMin(this.searchParameters.Parking.min==-1? 0 : this.ParkingSlider.getStepForValue(this.searchParameters.Parking.min));
			this.ParkingSlider.setMax(this.searchParameters.Parking.max==-1? this.ParkingSlider.getMaxStep() : this.ParkingSlider.getStepForValue(this.searchParameters.Parking.max));
		}
		
		//YearBuilt
		if(this.YearBuiltSlider) {
			this.YearBuiltSlider.setMin(this.searchParameters.YearBuilt.min==-1? 0 : this.YearBuiltSlider.getStepForValue(this.searchParameters.YearBuilt.min));
			this.YearBuiltSlider.setMax(this.searchParameters.YearBuilt.max==-1? this.YearBuiltSlider.getMaxStep() : this.YearBuiltSlider.getStepForValue(this.searchParameters.YearBuilt.max));
		}
		
		if($(baseElemId + '_cbMULT')) {
			$(baseElemId + '_cbMULT').checked = (this.searchParameters.PropertyTypes.indexOf('MULT') >= 0);
		}
		
		if($(baseElemId + '_IncludeOnlyCB_Active')) {
			$(baseElemId + '_IncludeOnlyCB_Active').checked = (this.searchParameters.Status=='Active');
		}

		if($(baseElemId + '_IncludeOnlyCB_OpenHouse')) {
			$(baseElemId + '_IncludeOnlyCB_OpenHouse').checked = (this.searchParameters.Open);
		}
		if($(baseElemId + '_IncludeOnlyCB_REO')) {
			$(baseElemId + '_IncludeOnlyCB_REO').checked = (this.searchParameters.REO);
		}
		if($(baseElemId + '_IncludeOnlyCB_ExcludeShort')) {
			$(baseElemId + '_IncludeOnlyCB_ExcludeShort').checked = (this.searchParameters.NoShort);
		}		

		this.BlockRefreshData = false;
		this._bnmap.RefreshData(true);
	},
	setSearchSliderVal: function(sliderName,minval,maxval) {
		if( this.searchParameters[sliderName].min!=minval || this.searchParameters[sliderName].max!=maxval ) {
			this.searchParameters[sliderName] = {'min': minval, 'max': maxval};
			if(this._bnmap)
				this._bnmap.RefreshData(true);
		}
	},
	setSearchParamVal: function(paramName,pVal) {
		this.searchParameters[paramName] = pVal;
		if(this._bnmap && !this.BlockRefreshData)
				this._bnmap.RefreshData(true);
	},
	setSearchPropertyType: function(typeName,bChecked) {
		if( bChecked ) {
			if( this.searchParameters.PropertyTypes.indexOf(typeName) < 0 ) {
				this.searchParameters.PropertyTypes.push(typeName);
				if(this._bnmap && !this.BlockRefreshData)
					this._bnmap.RefreshData(false); // no need to drop all markers because a class was ADDED
				if(typeName=='RENT' && this.PriceSlider.unhideRange) {
					this.PriceSlider.unhideRange(1,24);	
				}
			}
			else {
				// nothing to do.	
			}
		}
		else {
			if( this.searchParameters.PropertyTypes.indexOf(typeName) < 0 ) {
				// nothing to do
			}
			else {
				this.searchParameters.PropertyTypes.remove(typeName);
				if(this._bnmap && !this.BlockRefreshData)
					this._bnmap.RefreshData(true); // need to drop all markers because a class was removed
				if(typeName=='RENT' && this.PriceSlider.hideRange) {
					this.PriceSlider.hideRange(1,24);	
				}
			}
		}
	}
});

var BNMapLegendDrawer = BNMapDrawer.extend({
	onMapZoomChanged: function(zoom) {
		if(this.ACTIVE_CALLOUT_DIV && this.ACTIVE_CALLOUT_DIV.closeCallout)
			this.ACTIVE_CALLOUT_DIV.closeCallout();
		if( !this.UIInitialized ) {
			this.initHelp();			
			this.UIInitialized = true;
		}
	}
});

var BNMapFilmStripDrawer = BNMapDrawer.extend({
    initialize: function(id, elem, title, options) {
		this.parent(id, elem, title, options);
		this.stripTableRowElem = $E('tr', elem);
		this.resetMarkers();
	},	
	onMapResized: function() {
		this.validateDisplay(null);	
	},
	onMapZoomChanged: function(zoom) {
		this.validateDisplay(zoom);
	},	
	validateDisplay: function(zoom) {
		zoom = zoom || this._bnmap.map.getZoom();	
		if( zoom < 13 || this.stripMarkers==null || this.stripMarkers.length==0) {
			if( this.elem.style.display== 'block' )
				this.elem.style.display='none';
		}
		else { // if( zoom >= 14 ) 
			this.elem.style.display = 'block';
			var baseElemId = this.elem.id;	
			if( !this.UIInitialized ) {											
				var findDrawer = this; // create enclosure for event handlers
				var baseElem = this.elem;
				baseElem.setStyle('height','40px');				
				$(baseElemId + "_bundle").addEvent('mouseenter', function() {
					baseElem.setStyle('height','300px');	// room for fisheye effect																		
					new Fx.Style(baseElemId + '_bundle', 'bottom', {duration:300}).start(-12, 0);
				});
				$("mapDrawer_FilmStrip_bundle").addEvent('mouseleave', function() {
					baseElem.setStyle('height','40px');																
					new Fx.Style(baseElemId + '_bundle', 'bottom', {duration:300}).start(0, -12);
				});
				var filmstripDrawer = this; // enclosure;
				this.sliderPos = 0;
				
				var stripWidth = Math.max(150, $(this._bnmap.mapDivId).offsetWidth - 200);						
				$(baseElemId).setStyle('width', stripWidth + 'px');
				$(baseElemId + '_bundle').setStyle('width', stripWidth + 'px');		
				
				this.filmStripSlider = new Slider($(baseElemId + '_slider'),$(baseElemId + '_slider_knob'),
					{
						steps: 100,
						mode: 'horizontal',
						onChange: function(value) {
							var winSize = Math.floor($(baseElemId + "_bundle").offsetWidth / filmstripDrawer.options.thumbSize.width);
							var pos = Math.round(Math.max(0,filmstripDrawer.stripMarkers.length - winSize) * value / 100);
							var lbl = '';
							if( filmstripDrawer.stripMarkers.length > 0 && pos < filmstripDrawer.stripMarkers.length ) {
								lbl = filmstripDrawer.stripMarkers[pos].title;
							}							
							$(baseElemId +"_slider_knob").title = lbl;
						},
						onComplete: function(value) {	
							var winSize = Math.floor($(baseElemId + "_bundle").offsetWidth / filmstripDrawer.options.thumbSize.width);
							var pos = Math.round(Math.max(0,filmstripDrawer.stripMarkers.length - winSize) * value / 100);
							filmstripDrawer.sliderPos = pos;
							filmstripDrawer.markersValidated = false;
							if( filmstripDrawer.UIInitialized )
								filmstripDrawer.validateDisplay(zoom);							
						}
					});
				this.filmStripSlider.set(0);				
				
				/*$E('table', this.elem).makeDraggable();{
					container: 	$(baseElemId + '_strip'),
					overflown: [ this.elem ]
				});*/
				
				this.UIInitialized = true;
			}
			
			if( !this.markersValidated ) 
			{
				if( this.stripTableRowElem ) 
				{
					var tab = $E('table', this.elem);
					if( this.lastFishEyeObj ) 
						this.lastFishEyeObj.detachEvents();
						
					tab.deleteRow(0);
					tab.insertRow(0);
					this.stripTableRowElem = $E('tr', this.elem); //	remove all elements in the table row.				
					if( this.filmStripSlider ) {
						var prevWidth = $(baseElemId).offsetWidth;
						var stripWidth = Math.max(150, $(this._bnmap.mapDivId).offsetWidth - 200);						
						$(baseElemId).setStyle('width', stripWidth + 'px');
						$(baseElemId + '_bundle').setStyle('width', stripWidth + 'px');						
						var winSize = Math.floor(stripWidth / this.options.thumbSize.width) + 1 ;//15;
						var start = Math.max(0,Math.min(this.sliderPos,this.stripMarkers.length-winSize));
						var end = Math.min(start + winSize,this.stripMarkers.length);
						
						var prevKnobWidth = $(baseElemId + '_slider_knob').offsetWidth; 
						var knobSize = Math.floor($(baseElemId + '_bundle').offsetWidth * winSize / this.stripMarkers.length);
						$(baseElemId + '_slider_knob').setStyle('width', knobSize + 'px');
						knobSize = $(baseElemId + '_slider_knob').offsetWidth; // includes border, etc.
						
						if(prevWidth!=stripWidth || prevKnobWidth!=knobSize) {
							this.filmStripSlider.max = stripWidth - knobSize;
							this.filmStripSlider.half = knobSize/2;
							this.filmStripSlider.drag.options.limit.x[1] = this.filmStripSlider.max;
						}
						
						var cellRefs = [];
						for(var i=start;i<end;i++) {
							var cell = this.stripTableRowElem.insertCell(i-start);
							cell.id='stripCell_'+i;
							var marker = this.stripMarkers[i];
							/*if(this.options.waitImage) {
								cell.setStyles('background',"transparent url('" + this.options.waitImage + "') no-repeat center center");
							}*/
							cell.innerHTML = '<div class="iFishEyeCaption">' +marker.title+ '<br />'+ marker.subtitle +'</div><div style="position:relative;top:0px;left:0px;"><img class="iFishEyeImg" style="z-index:1" src="' + marker.img + '" /></div>';
							cellRefs.push(cell);
														
							var eCell = $(cell);
							
							eCell.BN_MARKER = this._bnmap.GetCachedMarker(this._bnmap.map.getZoom(), marker.uid);
							eCell.addEvent('mouseenter', function() { this.BN_MARKER.BN_SelectImage('selected'); });
							eCell.addEvent('mouseleave', function() { if(!this.BN_MARKER.BN_InfoWindowShowing) this.BN_MARKER.BN_SelectImage('standard'); });
							var _bnmap = this._bnmap;
							eCell.addEvent('click', function() { _bnmap.DisplayMarkerInfo(this.BN_MARKER); });
						}
						
						var shapeTool = this._bnmap.shapeTool;
						this.lastFishEyeObj = new iFishEye({   
							container: $(baseElemId + "_strip"), 
							dimThumb: this.options.thumbSize,
							dimFocus: this.options.focusSize,  
							eyeRadius: Math.round(this.options.focusSize.width * 0.8), 
							pupilRadius: Math.round(this.options.focusSize.width * 0.4),  
							norm: "L2",
							isEnabledCallback: function() {
								if(shapeTool && shapeTool.isDrawing()==true) 
									return false;
								return true;
							}
						});  
						
						
						
						for(var i=0;i<cellRefs.length;i++) {
							var eCell = $(cellRefs[i]);
							var propImg = eCell.getElement("img[class=iFishEyeImg]");
							var waitImg = new Element('img',{ styles : {"z-index" :0, "position": "absolute", "bottom": 10, "left": 10},  "src": this.options.waitImage });
							waitImg.injectAfter(propImg);
							
							if(waitImg && propImg) {
								eCell.propImg = propImg;
								eCell.waitImg = waitImg;
								eCell.fCheckWait = function() {
									if((this.propImg.readyState=='complete' || this.propImg.complete==true)) {
										this.waitImg.remove();
									}
									else {
										this.waitImg.setStyle('left', ((this.offsetWidth - this.waitImg.offsetWidth) / 2) + 'px');
										{
											var ctxt = this;
											(function() { ctxt.fCheckWait(); }).delay(300);
										}
									}
								};	
								eCell.fCheckWait()								
							}	
						}
					}
				}
			}
			
			this.markersValidated = true;
		}
	},		
	resetMarkers: function() {
		this.stripMarkers = [];	
		this.markersValidated = false;
	},
	addMarker: function(marker) {
		this.stripMarkers.push(marker);		
		this.markersValidated = false;
	}		
});

var BNMapResultsGridDrawer = BNMapDrawer.extend({
    initialize: function(id, elem, title, options) {
		this.parent(id, elem, title, options);
		if(window.ie)
			this.elem.addClass("SortableTableContainerIEFix");
			
		this.gridTable = $(options.tableId);
		this.resetMarkers();
	},	
	onMapResized: function() {
		this.validateDisplay(null);	
	},
	onMapZoomChanged: function(zoom) {
		this.validateDisplay(zoom);
	},	
	validateDisplay: function(zoom) {
		zoom = zoom || this._bnmap.map.getZoom();	
		if( zoom < 13 || this.markerCount==0) {
			if( this.elem.style.display== 'block' )
				this.elem.style.display='none';
		}
		else { // if( zoom >= 14 ) 
			this.elem.style.display = 'block';
			var baseElemId = this.elem.id;	
			var _bnmap = this._bnmap;
			if( !this.UIInitialized ) {											
				this.sortableTable = new sortableTable(this.options.tableId, {
					/*overCls: 'over',*/
					onClick: function(){
						_bnmap.DisplayMarkerInfo(this.BN_MARKER);
					}
				});
		
				this.UIInitialized = true;
			}
			
			if( !this.markersValidated ) 
			{
				this.sortableTable.reloadElements();
			}			
			this.markersValidated = true;
		}
	},		
	resetMarkers: function() {
		this.gridTable.getElement('tbody').remove();
		(new Element('tbody')).injectAfter(this.gridTable.getElement('thead'));
		this.markerCount=0;
		this.markersValidated = false;
	},
	addMarker: function(marker) {
		var tr = $(this.gridTable.getElement('tbody').insertRow(this.markerCount));
		tr.id = this.markerCount;
		tr.BN_MARKER = this._bnmap.GetCachedMarker(this._bnmap.map.getZoom(), marker.uid);
		tr.addEvent('mouseenter', function() { this.addClass('over'); this.BN_MARKER.BN_SelectImage('selected'); });
		tr.addEvent('mouseleave', function() { this.removeClass('over'); if(!this.BN_MARKER.BN_InfoWindowShowing) this.BN_MARKER.BN_SelectImage('standard'); });

		// icon
		var cell = tr.insertCell(0);
		var sIcon = tr.BN_MARKER.getIcon().image;
		cell.align="center";
		cell.verticalAlign="middle";
		//$(cell).adopt(new Element('img', {src: sIcon, styles: { display: 'block' } }));
		cell.innerHTML = "<img src='" + sIcon + "' style='display:block' />";
		
		// mls#
		cell = tr.insertCell(1);
		cell.innerHTML = (marker.lid ? marker.lid : '');
		
		// address
		cell = tr.insertCell(2);
		cell.innerHTML = marker.title.replace(/^(Pending|Sold):/i,'').trim();

		// location		
		cell = tr.insertCell(3);
		cell.innerHTML = (marker.loc ? marker.loc : '');
		
		// price
		cell = tr.insertCell(4);
		cell.innerHTML = (marker.lp ? marker.lp : '');
		
		// bed
		cell = tr.insertCell(5);
		cell.innerHTML = (marker.bd ? marker.bd : '');
		
		// bath
		cell = tr.insertCell(6);
		cell.innerHTML = (marker.bt ? marker.bt : '');
		
		// SqFt
		cell = tr.insertCell(7);
		cell.innerHTML = (marker.sf ? marker.sf : '');
		
		// Lot
		cell = tr.insertCell(8);
		cell.innerHTML = (marker.lot ? marker.lot : '');
		
		// more info
		cell = tr.insertCell(9);
		var isPending = ((',' + (marker.flags || '').toLowerCase() + ',').indexOf(",s:pending,") >= 0);
		var isOpen = ((',' + (marker.flags || '').toLowerCase() + ',').indexOf(",open,") >= 0);
		var isREO = ((',' + (marker.flags || '').toLowerCase() + ',').indexOf(",reo,") >= 0);
		
		var sMoreInfo = isPending ? "Pending" : "";
		if(isOpen) {
			if(sMoreInfo.length>0) 	sMoreInfo+= ", ";
			sMoreInfo += "Open House";
		}
		if(isREO) {
			if(sMoreInfo.length>0) 	sMoreInfo+= ", ";
			sMoreInfo += "REO";
		}
		cell.innerHTML = sMoreInfo;
		
		this.markerCount++;
		this.markersValidated = false;
	}		
});


var BNMapOfficesDrawer = BNMapDrawer.extend({					  
	initialize: function(id, elem, title, options) {
		this.parent(id, elem, title, options);
		var drawer = this; // enclosure
		var baseElemId = this.elem.id;
		$(baseElemId + '_cbShow').addEvent('click', function() {
			if( $(baseElemId + '_cbShow').checked==false ) {				
				drawer._bnmap.RemoveFilteredMarkers(function(mrkr) { return (mrkr.BN_TYPE=='Office'); });
			}
			else {
				drawer._bnmap.RefreshData( false );										 
			}
		});
	},							
	getDrawerEnabledLayers: function() {
		var baseElemId = this.elem.id;
		if($(baseElemId + '_cbShow').checked) {
			return ['Offices'];	
		}
		return [];
	},
	getIcon: function() {
		if(!this.icon)
		{
			this.icon = new google.maps.Icon();
			
			this.icon.image = this.options.officeIcon.main;
			this.icon.transparent = this.options.officeIcon.transparent;
			this.icon.shadow = this.options.officeIcon.shadow;
			this.icon.iconSize = new google.maps.Size(this.options.officeIcon.width,this.options.officeIcon.height);
			this.icon.shadowSize = new google.maps.Size(this.options.officeIcon.width,this.options.officeIcon.height);
			this.icon.iconAnchor = new google.maps.Point(this.options.officeIcon.anchorX,this.options.officeIcon.anchorY);
			this.icon.infoWindowAnchor = new google.maps.Point(this.options.officeIcon.infoWindowAnchorX,this.options.officeIcon.infoWindowAnchorY);
		}
		return this.icon;
	}
});

var BNMapSchoolsDrawer = BNMapDrawer.extend({					  
	initialize: function(id, elem, title, options) {
		this.parent(id, elem, title, options);
		var drawer = this; // enclosure
		var baseElemId = this.elem.id;
		$(baseElemId + '_cbShow').addEvent('click', function() {
			if( $(baseElemId + '_cbShow').checked==false ) {				
				drawer._bnmap.RemoveFilteredMarkers(function(mrkr) { return (mrkr.BN_TYPE=='School'); });
			}
			else {
				drawer._bnmap.RefreshData( false );										 
			}
		});
	},		
	onMapZoomChanged: function(zoom) {
		if( zoom < 13 ) {
			if( this.elem.style.display=='block' || this.elem.style.display=='' ) {
				this.elem.style.display='none';
			}
		}
		else { // if( zoom >= 16 ) 
			this.elem.style.display = '';
		}
	},	
	getDrawerEnabledLayers: function() {
		var baseElemId = this.elem.id;
		if($(baseElemId + '_cbShow').checked && this._bnmap.map.getZoom() >= 13) {
			return ['Schools'];	
		}
		return [];
	},
	getIcon: function() {
		if(!this.icon)
		{
			this.icon = new google.maps.Icon();
			
			this.icon.image = this.options.schoolIcon.main;
			this.icon.transparent = this.options.schoolIcon.transparent;
			this.icon.shadow = this.options.schoolIcon.shadow;
			this.icon.iconSize = new google.maps.Size(this.options.schoolIcon.width,this.options.schoolIcon.height);
			this.icon.shadowSize = new google.maps.Size(this.options.schoolIcon.width,this.options.schoolIcon.height);
			this.icon.iconAnchor = new google.maps.Point(this.options.schoolIcon.anchorX,this.options.schoolIcon.anchorY);
			this.icon.infoWindowAnchor = new google.maps.Point(this.options.schoolIcon.infoWindowAnchorX,this.options.schoolIcon.infoWindowAnchorY);
		}
		return this.icon;
	}
});

function BNClearRibbonControl(width,height){ this.width_=width; this.height_=height }
BNClearRibbonControl.prototype = new GControl();
BNClearRibbonControl.prototype.printable = function() {return false;};
BNClearRibbonControl.prototype.selectable = function() {return false;};
BNClearRibbonControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(100, 0));
}
BNClearRibbonControl.prototype.initialize = function(map) {
  this.div_=new Element('div',{ styles: { width: this.width_, height: this.height_/*, backgroundColor: 'red'*/ }});
  map.getContainer().appendChild(this.div_);
  return this.div_;
}
BNClearRibbonControl.prototype.destroy = function() { if(this.div_) this.div_.remove(); };

var BNMapTopToolsDrawer = BNMapDrawer.extend({					  
	initialize: function(id, elem, title, options) {
		this.parent(id, elem, title, options);
		if( !this.UIInitialized ) {
			var drawer = this;			
			(function() { 
				drawer.reposition();
				drawer.elem.setStyle('visibility', 'visible'); 
				drawer._bnmap.shapeTool.addEvent('reset', function() {
					var shapeBtns = [ $(drawer.elem.id+'_btn_rectangle'), $(drawer.elem.id+'_btn_polygon')];
					shapeBtns.forEach(function(btnEl) {
						var upSrc = btnEl.src.replace(/_down.png$/,".png");
						btnEl.src = upSrc;
						drawer.retractShapeSlider(btnEl);			   
					});
				});				
			}).delay(1); // do after drawer is registered
			var buttons = [];
			this.elem.getElements('img[id^='+this.elem.id+'_btn_]').each(function(btnEl) {
				buttons.push(btnEl);																	  
			});
			buttons.forEach(function(btnEl) {
				btnEl.addEvent('click', function() {
					var anyChanging = false;
					for(var i=0;i<buttons.length;i++) {
						if(buttons[i].getProperty("BN_ISCHANGING")=="1")
							anyChanging=true;
					}
					if(anyChanging==false) {
						drawer.toggleButton(btnEl);
					}
				});
			});
			// on initialization, extend the location tool
			var locBtn = this.elem.getElement('img[id='+this.elem.id+'_btn_location]');
			if(locBtn) {
				(function() { drawer.toggleButton(locBtn) }).delay(1000);
			}
			
			this.UIInitialized = true;
		}
	},	
	onMapResized: function() {
		this.reposition();
	},
	onMapZoomChanged: function(zoom) {
	},
	reposition: function() {
		var targetLeft = Math.max(250,($(this._bnmap.mapDivId).offsetWidth - this.elem.offsetWidth)/2 + $(this._bnmap.mapDivId).offsetLeft - 70);
		this.elem.setStyle('left', targetLeft);
		
		if(this.clrRibbonCtl) {
			this.clrRibbonCtl.destroy();
			this._bnmap.map.removeControl(this.clrRibbonCtl);
		}
		this.clrRibbonCtl = new BNClearRibbonControl(this.elem.offsetWidth,this.elem.offsetHeight);		
		this._bnmap.map.addControl(this.clrRibbonCtl, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(targetLeft - $(this._bnmap.mapDivId).offsetLeft, 0)));
	},
	toggleButtonByType: function(btnType) {
		var btnEl = this.elem.getElement('img[id='+this.elem.id+'_btn_'+btnType+']');
		if(btnEl) 
			this.toggleButton(btnEl);
	},
	isButtonTypeSupported: function(btnType) {
		var btnEl = this.elem.getElement('img[id='+this.elem.id+'_btn_'+btnType+']');
		return (btnEl ? true : false);
	},
	toggleButton: function(btnEl) {
		var drawer = this;
		var btnType = /_btn_(.*)$/.exec(btnEl.id)[1];		
		if(/_down.png$/.test(btnEl.src)) {
			// in down state
			var upSrc = btnEl.src.replace(/_down.png$/,".png");
			switch(btnType) {
				case "location": case "savealert":
					btnEl.setProperty("BN_ISCHANGING","1");
					drawer.retractToolSlider(btnEl, btnType, function() {
						btnEl.src = upSrc;
						btnEl.setProperty("BN_ISCHANGING","0");
					});
					break;
				case "rectangle":
					// stop rectangle
					btnEl.src = upSrc;
					drawer.retractShapeSlider(btnEl);
					break;
				case "polygon":
					//todo: stop polygon?
					btnEl.src = upSrc;
					drawer.retractShapeSlider(btnEl);
					break;			
			}
		}
		else {
			// in up state			
			
			// if the SearchProperty advanced panel is extended, retradt it			
			if(drawer._bnmap.drawers["PropertySearch"] && btnType!="rectangle" && btnType!="polygon") {
				drawer._bnmap.drawers["PropertySearch"].hideAdvancedSearchPanel();
			}
			
			// check first if there is a currently extended button, if so, retract it first
			if(drawer.CurrExtendedBtn != null ) {
				var currExtBtn = drawer.CurrExtendedBtn; // enclose
				currExtBtn.setProperty("BN_ISCHANGING","1");
				var currExtendedBtnType = /_btn_(.*)$/.exec(currExtBtn.id)[1];	
				var currExtendedBtnUpSrc = currExtBtn.src.replace(/_down.png$/,".png");
				drawer.retractToolSlider(currExtBtn, btnType, function() {
					currExtBtn.src = currExtendedBtnUpSrc;
					currExtBtn.setProperty("BN_ISCHANGING","0");
					drawer.toggleButton(btnEl); // now call toggle on this button again.
				});
			}
			else if(drawer.CurrExtendedShapeBtn !=null ) {
				var currExtBtn = drawer.CurrExtendedShapeBtn; // enclose
				var currExtendedBtnUpSrc = currExtBtn.src.replace(/_down.png$/,".png");
				drawer.retractShapeSlider(currExtBtn, function() {
					currExtBtn.src = currExtendedBtnUpSrc;
					drawer.toggleButton(btnEl); // now call toggle on this button again.
				});
			}
			else {
				var downSrc = btnEl.src.replace(/.png$/,"_down.png");
				var upSrc = btnEl.src;
				switch(btnType) {
					case "location": case "savealert":
						btnEl.setProperty("BN_ISCHANGING","1");
						btnEl.src = downSrc;
						drawer.extendToolSlider(btnEl, btnType, function() {
							btnEl.setProperty("BN_ISCHANGING","0"); 
						},
						function() { /* retract callback */
							btnEl.src = upSrc;
							btnEl.setProperty("BN_ISCHANGING","0");
						}
						);
						break;
					case "rectangle":
						// todo: start rectangle
						btnEl.src = downSrc;						
						this._bnmap.shapeTool.startDrawing('RECTANGLE');
						this.extendShapeSlider(btnEl,'RECTANGLE');
						break;
					case "polygon":
						//todo: start polygon?
						btnEl.src = downSrc;
						this._bnmap.shapeTool.startDrawing('POLYGON');						
						this.extendShapeSlider(btnEl,'POLYGON');
						break;			
				}
			}
		}
	},
	retractToolSlider: function(btnEl, btnType, fDoneCallback) {
		var drawer = this;
		btnEl.toolSlider5.remove();
		btnEl.toolSlider5 = null;
		
		var stepDuration = 300;
		new Fx.Style(btnEl.toolSlider4, 'width', { duration: stepDuration } ).start(btnEl.toolSlider4.offsetWidth,0);
		new Fx.Styles(btnEl.toolSlider3, { duration: stepDuration } ).start({
					'width': [btnEl.toolSlider3.offsetWidth,0],
					'left': [ - btnEl.toolSlider3.offsetWidth,0]
				}).chain(function() 
		{		
			btnEl.toolSlider4.setStyle('display','none'); // don't remove yet to avoid timing issues
			btnEl.toolSlider3.setStyle('display','none'); // don't remove yet to avoid timing issues
			btnEl.toolSlider2.setStyles({
				'border-left-width':1,
				'border-right-width':1,
				'margin-left': 0 /* compensation for border */
			});	
			new Fx.Style(btnEl.toolSlider2, 'height', { duration: 300 } ).start(btnEl.toolSlider2.offsetHeight,0).chain( function() 
			{
				btnEl.toolSlider4.remove(); btnEl.toolSlider4=null;
				btnEl.toolSlider3.remove(); btnEl.toolSlider3=null;
				btnEl.toolSlider2.remove(); btnEl.toolSlider4=null;
				
				btnEl.toolSlider1.setStyle('border-bottom-width',1);																												 				new Fx.Style(btnEl.toolSlider1, 'height', { duration: 125, transition: Fx.Transitions.linear } ).start(btnEl.toolSlider1.offsetHeight,0).chain(function() 																																																																																								  				{
					btnEl.toolSlider1.remove(); 
					btnEl.toolSlider4=null;		
					drawer.CurrExtendedBtn = null;
					fDoneCallback();	
				});												
			});			
		});
		
		
	},
	extendToolSlider: function(btnEl, btnType, fDoneCallback, fRetractDoneCallback) {
		var drawer = this;
		var btnCoords = btnEl.getCoordinates();
		var posDiv = $(btnEl.id.replace('_btn_','_pos_'));
		var posDivCoords = posDiv.getCoordinates();
		var mapCoords = $(this._bnmap.mapDivId).getCoordinates();
			
		var sliderWindowMargin = { bottom: 50, left: 70, right: 70 }
		var sliderWindowDimensions = {
			height: mapCoords.height - (posDivCoords.top + btnCoords.height + drawer.options.sliderExtensionHeight - mapCoords.top) - sliderWindowMargin.bottom,
			leftWidth: posDivCoords.left - mapCoords.left - sliderWindowMargin.left,
			rightWidth: mapCoords.right - posDivCoords.right - sliderWindowMargin.right
		}
		sliderWindowDimensions.totalWidth = sliderWindowDimensions.leftWidth + btnCoords.width + sliderWindowDimensions.rightWidth;

		// adjust height to something more reasonable: measure the element we are about to place inside the final div
		var finalContentElemId = drawer.elem.id + "_"+btnType+"_content";
		var finalContentElem = $(finalContentElemId);

		if(btnType=='savealert') {
			// make sure the final content elem is reset
			$(finalContentElemId +'_prepare').setStyle('display','block');
			$(finalContentElemId +'_success').setStyle('display','none');
			$(finalContentElemId +'_failure').setStyle('display','none');
		}
		
		// for measurement, we need it to render in a hidden way
		finalContentElem.setStyles({
			visibility: 'hidden',
			position: 'absolute',
			display: 'block',
			width: sliderWindowDimensions.totalWidth
		});
		finalContentElem.getFirst().setStyle('float','left');
		sliderWindowDimensions.height = Math.min(sliderWindowDimensions.height, finalContentElem.offsetHeight);
		sliderWindowDimensions.innerWidth =  finalContentElem.getFirst().offsetWidth;
		// adjust the textField's size in the location panel if the available width is too small
		if(btnType=='location') {
			var locTxtField = finalContentElem.getElement('input[id=txtField]');
			var bWidthRestricted = false;
			while(locTxtField && locTxtField.offsetWidth>100 && sliderWindowDimensions.innerWidth > sliderWindowDimensions.totalWidth) {
				locTxtField.setStyle('width',locTxtField.offsetWidth -10);
				sliderWindowDimensions.innerWidth =  finalContentElem.getFirst().offsetWidth;
				bWidthRestricted = true;
			}
			if(bWidthRestricted) {
				locTxtField.setStyle('width',locTxtField.offsetWidth -10); // a bit of a margin	
				sliderWindowDimensions.innerWidth =  finalContentElem.getFirst().offsetWidth;
				finalContentElem.getElement('div[id=locInstructions]').setStyle('font-size','14px');
				sliderWindowDimensions.height = Math.min(sliderWindowDimensions.height, finalContentElem.offsetHeight);
			}
		}
		finalContentElem.setStyle('display','none');
		finalContentElem.getFirst().setStyle('float','none');
		
		// step 1: extend short extension down
		btnEl.toolSlider1 = new Element('div', {
			styles: {
				position: 'absolute',
				top: btnCoords.height,
				left: 0,
				width: btnCoords.width - 2,
				height: 0,
				opacity: drawer.options.sliderBorderOpacity,
				color: 'transparent',
				borderLeft: '1px solid ' + drawer.options.sliderBorderColor,
				borderRight: '1px solid ' + drawer.options.sliderBorderColor,
				borderBottom: '1px solid ' + drawer.options.sliderBorderColor
			}
		});
		btnEl.toolSlider1.injectInside(posDiv);
		var bgDiv1 = new Element('div', { 
			styles: {
				width: '100%',
				height: '100%',
				opacity: drawer.options.sliderOpacity,
				borderWidth: 0,
				backgroundColor: drawer.options.sliderBackColor
			}
		});
		bgDiv1.injectInside(btnEl.toolSlider1);
		
		new Fx.Style(btnEl.toolSlider1, 'height', { duration: 125, transition: Fx.Transitions.linear } ).start(0,drawer.options.sliderExtensionHeight).chain(function() {
			// step 2: hide extension bottom border, and extend down fully (window height)
			btnEl.toolSlider1.setStyle('border-bottom-width',0);																											 			
			btnEl.toolSlider2 = new Element('div', {
			styles: {
				position: 'absolute',
				top: btnCoords.height + drawer.options.sliderExtensionHeight,
				left: 0,
				width: btnCoords.width - 2,
				height: 0,
				opacity: drawer.options.sliderBorderOpacity,
				color: 'transparent',
				borderLeft: '1px solid ' + drawer.options.sliderBorderColor,
				borderRight: '1px solid ' + drawer.options.sliderBorderColor,
				borderBottom: '1px solid ' + drawer.options.sliderBorderColor
			}
			});
			btnEl.toolSlider2.injectInside(posDiv);
			var bgDiv2 = new Element('div', { 
				styles: {
					width: '100%',
					height: '100%',
					opacity: drawer.options.sliderOpacity,
					borderWidth: 0,
					backgroundColor: drawer.options.sliderBackColor
				}
			});
			bgDiv2.injectInside(btnEl.toolSlider2);
			
			new Fx.Style(btnEl.toolSlider2, 'height', { duration: 300 } ).start(0,sliderWindowDimensions.height).chain( function() {
				// step 3: hide step2 left/right borders, and extend left+right
				btnEl.toolSlider2.setStyles({
					'border-left-width':0,
					'border-right-width':0,
					'margin-left': 1 /* compensation for border */
				});	
				
				// slider3 : left
				btnEl.toolSlider3 = new Element('div', {
				styles: {
					position: 'absolute',
					top: btnCoords.height + drawer.options.sliderExtensionHeight - 1,
					left: 0,
					width: 0,
					height: sliderWindowDimensions.height,
					opacity: drawer.options.sliderBorderOpacity,
					color: 'transparent',
					borderLeft: '1px solid ' + drawer.options.sliderBorderColor,
					borderTop: '1px solid ' + drawer.options.sliderBorderColor,
					borderBottom: '1px solid ' + drawer.options.sliderBorderColor
				}
				});
				btnEl.toolSlider3.injectInside(posDiv);
				var bgDiv3 = new Element('div', { 
					styles: {
						width: '100%',
						height: '100%',
						opacity: drawer.options.sliderOpacity,
						borderWidth: 0,
						backgroundColor: drawer.options.sliderBackColor
					}
				});
				bgDiv3.injectInside(btnEl.toolSlider3);
				
				// slider4 : right
				btnEl.toolSlider4 = new Element('div', {
				styles: {
					position: 'absolute',
					top: btnCoords.height + drawer.options.sliderExtensionHeight - 1,
					left: btnCoords.width - 1,
					width: 0,
					height: sliderWindowDimensions.height,
					opacity: drawer.options.sliderBorderOpacity,
					color: 'transparent',
					borderRight: '1px solid ' + drawer.options.sliderBorderColor,
					borderTop: '1px solid ' + drawer.options.sliderBorderColor,
					borderBottom: '1px solid ' + drawer.options.sliderBorderColor
				}
				});
				btnEl.toolSlider4.injectInside(posDiv);
				var bgDiv4 = new Element('div', { 
					styles: {
						width: '100%',
						height: '100%',
						opacity: drawer.options.sliderOpacity,
						borderWidth: 0,
						backgroundColor: drawer.options.sliderBackColor
					}
				});
				bgDiv4.injectInside(btnEl.toolSlider4);
				
				var stepDuration = 300;
				new Fx.Styles(btnEl.toolSlider3, { duration: stepDuration } ).start({
					'width': [0,sliderWindowDimensions.leftWidth],
					'left': [0, - sliderWindowDimensions.leftWidth]
				});		
				new Fx.Style(btnEl.toolSlider4, 'width', { duration: stepDuration } ).start(0,sliderWindowDimensions.rightWidth).chain(function() {
					// step 4 display close button and content div.
					btnEl.toolSlider5 = new Element('div', {
						styles : {
							position: 'absolute',
							top: btnCoords.height + drawer.options.sliderExtensionHeight - 1,
							left: - sliderWindowDimensions.leftWidth,
							width: sliderWindowDimensions.totalWidth,
							height: sliderWindowDimensions.height,
							'text-align': 'center'
						}
					});
					btnEl.toolSlider5.injectInside(posDiv);
					
					btnEl.toolSlider5.innerHTML = finalContentElem.innerHTML;
					var cntnr = btnEl.toolSlider5.getFirst();
					cntnr.setStyles({																		
						width: sliderWindowDimensions.innerWidth
					});

					switch(btnType) {
						case "location":							
							var txtField = btnEl.toolSlider5.getElement('input[id=txtField]');
							var findButton = btnEl.toolSlider5.getElement('img[id=findButton]');
							var waitImg = btnEl.toolSlider5.getElement('img[id=waitImg]');
							var initValue = txtField.getProperty('initValue');
							txtField.addEvent('focus',function() {
								if(txtField.value==initValue) {
									txtField.value = ''
									txtField.setStyle('color','#000');
								}
							});
							txtField.addEvent('blur',function() {
								if(txtField.value.trim()=='') {
									txtField.value = initValue
									txtField.setStyle('color','#ccc');
								}
							});							
							txtField.addEvent('keydown', function(event){
								event = new Event(event);
								if (event.key == 'enter') {
									drawer.doFind(txtField.value, initValue, function() {
										btnEl.setProperty("BN_ISCHANGING","1");
										drawer.retractToolSlider(btnEl,btnType,fRetractDoneCallback);											  
									}, waitImg, findButton);
								}
							});
							findButton.addEvent('click', function() {
								drawer.doFind(txtField.value, initValue, function() {
									btnEl.setProperty("BN_ISCHANGING","1");
									drawer.retractToolSlider(btnEl,btnType,fRetractDoneCallback);											  
								}, waitImg, findButton);
							});
							break;
						case "savealert":
							drawer.doSaveMapSearch();
							break;
					}
					// look for close links and hook them up properly
					var closeLinks = btnEl.toolSlider5.getElements('a[class=closeTool]').each(function(closeLink) {
						closeLink.addEvent('click',function(event) {
							var event = new Event(event);
							btnEl.setProperty("BN_ISCHANGING","1");
							drawer.retractToolSlider(btnEl,btnType,fRetractDoneCallback);
							event.stop();
						});
					});
					
					var closeBtn = new Element('img', { 
						src: drawer.options.closeIcon,
						styles: {
							position: 'absolute',
							top: 5,
							right: 5
						},
						events: {
							click: function() {
								btnEl.setProperty("BN_ISCHANGING","1");
								drawer.retractToolSlider(btnEl,btnType,fRetractDoneCallback);
							}
						}
					});
					closeBtn.injectInside(btnEl.toolSlider5);
					drawer.CurrExtendedBtn = btnEl;
					fDoneCallback();
				});
			});		
		});				
	},
	extendShapeSlider: function(btnEl, drawType) {
		var drawer = this;
		var btnCoords = btnEl.getCoordinates();
		var posDiv = $(btnEl.id.replace('_btn_','_pos_'));
		var posDivCoords = posDiv.getCoordinates();
		
		// step 1: extend short extension down
		btnEl.toolSlider1 = new Element('div', {
			styles: {
				position: 'absolute',
				top: btnCoords.height,
				left: 0,
				width: btnCoords.width - 2,
				height: 0,
				opacity: drawer.options.sliderBorderOpacity,
				color: 'transparent',
				borderLeft: '1px solid ' + drawer.options.sliderBorderColor,
				borderRight: '1px solid ' + drawer.options.sliderBorderColor,
				borderBottom: '1px solid ' + drawer.options.sliderBorderColor
			}
		});
		btnEl.toolSlider1.injectInside(posDiv);
		var bgDiv1 = new Element('div', { 
			styles: {
				width: '100%',
				height: '100%',
				opacity: drawer.options.sliderOpacity,
				borderWidth: 0,
				'text-align': 'center',
				backgroundColor: drawer.options.sliderBackColor
			}
		});
		bgDiv1.injectInside(btnEl.toolSlider1);
		var drawer = this;
		new Fx.Style(btnEl.toolSlider1, 'height', { duration: 100, transition: Fx.Transitions.linear } ).start(0,30).chain(function() {
			var fShowClearUI = function(elemToRemove) {
				var clearEl = new Element('a', 	{
					'href': '#',
					'tabindex': -1,
					'events': { 
						'click': function(event) {
							event = new Event(event);
							drawer._bnmap.shapeTool.clearShape();
							event.stop();
						}
					},
					styles: {
						'margin-left': 'auto',
						'margin-right': 'auto',
						color: 'white',
						'font-size': 12,
						'-moz-outline': '0px none black',
						'outline': '0px none black'
					}
				});			
				clearEl.innerHTML="clear";
				if(elemToRemove)
					elemToRemove.remove();
				clearEl.injectInside(bgDiv1);
				new Fx.Style(btnEl.toolSlider1, 'height', { duration: 50, transition: Fx.Transitions.linear } ).start(btnEl.toolSlider1.offsetHeight,20);
			}
			
			if(drawer._bnmap.shapeTool.isDrawing()) {			
				var helpEl = new Element('img', {
					src: drawer.options.shapeHelpImage,
					styles: {
						'height': 30,
						'width': 80,
						'display': 'block',
						'margin-left': 'auto',
						'margin-right': 'auto'
					}
				});
				helpEl.injectInside(bgDiv1);
				drawer.CurrExtendedShapeBtn = btnEl;
				
				var firstClickListener = GEvent.addListener(drawer._bnmap.map,"click",function(latLng) {
					GEvent.removeListener(firstClickListener);
					fShowClearUI(helpEl);
				});
			}
			else {
				// we extended the shape tool but aren't drawing - this measn we have a previously selected shape
				fShowClearUI(null);
			}
		});
	},
	retractShapeSlider: function(btnEl, fDoneCallback) {
		this._bnmap.shapeTool.abortInteractiveDrawing();
		if(btnEl.toolSlider1) {
			var drawer = this;
			new Fx.Style(btnEl.toolSlider1, 'height', { duration: 100, transition: Fx.Transitions.linear } ).start(btnEl.toolSlider1.offsetHeight,0).chain(function() {
				btnEl.toolSlider1.remove();
				btnEl.toolSlider1=null;
				drawer.CurrExtendedShapeBtn = null;
				if(fDoneCallback) {
					fDoneCallback();	
				}
			});	
		}
	},
	retractAnyOpenSlider: function(bLeaveShapeSliders,fCallback) {
		var drawer = this;
		if(drawer.CurrExtendedBtn != null ) {
			var currExtBtn = drawer.CurrExtendedBtn; // enclose
			currExtBtn.setProperty("BN_ISCHANGING","1");
			var currExtendedBtnType = /_btn_(.*)$/.exec(currExtBtn.id)[1];	
			var currExtendedBtnUpSrc = currExtBtn.src.replace(/_down.png$/,".png");
			drawer.retractToolSlider(currExtBtn, '', function() {
				currExtBtn.src = currExtendedBtnUpSrc;
				currExtBtn.setProperty("BN_ISCHANGING","0");
				if(fCallback) {
					fCallback();	
				}
			});
		}
		else if(bLeaveShapeSliders==false && drawer.CurrExtendedShapeBtn !=null ) {
			var currExtBtn = drawer.CurrExtendedShapeBtn; // enclose
			var currExtendedBtnUpSrc = currExtBtn.src.replace(/_down.png$/,".png");
			drawer.retractShapeSlider(currExtBtn, function() {
				currExtBtn.src = currExtendedBtnUpSrc;
				if(fCallback) {
					fCallback();	
				}
			});
		}
		else {
			if(fCallback) {
				fCallback();	
			}	
		}
	},
	doFind: function(s, initValue, fOnSuccess, progressElem, findElem) {
		if( s.trim()=="" || s==initValue ) {
			alert("Please enter a city name, neighborhood name or zip code");	
		}
		else {
			var _bnmap = this._bnmap; // enclosure
			findElem.setStyle('display','none');
			progressElem.setStyle('display', 'block');
			var infoReq = new Json.Remote(this._bnmap.options.baseUrl + "AdvSearchJSON.aspx?Cmd=QuickFind", {
				onComplete: function(response) {
					progressElem.setStyle('display', 'none');
					findElem.setStyle('display','block');
					if( response==null || response.latitude == 0 && response.longitude == 0 ) {
						alert("Location not found, please try a different search");
					}
					else {
						//alert(response.latitude + ',' + response.longitude);
						var dstZoom = 14;
						if(response.zoom && response.zoom>0)
							dstZoom = response.zoom;
						_bnmap.map.setCenter(new google.maps.LatLng(response.latitude, response.longitude),dstZoom);
						fOnSuccess();
					}
				},
				onFailure: function(response) {	
					progressElem.setStyle('display', 'none');
					findElem.setStyle('display','block');
					BNDebugLog("FAILED:");	
					BNDebugLog(response.statusText);
					BNDebugShowHTML(response.responseText);
				 	alert("An error occurred");
			  }
			});
			infoReq.send(s);
		}
	},
	doSaveMapSearch: function() {
		var bounds = this._bnmap.map.getBounds();
		var zoom = this._bnmap.map.getZoom();	
		var shape = this._bnmap.shapeTool.currentPolygon==null ? null : this._bnmap.shapeTool.getShapeParamString();

		var jsonParam = { 
			bounds: { NELat: bounds.getNorthEast().lat(), NELng: bounds.getNorthEast().lng(), SWLat: bounds.getSouthWest().lat(), SWLng: bounds.getSouthWest().lng() },
			zoom: zoom,
			search: this._bnmap.drawers.PropertySearch.searchParameters,
			layers: [],
			shape: shape
		};
		
		var drawer = this; // create enclosure
		var saveReq = new Json.Remote(this._bnmap.options.baseUrl + "AdvSearchJSON.aspx?Cmd=StoreSearch", {
		 	onComplete: function(response){
				var finalContentElemId = drawer.elem.id + "_savealert_content";
				$(finalContentElemId +'_prepare').setStyle('display','none');
				$(finalContentElemId +'_success').setStyle('display','block');
				$(finalContentElemId +'_failure').setStyle('display','none');
			},
			onFailure: function(response) {
				var finalContentElemId = drawer.elem.id + "_savealert_content";
				
				if($(finalContentElemId +'_failure_details')) {
					if(response.statusText && response.statusText.test('^ERROR:')) {
						$(finalContentElemId +'_failure_details').setText(response.statusText.substring(6));
						$(finalContentElemId +'_failure_details').setStyle('display','block');
					}
					else {
						$(finalContentElemId +'_failure_details').setStyle('display','none');
					}
				}
				
				$(finalContentElemId +'_prepare').setStyle('display','none');
				$(finalContentElemId +'_success').setStyle('display','none');
				$(finalContentElemId +'_failure').setStyle('display','block');
			}
		});
		saveReq.send(jsonParam);
	}
});

function BNStatusControl(bnmap,width){ this._bnmap = bnmap; this._width=width;}
BNStatusControl.prototype = new GControl();
BNStatusControl.prototype.printable = function() {return true;};
BNStatusControl.prototype.selectable = function() {return false;};
BNStatusControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 28));
}
BNStatusControl.prototype.initialize = function(map) {
  this._div=new Element('div',{ styles: { width: this._width, opacity:0.85 } });
  this._div.addClass('MapSearchStatusCtl');
  map.getContainer().appendChild(this._div);
  return this._div;
}
BNStatusControl.prototype.destroy = function() { if(this._div) this._div.remove(); };
BNStatusControl.prototype.setStatus = function(htmlMessage, useIconId) {
	this._div.setStyle('display','block');
	this._div.innerHTML="<table align='left' width='100%' border='0'><tr id='MapStatusTr'></tr></table>";
	var row = this._div.getElement('tr[id=MapStatusTr]')
	var cell = $(row.insertCell(0));
	cell.innerHTML = htmlMessage;		
	var _bnmap = this._bnmap;
	cell.getElements('a[rel=zoom_in]').each(function(el) {
		el.href='#';
		el.addEvent('click',function(event) {
			var event = new Event(event);
			event.stop();
			_bnmap.map.setZoom(_bnmap.map.getZoom()+1);
		});
	});
	cell.getElements('a[rel=zoom_out]').each(function(el) {
		el.href='#';
		el.addEvent('click',function(event) {
			var event = new Event(event);
			event.stop();
			_bnmap.map.setZoom(_bnmap.map.getZoom()-1);
		});
	});
	cell.getElements('a[rel=location]').each(function(el) {
		el.href='#';
		el.addEvent('click',function(event) {
			var event = new Event(event);
			event.stop();
			if(_bnmap.drawers["TopTools"]) {
				if(_bnmap.drawers["PropertySearch"]) {
					_bnmap.drawers["PropertySearch"].hideAdvancedSearchPanel();
				}
				var topToolsDrawer = _bnmap.drawers["TopTools"];
				topToolsDrawer.retractAnyOpenSlider(true, function() {																			
					topToolsDrawer.toggleButtonByType('location');
				});
			}
		});
	});
	cell.getElements('a[rel=savealert]').each(function(el) {
		el.href='#';
		el.addEvent('click',function(event) {
			var event = new Event(event);
			event.stop();
			if(_bnmap.drawers["TopTools"]) {
				var topToolsDrawer = _bnmap.drawers["TopTools"];
				topToolsDrawer.retractAnyOpenSlider(true, function() {																			
					topToolsDrawer.toggleButtonByType('savealert');
				});
			}
		});
	});
	cell.getElements('a[rel=criteria]').each(function(el) {
		el.href='#';
		el.addEvent('click',function(event) {
			var event = new Event(event);
			event.stop();
			if(_bnmap.drawers["PropertySearch"]) {
				var topToolsDrawer = _bnmap.drawers["TopTools"];
				var searchDrawer = _bnmap.drawers["PropertySearch"];
				if(topToolsDrawer) {
					topToolsDrawer.retractAnyOpenSlider(true, function() {																			
						searchDrawer.showAdvancedSearchPanel();
					});
				}
				else {
					searchDrawer.showAdvancedSearchPanel();
				}
			}
		});
	});
	cell.getElements('a[rel=criteria_reset]').each(function(el) {
		el.href='#';
		el.addEvent('click',function(event) {
			var event = new Event(event);
			event.stop();
			if(_bnmap.drawers["PropertySearch"]) {
				_bnmap.drawers["PropertySearch"].resetCriteria();
			}
		});
	});
	
	if(useIconId=='wait') {
		cell = row.insertCell(0);
		cell.width='1%';
		var img = new Element('img', {src: this._bnmap.options.imageResources.statusWaitImage, 'border': 0, styles: {float: 'left'} });
		img.injectTop(cell);	
	}	
};
BNStatusControl.prototype.hide = function() {
	this._div.setStyle('display','none');
}



var BNMapParcelLinesDrawer = BNMapDrawer.extend({					  
	onMapZoomChanged: function(zoom) {
		this.validateDisplay(zoom);
	},	
	validateDisplay: function(zoom) {
		zoom = zoom || this._bnmap.map.getZoom();	
		if( zoom < 16 ) {
			if( this.elem.style.display=='block' || this.elem.style.display=='' ) {
				this.elem.style.display='none';
				this.setLinesVisible(false);
			}
		}
		else { // if( zoom >= 16 ) 
			this.elem.style.display = '';
			var baseElemId = this.elem.id;	
			if( !this.UIInitialized ) {											
				var drawer = this; // create enclosure for event handlers

				// add parcelStream parcels layer (optional)
				var layers = ["Parcels"];
				this.tileLayer = new TiledLayer(this._bnmap.map , layers);
				
				// Turn it on for zoom levels 16-20
				this.tileLayer.setMinZoomLevel(16);
				this.tileLayer.setMaxZoomLevel(20);
				this.tileLayer.initialize();
	
				$(baseElemId + '_cbShow').addEvent('click', function() {
					if( $(baseElemId + '_cbShow').checked==false ) {				
						drawer.setLinesVisible(false);
					}
					else {
						drawer.setLinesVisible(true);										 
					}
				});
				
				this.UIInitialized = true;
				this.setLinesVisible($(baseElemId + '_cbShow').checked);				
			}
		}
	},
	setLinesVisible: function(bVisible) {
		if( this.UIInitialized && this.tileLayer!=null ) {
			this.tileLayer.setVisible(bVisible);	
		}
	}
});


//var _m = null;
/* supported options:
	baseUrl: url
	waitIcon: url
	waitIconSize: {width: n, height: n}
*/
function BNInitializeAdvMap(mapCanvasId,options) {
	var _m = new BNMap();
	_m.mapDivId = mapCanvasId;
	var hMapDiv = document.getElementById(mapCanvasId)
	_m.map = new google.maps.Map2(hMapDiv); 	
	
	// default options
	options= options || [];
	options.baseUrl = options.baseUrl || "/";
	options.waitIcon = options.waitIcon || "/MapImages/waitAnim.gif";
	options.waitIconSize = options.waitIconSize || {width: 16, height: 16};
	
	_m.options = options;
	
	// setup map controls
	_m.statusControl = new BNStatusControl(_m, 174);
	_m.map.addControl(_m.statusControl);
	_m.statusControl.hide();

	_m.map.addMapType(G_PHYSICAL_MAP); 	
	var typeCtl = new google.maps.MenuMapTypeControl();
	_m.map.addControl(typeCtl);		
  if( hMapDiv.offsetWidth > 250 ) {
		_m.map.addControl(new google.maps.OverviewMapControl());
		if( window.TrafficMapTypeControl ){
			_m.map.addControl(new TrafficMapTypeControl({showTraffic: true, showTrafficKey: true}), new google.maps.ControlPosition(G_ANCHOR_TOP_RIGHT, new google.maps.Size(87,7)) );
		}
	}	
	var bHasLargeMapControl = false;
	if( hMapDiv.offsetHeight > 250 ) {
			 _m.map.addControl(new google.maps.LargeMapControl());
			 bHasLargeMapControl = true;
	}
	else {
			_m.map.addControl(new google.maps.SmallMapControl());
	}		
	_m.map.enableDoubleClickZoom();
	
	
	// initialize map
	if( options.defaultBounds ) {
		var zoomLev = _m.map.getBoundsZoomLevel(new google.maps.LatLngBounds(
				new google.maps.LatLng(options.defaultBounds.southWest.lat,options.defaultBounds.southWest.lon), 
				new google.maps.LatLng(options.defaultBounds.northEast.lat,options.defaultBounds.northEast.lon)));		
		/*if( zoomLev > 11 )
			zoomLev = 11;*/ // cap at a reasonable level
		_m.map.setCenter(new google.maps.LatLng((options.defaultBounds.northEast.lat+options.defaultBounds.southWest.lat)/2, (options.defaultBounds.northEast.lon+options.defaultBounds.southWest.lon)/2), zoomLev);
	}
	else {
		_m.map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 8);
	}
	_m.map.setMapType(G_PHYSICAL_MAP); 
	_m.LastAutosetMapType = G_PHYSICAL_MAP;
	
	// BNAddDragZoom(_m.map,bHasLargeMapControl);

	_m.markerMgr = new MarkerManager(_m.map);		
	google.maps.Event.addListener(_m.map, "moveend", function() {_m.onMapLocationChanged();} );
	google.maps.Event.addListener(_m.map, "zoomend", function() {_m.onMapLocationChanged();} );

	_m.shapeTool = new BNShapeTool(_m,options.shapeTool);
	_m.shapeTool.addEvent('shapeCreated', function() {
		if(_m.shapeTool.currentPolygon!=null) {
			var boundingBox = _m.shapeTool.currentPolygon.getBounds();
			var zoomLev = _m.map.getBoundsZoomLevel(boundingBox);
			_m.map.setCenter(boundingBox.getCenter(), zoomLev);
		}
	});
	_m.shapeTool.addEvent('shapeModified', function() {
		_m.onMapLocationChanged(true);													
	});

	var drawer = new BNMapPropertySearchDrawer("PropertySearch", $(options.searchDrawer.baseDivId), "Property Search", options.searchDrawer.options );
	_m.RegisterDrawer(drawer);
	drawer = new BNMapTopToolsDrawer("TopTools", $(options.topToolsDrawer.baseDivId), "Top Tools", options.topToolsDrawer.options );
	_m.RegisterDrawer(drawer);
	drawer = new BNMapLegendDrawer("Legend", $(options.legendDrawer.baseDivId), "Legend", options.legendDrawer.options );
	_m.RegisterDrawer(drawer);
	drawer = new BNMapFilmStripDrawer("FilmStrip", $(options.filmStripDrawer.baseDivId), "Result Pictures", options.filmStripDrawer.options );
	_m.RegisterDrawer(drawer);
	if( options.officesDrawer ) {
		drawer = new BNMapOfficesDrawer("Offices", $(options.officesDrawer.baseDivId), "Offices", options.officesDrawer.options );
		_m.RegisterDrawer(drawer);
	}
	if( options.schoolsDrawer ) {
		drawer = new BNMapSchoolsDrawer("Schools", $(options.schoolsDrawer.baseDivId), "Schools", options.schoolsDrawer.options );
		_m.RegisterDrawer(drawer);
	}
	if( options.parcelLinesDrawer ) {
		drawer = new BNMapParcelLinesDrawer("Parcel Lines", $(options.parcelLinesDrawer.baseDivId), "Parcel Lines", options.parcelLinesDrawer.options );
		_m.RegisterDrawer(drawer);
	}
	if(options.resultsGridDrawer) {
		drawer = new BNMapResultsGridDrawer("ResultsGrid", $(options.resultsGridDrawer.baseDivId), "Results Grid", options.resultsGridDrawer.options );	
		_m.RegisterDrawer(drawer);
	}

	// load initial locations
	_m.onMapLocationChanged();	
	window.addEvent('resize',function() {
		_m.onResize();							  						  
	});
}

/*
function BNAddDragZoom(hMap,bHasLargeMapControl) {
	var styleOpts = {};
	var otherOpts = {};
	otherOpts.buttonHTML = 'Drag-Zoom';
	otherOpts.buttonZoomingHTML = 'Drag a region on the map to zoom';
	otherOpts.overlayRemoveTime = 1500;
	otherOpts.buttonStyle = {background: '#FFFFFF' };
	otherOpts.buttonStartingStyle = {width: '63px', border: '2px outset #CCCCCC', borderLeft: '1px solid black', borderTop: '1px solid black', padding: '1px 3px 1px 2px', fontFamily: 'tahoma', fontSize: '12px' };
	otherOpts.buttonZoomingStyle = {border: '1px dashed black', width: '95px', background: '#CCCCCC' };
	zcontrol = new DragZoomControl(styleOpts, otherOpts, {});
	hMap.addControl(zcontrol,new google.maps.ControlPosition(G_ANCHOR_TOP_LEFT,new GSize(2, bHasLargeMapControl ? 275 : 105 )));
}
*/

/* prototype additions for google maps objects */
google.maps.Marker.prototype.BN_SelectImage = function(sImageType) {
	try {
		if( sImageType=="selected" && this.BN_selectedIconImage) {
			this.setImage(this.BN_selectedIconImage);	
		}
		else if( this.BN_standardIconImage ) {
			this.setImage(this.BN_standardIconImage);
		}
	}
	catch(ex1) {
	}
};




function BNDebugLog(s) {
	var output = $("output") 
	if( output )
		output.value += s + '\n';
}
function BNDebugShowHTML(s) {
	var output = $("debugDiv") 
	if( output )
		output.innerHTML = s;
}
function odump(object, depth, max){
  depth = depth || 0;
  max = max || 2;

  if (depth > max)
    return false;

  var indent = "";
  for (var i = 0; i < depth; i++)
    indent += "  ";

  var output = "";  
  for (var key in object){
    output += "\n" + indent + key + ": ";
    switch (typeof object[key]){
      case "object": output += odump(object[key], depth + 1, max); break;
      case "function": output += "function"; break;
      default: output += object[key]; break;        
    }
  }
  return output;
}
