function Timer(){this.obj=(arguments.length)?arguments[0]:window;return this;}
Timer.prototype.setInterval=function(func,msec){var i=Timer.getNew();var t=Timer.buildCall(this.obj,i,arguments);Timer.set[i].timer=window.setInterval(t,msec);return i;}
Timer.prototype.setTimeout=function(func,msec){var i=Timer.getNew();Timer.buildCall(this.obj,i,arguments);Timer.set[i].timer=window.setTimeout("Timer.callOnce("+i+");",msec);return i;}
Timer.prototype.clearInterval=function(i){if(!Timer.set[i]){return;}
window.clearInterval(Timer.set[i].timer);Timer.set[i]=null;}
Timer.prototype.clearTimeout=function(i){if(!Timer.set[i]){return;}
window.clearTimeout(Timer.set[i].timer);Timer.set[i]=null;}
Timer.set=new Array();Timer.buildCall=function(obj,i,args){var t="";Timer.set[i]=new Array();if(obj!=window){Timer.set[i].obj=obj;t="Timer.set["+i+"].obj.";}
t+=args[0]+"(";if(args.length>2){Timer.set[i][0]=args[2];t+="Timer.set["+i+"][0]";for(var j=1;(j+2)<args.length;j++){Timer.set[i][j]=args[j+2];t+=", Timer.set["+i+"]["+j+"]";}}
t+=");";Timer.set[i].call=t;return t;}
Timer.callOnce=function(i){if(!Timer.set[i]){return;}
eval(Timer.set[i].call);Timer.set[i]=null;}
Timer.getNew=function(){var i=0;while(Timer.set[i]){i++;}
return i;}
var LoadEventHandler=Class.create();LoadEventHandler.prototype={initialize:function(){},add:function(func){if(this.alreadyRun){func();}
else{this.addEvent(func);}},alreadyRun:false,_events:[],addEvent:function(func){this._events.push(func);},doEvents:function(){this.alreadyRun=true;var f=function(f){f();};this._events.each(f);}};var onLoadHandler=new LoadEventHandler();initializePage={map:function(){resizePage.init();if(typeof(development_mode)=='undefined'){window.onerror=reportBug;}
searchFilters.toggle(false);searchFilters.restripe();map=new GMap2($('gmap'));moveMapElements();force_polygons();map.checkResize();map.queryCenter=new GLatLng((max_y+min_y)/2,(max_x+min_x)/2);map.setCenter(map.queryCenter,12);if(max_x&&max_y&&min_x&&min_y){var bounds=new GLatLngBounds();bounds.extend(new GLatLng(max_y,max_x));bounds.extend(new GLatLng(min_y,min_x));zoom=map.getBoundsZoomLevel(bounds);}
map.setZoom(zoom);updateMapCenter();map.enableScrollWheelZoom();GEvent.addListener(map,"zoomend",function(){update_map();});GEvent.addListener(map,"dragend",dragEnd);GEvent.addListener(map,"moveend",moveEnd);GEvent.addListener(map,"infowindowopen",infoWindowOpen);map.addControl(new GLargeMapControl());map.addControl(new GScaleControl());resizePage.resize();window.onresize=function(){resizePage.resize();map.checkResize();};setupTooltip(map);current_lots=new Lots();new Form.Element.Observer('full_text',0.1,full_text_observer);new Form.Element.Observer('transit_stops',0.1,transit_search_observer);var temp=$('order_by').value.split('_');set_order_img(temp[0],temp[1]);var initial_page=current_page();var fff=function(){update_map(initial_page);NotificationBar.show(Content.city_search_error_txt,$('map_notification'));};if(initial_area_id){location_search(fff,{skip_open_map:true,area_id:initial_area_id,dist:initial_dist,area_type:initial_area_type,initial_load:true});}else if(!initial_location.blank()){EstatelyLog('running initial location_search');location_search(fff,{skip_open_map:true,loc:initial_location,dist:initial_dist,initial_load:true});}
else{update_map(initial_page);}
DropDown=new DropDownController();createListingGallerySpotlight();generalSpotlight=new Spotlight('general','page_container');},listing:function(){if(Estately.partner.get('isSet')===false){initializePage.map();}
else{resizePage.init();resizePage.resize();window.onresize=function(){resizePage.resize();};createListingGallerySpotlight();generalSpotlight=new Spotlight('general','page_container');}},listingAjax:function(){}};function get_permalink(){return $('permalink').href;};function save_search(){var area='';var popupDiv=new Element('div');popupDiv.update('Type a name for this search:<br/>');var form=new Element('form',{action:"/saved_searches/create",method:"post"});var nameInput=form.appendChild(new Element('input',{type:"text",name:"name",value:area}));form.appendChild(new Element('input',{type:"hidden",name:"bookmark",value:get_permalink()}));form.appendChild(new Element('input',{type:"hidden",name:"authenticity_token",value:auth_token}));form.appendChild(new Element('input',{type:"submit",value:"Save"}));popupDiv.appendChild(form);open_map_overlay("Save Search",popupDiv);nameInput.focus();nameInput.select();}
function set_daily_property_alerts(){open_alert('subscribing...');var f=function(){open_alert('You are now subscribed to saved properties email alerts');var subscription_ele=$('daily_property_alert_subscription');subscription_ele.onclick='';subscription_ele.innerHTML='You are now subscribed to daily alerts!';};new Ajax.Request('/account/set_daily_property_alerts',{method:'post',onSuccess:f});};function save_property(id){EstateyLog('USING DEPRECIATED SAVE FUNCTION. Please update.');Home.toggleState('save',id,false);}
function remove_property(id){EstateyLog('USING DEPRECIATED UNSAVE FUNCTION. Please update.');Home.toggleState('save',id,true);}
Home={'save':{'verb':'unsave','true':{url:'/saved_properties/destroy',msg1:'Unsaving home...',msg2:'Home is no longer saved.',verb1:'Unsave',verb2:'Save'},'false':{url:'/saved_properties/create',msg1:'Saving home...',msg2:'Home is now saved.',verb1:'Save',verb2:'Unsave'}},'hide':{'verb':'unhide','true':{url:'/trashed_properties/destroy',msg1:'Unhiding home...',msg2:'Home is no longer hidden.',verb1:'Unhide',verb2:'Hide'},'false':{url:'/trashed_properties/create',msg1:'Hiding home...',msg2:'The property will not appear in your search results. <a href="#" onclick="Home.toggleState(\'hide\', \'#id\', true); return false;">Undo</a>?',verb1:'Hide',verb2:'Unhide'}},toggleState:function(action,id,state){if(typeof(this[id])!=='undefined'){EstatelyLog('Still processing...');return false;}
this[id]=true;var textEl=textEl||false;var togglePoints=$$('.home_'+id);var textPoints=$$('.text_'+action+'_'+id);if(!togglePoints.length&&(typeof(state)==='undefined')){return false;}
if(typeof(state)==='undefined'){state=togglePoints[0].hasClassName('home_'+this[action].verb);}
var params=this[action][state];NotificationBar.show(params.msg1,$('map_notification'));var onSuccess=function(){togglePoints.each(function(el){el.removeClassName('home_'+params.verb1.toLowerCase()).addClassName('home_'+params.verb2.toLowerCase());if(textPoints){textPoints.each(function(el){el.update(el.innerHTML.replace(params.verb1,params.verb2));});}
NotificationBar.show(params.msg2.gsub('#id',id),$('map_notification'));});delete Home[id];if(action=='save'){if(!!state&&current_lots.has_property(id)){current_lots.property(id).unsave_property();}
else if(!state&&current_lots.has_property(id)){current_lots.property(id).save_property();}}
else if((action=='hide')&&(!state)){if(current_lots){EstatelyLog('found current_lots');current_lots.remove_property(id);}}};new Ajax.Request(params.url,{method:'post',postBody:'property_id='+id,onSuccess:onSuccess,on403:function(){}});}};function force_polygons(){if(document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#SVG","1.1")){_mSvgEnabled=true;_mSvgForced=true;}}
function add_user_area(){var newInput=new Element("input",{type:"text",name:"areas_of_interest[]",onfocus:"$('create_buyer_area_list_slow_tip').show();",onblur:"$('create_buyer_area_list_slow_tip').hide()"});var newDiv=new Element("div");newDiv.appendChild(newInput);new Insertion.Bottom($("buyer_area_list"),newDiv);new Ajax.Autocompleter(newInput,"buyer_area_list_auto_complete","/auto_complete/buyer_area",{});}
var Content={saved_properties_email_error:'Unable to update your saved property email option!',saved_properties_email_error:'Your saved property email option has been updated',bubble_error_txt:"Application Error!\n  Please try again in a few seconds.",search_error_txt:"Application Error!\n Please try your search again.",tab_error_txt:'<div class="splash_main" style="padding: 40px 55px; text-align: center;"><h2>Application Error!</h2>Something weird just happened... please try again in a few seconds.</div>',city_search_error_txt:"Unknown location!"};function open_alert(message,urgency,fade){if($("alert_message")!=null){$("alert_message").innerHTML=message;if(urgency=="high"){$("alert_table").style.backgroundColor="#fa6464";}
else{$("alert_table").style.backgroundColor="#64b1fa";};$("alert").show();if(!(fade==false)){setTimeout('Effect.Fade(\'alert\')',10000);};}}
function close_alert(){if($("alert")!=null){$("alert").style.display="none";}}
function open_map_overlay(title,msg,width){if(typeof(width)==='undefined'){width='300';}
$('map_overlay_dialog').setStyle({'width':(width+'px'),'marginLeft':((width/-2)+'px')});$('map_overlay_title').update(title);if(typeof(msg)=="string"){$('map_overlay_contents').update(msg);}else{$('map_overlay_contents').update('');$('map_overlay_contents').appendChild(msg);}
$('map_overlay').show();var height=($('map_overlay_dialog').getHeight()/-2)+'px';$('map_overlay_dialog').setStyle('margin-top:'+height);}
function close_map_overlay(){$('map_overlay').hide();}
function set_location_search(location,options){if(!options){options={};}
$('search_location').value=location;if(options.buffer){$('place_search_buffer').value=options.buffer;}
if(options.area_id){$('search_area_id').value=options.area_id;}
if(options.area_type){$('search_area_type').value=options.area_type;}}
function location_search(failure,options){if(!options){options={};}
skip_open_map=options.skip_open_map;if(!failure){failure=function(){NotificationBar.show(Content.city_search_error_txt,$('map_notification'));};}
f=function(){failure();PageUpdater.set_default('city');};ff=function(){new Ajax.Request('/map/city_search',{onFailure:f,parameters:{location:options.loc||$('search_location').value,area_id:options.area_id||$('search_area_id').value,area_type:options.area_type||$('search_area_type').value,buffer:options.dist||$('place_search_buffer').value,initial_load:options.initial_load?'true':false}});};current_lots.unselect();PageUpdater.set_loading('city');if(skip_open_map){ff();}
else{show_map({after_open:ff});}}
function scrollToResult(result){if(!result){return false;}
var results=$('search_results');results.scrollTop=result.cumulativeOffset().top-results.cumulativeOffset().top-(results.getHeight()/2-10);}
var resizePage={init:function(){this.pageContainer=$('page_container');this.searchFilters=$('search_filters');this.searchColumn=$('search_column');this.searchResults=$('search_results');this.contentColumn=$('content_column');this.contentPages=$('content_pages');this.contentMap=$('content_map');this.mapStatusbar=$('map_statusbar');this.gmap=$('gmap');this.mapHeight=130;this.searchHeightAdjust=this.searchHeightAdjust||0;if(Estately.partner.get('name')==='findwell'){this.mapHeight=200;this.searchHeightAdjust=-70;}
else if(Estately.partner.get('name')==='sutton'){this.mapHeight=122;this.searchHeightAdjust=-109;}
this.resize();},resize:function(){this.docHeight=document.viewport.getHeight();var docHeight=this.docHeight;var mapHeight=this.mapHeight;this.resizeFilters();var hContentColumn=(docHeight-mapHeight-2)+'px';this.contentColumn.setStyle('min-height:'+hContentColumn+';height:auto!important; height:'+hContentColumn);this.contentMap.setStyle('height:'+(docHeight-mapHeight-11)+'px');this.gmap.setStyle('height:'+(docHeight-mapHeight-13-24)+'px');docWidth=document.viewport.getWidth();if(docWidth>1310){var wContentMap=(docWidth-315-15-10)+'px';var wContentPages='970px';var wMapStatusbar=(docWidth-315-15-12)+'px';var wPageContainer='auto';}else if(docWidth>969){var wContentMap=(docWidth-315-15-10)+'px';var wContentPages='auto';var wMapStatusbar=(docWidth-315-15-12)+'px';var wPageContainer='auto';}else{var wContentMap='630px';var wContentPages='auto';var wMapStatusbar='628px';var wPageContainer='970px';}
this.contentMap.setStyle('width:'+wContentMap);this.contentPages.setStyle('width:'+wContentPages);this.mapStatusbar.setStyle('width:'+wMapStatusbar);this.pageContainer.setStyle('width:'+wPageContainer);if(!!this.searchColumn){this.resizeSearch(true);}},resizeSearch:function(chained){chained=chained||true;var y=this.docHeight-15-7-this.searchColumn.getHeight()+this.searchResults.getHeight();y+=this.searchHeightAdjust;if(Estately.partner.get('isSet')){y-=115;}
if(y>50){this.searchResults.setStyle('height:'+y+'px');}
else{this.searchResults.setStyle('height:50px');}
if(!chained){(function(){resizePage.resizeSearch(true);}).delay(3);}},resizeFilters:function(){var ratio=2.8;var docHeight=document.viewport.getHeight();var searchFilters=this.searchFilters;if(!!this.searchColumn){searchFilters.setStyle({'height':'auto'});var filterHeight=searchFilters.getHeight();if(docHeight/filterHeight<ratio){searchFilters.setStyle({'height':docHeight/ratio+'px'});}}}};PageUpdater={id:0,is_updating:function(){if(this.is_updating_data['gmap']||this.is_updating_data['city']){return true;}
else{return false;}},is_updating_data:{gmap:false,city:false},set_default:function(type){this.is_updating_data[type]=false;if(!this.is_updating()){this.is_updating_data[type]=true;this.hide_loading();this.is_updating_data[type]=false;}},set_loading:function(type){this.is_updating_data[type]=true;this.show_loading();},hide_loading:function(){if(this.is_updating()){$('map_loading').addClassName('hide');document.body.style.cursor='default';}
else{EstatelyLog('not hiding loading div ');}},show_loading:function(){if(this.is_updating()){$('map_loading').removeClassName('hide');document.body.style.cursor='progress';}},get_id:function(){this.id=this.id+1;return this.id;},is_current_id:function(test_id){if(test_id==this.id){return true;}
else{return false;}}};function open_element(element){Element.show(element);new Effect.Highlight(element);}
function clearDefault(el){if(el.defaultValue==el.value){el.value="";}}
function agent_slide(element){target=$(element.id+'_target');if((target.style)&&(target.style.display=='none')){Effect.SlideDown(target,{duration:0.3});element.parentNode.className='show_less';}
else{Effect.SlideUp(target,{duration:0.3});element.parentNode.className='show_more';}}
function slide(element,open_link,close_link){target=$(element.id+'_target');if((target.style)&&(target.style.display=='none')){Effect.SlideDown(target.id);if(close_link){element.innerHTML=close_link;}}
else{Effect.SlideUp(target.id);if(open_link){element.innerHTML=open_link;}}}
function blind(element,duration){target=$(element.id+'_target');if((target.style)&&(target.style.display=='none')){Effect.BlindDown(target.id,duration);}
else{Effect.BlindUp(target.id,duration);}}
function number_to_currency(nStr,precision){var multiplier=Math.pow(10,precision);nStr=Math.round(parseFloat(nStr)*multiplier)/multiplier;nStr+='';var x=nStr.split('.');var x1=x[0];var x2=x.length>1?'.'+x[1]:'';var rgx=/(\d+)(\d{3})/;while(rgx.test(x1)){x1=x1.replace(rgx,'$1'+','+'$2');}
return'$'+x1+x2;}
function complexParseFloat(string){var scrubbed=string.toString().gsub(/[^1234567890.]/,'');if(scrubbed=='')
scrubbed='0';return(parseFloat(scrubbed));}
function setCookie(name,value){document.cookie=name+'='+escape(value)+';';}
function getCookie(name){name+='=';start=document.cookie.indexOf(name);if(start!=-1){start+=name.length;end=document.cookie.indexOf(';',start);if(end==-1)end=document.cookie.length;return(unescape(document.cookie.substring(start,end)));}else{return null;}}
function setRssFeedUrl(url){var elements=$$("#map_rss_button option[value!='none']");for(i=0;i<elements.length;i++){if(!elements[i].getAttribute('base_href')&&elements[i].getAttribute('base_href')!='')
elements[i].setAttribute('base_href',elements[i].getAttribute('value'));if(elements[i].getAttribute('base_href')!='')
url=encodeURIComponent(url);elements[i].setAttribute('value',elements[i].getAttribute('base_href')+url);}}
function showNoAddressError(mls,ln){open_map_overlay("Why can't I see this address?","<p class='last-child'>Unfortunately, local MLS rules prevent us from displaying the address. You can <a href='/about/contact_us?subject=About+"+mls+"+"+ln+"'>contact us</a> for more information on any property.</p>");}
var searchFilters={toggle:function(state){var toggleFilters=$('toggle_filters');var toggleFilterText=$('toggle_filters_text');var additionFilters=$('additional_filters');if(typeof(state)==='undefined'){var state=toggleFilters.hasClassName('more');if(state){EstatelyEvent('Map - Search Filters','Show More');}
else{EstatelyEvent('Map - Search Filters','Show Less');}}
if(state){toggleFilters.removeClassName('more').addClassName('less');toggleFilterText.update('Hide Unused Search Options');additionFilters.removeClassName('hidden');additionFilters.select('*[disabled]').each(function(el){el.enable();});}else{toggleFilters.removeClassName('less').addClassName('more');toggleFilterText.update('Show More Search Options');additionFilters.addClassName('hidden');additionFilters.select('.filter').each(function(filter){if(searchFilters.checkStatus(filter)){filter.addClassName('visible');}else{filter.removeClassName('visible');}});additionFilters.select('.filter:not([class~="visible"]) select, .filter:not([class~="visible"]) input').each(function(el){el.disable();});this.restripe();}
resizePage.resizeFilters();resizePage.resizeSearch(true);},remove:function(filter){var filterLabel=$(filter).down('label').innerHTML.replace(':','');EstatelyEvent('Map - Search Filters','Remove: '+filterLabel);var filterInUse=this.checkStatus(filter);if(filterInUse){filter.removeClassName('visible').select('select, input').each(function(el){el.disable().clear().selectedIndex=0;});update_map();}else{filter.removeClassName('visible');}
resizePage.resizeFilters();resizePage.resizeSearch(true);this.restripe();},reset:function(formControl){$(formControl).clear().selectedIndex=0;},checkStatus:function(filter){var status=false;if(filter.id==='filter_transit'){transitDistance=$('transit_dist');status=!transitDistance.options[transitDistance.selectedIndex].selected;status=$('transit_stops').present();return status;}
var selectFields=filter.select('select');var inputFields=filter.select('input');selectFields.each(function(el){if(el.selectedIndex>0){status=true;}});inputFields.each(function(el){if(el.present()){status=true;}});return status;},restripe:function(){$$('#additional_filters .visible').each(function(el,i){if(i%2===0){el.removeClassName('even').addClassName('odd');}
else{el.removeClassName('odd').addClassName('even');}});}};searchBounds={toggle:function(state){var boundsMenu=$('search_bounds_menu');if(typeof(state)==='undefined'){var state=!boundsMenu.hasClassName('show');}
if(state){boundsMenu.addClassName('show');this.boundEvent=searchBounds.click.bindAsEventListener();Event.observe(document,'click',searchBounds.boundEvent);}else{boundsMenu.removeClassName('show');Event.stopObserving(document,'click',searchBounds.boundEvent);}},click:function(event){var clickedEl=Event.element(event);if((clickedEl.id!=='search_bounds')&&(!clickedEl.up('#search_bounds'))){searchBounds.toggle(false);}},set:function(anchor,distance){var boundsMenu=$('search_bounds_menu');boundsMenu.removeClassName('show');if(anchor.hasClassName('selected')){return false;}
EstatelyEvent('Map - Location Searchbar','Set: Bounds',distance.toString());anchor.up().down('.selected').removeClassName('selected');anchor.addClassName('selected');$('place_search_buffer').value=distance;this.update(distance);location_search();},update:function(distance){var boundsDisplay=$('search_bounds');switch(distance){case-1:boundsDisplay.update('<b>+</b>Map');break;case 0:boundsDisplay.update('<b>+0</b> mi');break;case 805:boundsDisplay.update('<b>+0.5</b> mi');break;case 1609:boundsDisplay.update('<b>+1</b> mi');break;case 3218:boundsDisplay.update('<b>+2</b> mi');break;case 8046:boundsDisplay.update('<b>+5</b> mi');break;case 16093:boundsDisplay.update('<b>+10</b> mi');break;}}};mapPagination={setCurrentPage:function(page){this.currentPage=page;},setPage:function(by,el){if(this.isDisabled(el)){return false;}
EstatelyEvent('Other - Optimization','Pagination','Click');update_map((this.currentPage+by));},isDisabled:function(el){if(el.hasClassName('disabled')){return true;}
if(!$('map_loading').hasClassName('hide')){return true;}
return false;}};Array.prototype.remove=function(s){for(i=0;i<this.length;i++){if(s==this[i])this.splice(i,1);}};DropDownController=Class.create();DropDownController.prototype={initialize:function(){document.body.onclick=this.onBodyClick.bind(this);this._justClicked=null;this._open_ele=null;},resetEle:function(){if(this._open_ele&&this._open_ele.visible()&&this._open_ele!=this._justClicked){this._open_ele.removeClassName('drop_down_selected');$(this._open_ele.id+'_target').removeClassName('drop_down_displayed');this._open_ele=null;}},onBodyClick:function(){this.resetEle()
this._justClicked=null;},onClick:function(ele){if(ele.className!='drop_down_selected'){this.resetEle();this.justClicked(ele);target=$(ele.id+'_target');Element.Methods.addClassName(ele,'drop_down_selected');Element.Methods.addClassName(target,'drop_down_displayed');target.style.top=Element.getHeight(ele)-(parseInt(ele.getStyle('borderBottomWidth')||0)+parseInt(ele.getStyle('borderTopWidth'))||1)+'px';}},justClicked:function(ele){this._justClicked=ele;this._open_ele=ele}}
function MarkerManager(mapvar,options){this.initialize(mapvar,options);}
MarkerManager.prototype={initialize:function(mapvar,options){this.map=mapvar;this.properties={};this.condo_buildings=[];this.selected_id=0;if(!options){options={};};this.use_tabs=options.use_tabs;},add_new_lots:function(incoming_lots,condo_buildings,options){if(!options){options={};}
var class_suffixes=options.class_suffixes||[''];var left_column_text='';for(var j=0;j<incoming_lots.length;j++){cf=class_suffixes[j%class_suffixes.length];this.properties[incoming_lots[j].id]=new Lot(incoming_lots[j],cf,this.map,this);if(options.add_to_list){left_column_text+=this.properties[incoming_lots[j].id].left_column_text();}}
if(options.add_to_list){this.add_to_left_column(options.list_id,left_column_text);}
for(var i=0;i<condo_buildings.length;i++){this.condo_buildings[i]=new MarkerCondoBuilding(condo_buildings[i],this.properties[condo_buildings[i].condos[0]],this.map,this);}},add_to_left_column:function(listId,resultsHtml){var resultsWrapper=$(listId);resultsWrapper.update(resultsHtml);resultsWrapper.stopObserving();resultsWrapper.observe('click',function(event){Event.stop(event);var element=Event.element(event);if(element.tagName!=='EM'){if(element.tagName!=='A'){element=element.up('a');}
var id=element.id.gsub('result_','');this.properties[id].on_click();}else{EstatelyEvent('Map - Search Results','Save Star',element.hasClassName('saved')?'Unsave':'Save');var id=element.up('a').id.gsub('result_','');this.properties[id].do_star_click();}}.bindAsEventListener(this));resultsWrapper.observe('mouseover',function(event){var element=Event.findElement(event,'A');var id=element.id.gsub('result_','');this.properties[id].mouse_over();}.bindAsEventListener(this));resultsWrapper.observe('mouseout',function(event){var element=Event.findElement(event,'A');var id=element.id.gsub('result_','');this.properties[id].mouse_out();}.bindAsEventListener(this));},empty:function(){this.properties={};this.condo_buildings=[];},property:function(id){return this.properties[id];},is_selected:function(id){return id==this.selected_id;},has_property:function(id){return this.properties[id]?true:false;},selected_property:function(){return this.property(this.selected_id);},has_selected_property:function(){return this.has_property(this.selected_id);},switch_focus:function(id){var old_id=this.selected_id;this.selected_id=id;if(old_id!=this.selected_id){if(this.has_selected_property()){this.selected_property().select();};if(this.has_property(old_id)){this.property(old_id).unselect();};};},show_bubble:function(){EstatelyLog("show_bubble? "+this.use_tabs);if(this.use_tabs){return(tabs.get_tab().indexOf('map')!=-1)?true:false;};return true;}};function Lot(data,cf,mapvar,manager){this.initialize(data,cf,mapvar,manager);};Lot.prototype={initialize:function(data,cf,mapvar,manager){this.id=data.id;this.map=mapvar;this.manager=manager;this._class_suffix=cf;this.data=data;this.full_data=false;var this_lot=this;this.build_marker(mapvar);},left_small:function(){return $('result_'+this.id);},remove:function(){this.marker.remove();$('result_'+this.data.id).hide();},left_column_text:function(){var this_lot=this;var mapped='';if(this.data.has_marker==0){mapped=' (not mapped)';};var safeAddress=this.data.address.gsub('"','');var wrappingAddress=safeAddress.replace(/(\S(?!$))/g,"$1&shy;");return'<a href="\#" id="result_'+this.data.id+'" class="r '+this.data.mls_acronym+this.alternating_class()+'">'+'<b class="a" title="'+safeAddress+mapped+'">'+'<em class="'+this.star_class(this.data.saved)+'" onmouseover="$(this).addClassName(\'hover\')" onmouseout="$(this).removeClassName(\'hover\')"></em>'+
wrappingAddress+'</b>'+
(this.data.mls_logo||'')+'<b class="b">'+this.data.price+'</b>'+'<b class="c">'+this.data.bedrooms+'</b>'+'<b class="d">'+this.data.sqf+'</b>'+'<b class="e">'+this.data.days+'</b>'+'</a>';},save_property:function(){this.data.saved=true;this.left_small_star_behavior();this.marker.rebuild();},unsave_property:function(){this.data.saved=false;this.left_small_star_behavior();this.marker.rebuild();},left_small_star:function(){return $('result_'+this.data.id).down('em');},star_class:function(val){if(val){return'saved';}else{return'';};},do_star_click:function(){if(this.data.saved){Home.toggleState('save',this.data.id,true);}
else{Home.toggleState('save',this.data.id,false);}},left_small_star_behavior:function(){if(this.data.saved){this.left_small_star().addClassName(this.star_class(true));}else{this.left_small_star().removeClassName(this.star_class(true));}},build_marker:function(mapvar){if(this.data.has_marker!=0){if(this.data.type=='resi'){this.marker=new MarkerReal(this.data,this,mapvar);}else{this.marker=new MarkerCondo(this.data,this,mapvar);};}else{this.marker=new NoMarker(this);};},on_map:function(){if(this.has_marker()&&onMap({x:this.data.x,y:this.data.y})){return true;};return false;},has_marker:function(){return this.data.has_marker!=0;},type:function(){return this.data.type;},class_suffix:function(){return this._class_suffix;},alternating_class:function(){return this.class_suffix();},mouse_over:function(){this.do_mouse_over();this.marker.mouse_over();},do_mouse_over:function(){if(this.left_small()){this.left_small().addClassName("hover");};},select:function(){this.do_mouse_over();},unselect:function(){this.do_mouse_out();},mouse_out:function(){this.do_mouse_out();this.marker.mouse_out();},do_mouse_out:function(){if(this.left_small()&&!this.manager.is_selected(this.id)&&this.left_small()){this.left_small().removeClassName("hover");};},open_bubble:function(){this.marker.open_bubble(this.data);},on_click:function(){EstatelyLog('On Click');this.manager.switch_focus(this.id);if(this.manager.show_bubble()){EstatelyLog('showing bubble');this.open_bubble();EstatelyLog('creating PropertyView');new Ajax.Request('/property_views?kind=bubble&amp;property_ids%5B%5D='+this.id,{asynchronous:true,method:'post'});}else{EstatelyLog('showing tab');if(!tabs.is_listing()){changeContent(tabs.build_hash('listings_info',this));}else{changeContent(tabs.build_hash(tabs.get_tab(),this));};};}};function NoMarker(lot){this.lot=lot;};NoMarker.prototype={mouse_over:function(val){},mouse_out:function(val){},rebuild:function(){},open_bubble:function(data){changeContent(tabs.build_hash('listings_info',this.lot));},select:function(){},remove:function(){}};function MarkerCondo(data,lot,mapvar){this.lot=lot;this.tooltip="<div class='markerTooltip "+data.mls_acronym+"_tooltip'>"+data.address+" - "+data.price+"</div>";this.map=mapvar;}
MarkerCondo.prototype={marker:function(){if(this._building){return this._building.marker();}else{false;};},set_building:function(b){this._building=b;},building:function(){return this._building;},mouse_over:function(val){this.building().mouse_over(this.tooltip);},mouse_out:function(val){tooltip.style.visibility="hidden";highlight.style.visibility="hidden";},open_bubble:function(data){this.building().open_bubble(data,this.lot);},rebuild:function(){this.building().rebuild();}};function MarkerPlace(place,mapvar){this.tooltip="<div class='markerTooltip'>"+place.name+"</div>";this._marker=new GMarker(new GLatLng(place.y,place.x),arrow);this.marker=function(){return this._marker;};this.initialize(mapvar);};function MarkerReal(data,lot,mapvar){this.initialize(data,lot,mapvar);this.tooltip="<div class='markerTooltip "+lot.data.mls_acronym+"_tooltip'>"+lot.data.address+" &mdash; "+lot.data.price+"</div>";this.make_marker();};function MarkerCondoBuilding(data,lot,mapvar,manager){this.manager=manager;this.initialize(data,lot,mapvar);this.tooltip="<div class='markerTooltip "+data.mls_acronym+"_tooltip'>"+data.address+" - "+data.price+"</div>";this.condos=data.condos;this.lot=lot;this.marker=function(){return this._marker;};this.make_marker();for(var i=0;i<data.condos.length;i++){this.manager.property(data.condos[i]).marker.set_building(this);};};var MarkerTooltip={showTooltip:function(text){marker=this.marker();tooltip.innerHTML=(text==null)?this.tooltip:text;var point=this.map.getCurrentMapType().getProjection().fromLatLngToPixel(this.map.fromDivPixelToLatLng(new GPoint(0,0),true),this.map.getZoom());var offset=this.map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),this.map.getZoom());var anchor=marker.getIcon().iconAnchor;var width=marker.getIcon().iconSize.width;var height=tooltip.clientHeight;var pos=new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(offset.x-point.x-anchor.x+width,offset.y-point.y-anchor.y-height));var hpos=new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(offset.x-point.x-anchor.x-20,offset.y-point.y-anchor.y-20));pos.apply(tooltip);hpos.apply(highlight);tooltip.style.visibility="visible";if(this.has_highlight){highlight.style.visibility="visible";};}};var MarkerShared={initialize:function(data,lot,mapvar){this.has_highlight=true;this.lot=lot;this.map=mapvar;},add_listeners:function(){var lot=this.lot;GEvent.addListener(this.marker(),"click",function(){EstatelyLog('marker onclick: '+lot.id);lot.on_click();scrollToResult($('result_'+lot.id));});GEvent.addListener(this.marker(),"mouseover",function(){lot.mouse_over();});GEvent.addListener(this.marker(),"mouseout",function(){lot.mouse_out();});},rebuild:function(){if(this.lot.data.saved){this.marker().setImage(this.saved_icon());}
else{this.marker().setImage(this.not_saved_icon());}},remove:function(){this.marker().closeInfoWindow();this.marker().hide();},mouse_over:function(text){this.showTooltip(text);},mouse_out:function(){tooltip.style.visibility="hidden";highlight.style.visibility="hidden";},update_bubble:function(attempt_num){EstatelyLog('updating bubble...');this_marker=this;if($('bubble_property_'+this.lot.id)){$('bubble_property_'+this.lot.id).innerHTML=this.bubble_data.bubble_property_;if(!!$('bubble_description_'+this.lot.id)){$('bubble_description_'+this.lot.id).innerHTML=this.bubble_data.bubble_description_;}}else{if(!attempt_num){attempt_num=0;}
if(attempt_num<20){setTimeout(function(){this_marker.update_bubble(attempt_num+1);},250);}}},set_bubble:function(transport){EstatelyLog('setting bubble');response=transport.responseText.evalJSON();this.bubble_data={bubble_property_:response.property,bubble_description_:response.description};this.update_bubble(this.data);}};Object.extend(MarkerPlace.prototype,MarkerTooltip);Object.extend(MarkerPlace.prototype,{mouse_out:function(){tooltip.style.visibility="hidden";},initialize:function(mapvar){this.has_highlight=false;place=this;this.map=mapvar;GEvent.addListener(this.marker(),"mouseover",function(){place.showTooltip();});GEvent.addListener(this.marker(),"mouseout",function(){place.mouse_out();});this.map.addOverlay(this.marker());}});Object.extend(MarkerReal.prototype,MarkerShared);Object.extend(MarkerCondoBuilding.prototype,MarkerShared);Object.extend(MarkerReal.prototype,MarkerTooltip);Object.extend(MarkerCondoBuilding.prototype,MarkerTooltip);Object.extend(MarkerReal.prototype,{saved_icon:function(){return icon_saved.image;},not_saved_icon:function(){return icon.image;},make_marker:function(){if(this.lot.data.saved){this._marker=new GMarker(new GLatLng(this.lot.data.y,this.lot.data.x),icon_saved);}else{this._marker=new GMarker(new GLatLng(this.lot.data.y,this.lot.data.x),icon);};this.add_listeners();this.map.addOverlay(this.marker());},marker:function(){return this._marker;},open_bubble:function(data){var bubbleHeight=195;if(Estately.partner.get('name')==='sutton'){bubbleHeight=225;}
var infoTabs=[new GInfoWindowTab("Property",'<div id="bubble_property_'+this.lot.id+'" class="bubble bubble_'+this.lot.data.mls_acronym+'" style="height:'+bubbleHeight+'px;width:320px"><div class="loading_bubble">Loading property information</div></div>')];this.marker().openInfoWindowTabsHtml(infoTabs);new Ajax.Request('/map/bubble/'+this.lot.id,{method:'get',onSuccess:this.set_bubble.bind(this),onFailure:bubble_error});}});Object.extend(MarkerCondoBuilding.prototype,{saved:function(){var saved_now=false;var f=function(res,cur){return(res||this.manager.property(cur).data.saved);};return this.condos.inject(false,f.bind(this));},saved_icon:function(){return cicon_saved.image;},not_saved_icon:function(){return cicon.image;},make_marker:function(){if(this.saved()){this._marker=new GMarker(new GLatLng(this.lot.data.y,this.lot.data.x),cicon_saved);}else{this._marker=new GMarker(new GLatLng(this.lot.data.y,this.lot.data.x),cicon);};this.add_listeners();this.map.addOverlay(this.marker());},open_bubble:function(data,lot){this.lot=lot;var bubbleHeight=195;if(Estately.partner.get('name')==='sutton'){bubbleHeight=225;}
var infoTabs=[new GInfoWindowTab("Property",'<div id="bubble_property_'+this.lot.id+'" class="bubble bubble_'+this.lot.data.mls_acronym+'" style="height:'+bubbleHeight+'px;width:320px"><div class="loading_bubble">Loading property information</div></div>')];this.marker().openInfoWindowTabsHtml(infoTabs);new Ajax.Request('/map/bubble/'+this.lot.id,{method:'get',onSuccess:this.set_bubble.bind(this),onFailure:bubble_error});}});function setupTooltip(map){tooltip=document.createElement("div");map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);tooltip.style.visibility="hidden";highlight=document.createElement("div");map.getPane(G_MAP_MARKER_SHADOW_PANE).appendChild(highlight);highlight.style.visibility="hidden";highlight.innerHTML='<img src="/images/glow.png" class="png" alt="" />';};function bubble_error(){alert(Content.bubble_error_txt);map.closeInfoWindow();};var icon=new GIcon();if(Estately.partner.get('name')==='sutton'){icon.image="/images/partners/sutton/map/marker_house.png";}
else{icon.image="/images/house.png";}
icon.shadow="/images/shadow.png";icon.iconSize=new GSize(27,32);icon.shadowSize=new GSize(33,30);icon.iconAnchor=new GPoint(10,32);icon.infoWindowAnchor=new GPoint(13,6);var cicon=new GIcon();if(Estately.partner.get('name')==='sutton'){cicon.image="/images/partners/sutton/map/marker_condo.png";}
else{cicon.image="/images/condo.png";}
cicon.shadow="/images/shadow.png";cicon.iconSize=new GSize(27,32);cicon.shadowSize=new GSize(33,30);cicon.iconAnchor=new GPoint(10,32);cicon.infoWindowAnchor=new GPoint(13,6);var icon_saved=new GIcon();if(Estately.partner.get('name')==='sutton'){icon_saved.image="/images/partners/sutton/map/marker_house_saved.png";}
else{icon_saved.image="/images/house_saved.png";}
icon_saved.shadow="/images/shadow_saved.png";icon_saved.iconSize=new GSize(27,32);icon_saved.shadowSize=new GSize(33,32);icon_saved.iconAnchor=new GPoint(10,32);icon_saved.infoWindowAnchor=new GPoint(13,15);var cicon_saved=new GIcon();if(Estately.partner.get('name')==='sutton'){cicon_saved.image="/images/partners/sutton/map/marker_condo_saved.png";}
else{cicon_saved.image="/images/condo_saved.png";}
cicon_saved.shadow="/images/shadow_saved.png";cicon_saved.iconSize=new GSize(27,32);cicon_saved.shadowSize=new GSize(33,32);cicon_saved.iconAnchor=new GPoint(10,32);cicon_saved.infoWindowAnchor=new GPoint(13,15);var arrow=new GIcon();arrow.image="/images/icons/arrow.png";arrow.shadow="/images/icons/arrowshadow.png";arrow.iconSize=new GSize(39,34);arrow.shadowSize=new GSize(39,34);arrow.iconAnchor=new GPoint(12,34);arrow.infoWindowAnchor=new GPoint(12,20);var AllowUpdate=1;var map;var current_lots;var search_options={};function Lots(){this._marker_manager=new MarkerManager(map,{use_tabs:true});this.empty();};Lots.prototype={do_map_drag:function(){var bounds=mapBounds();if(!(bounds.minX<=this.place.x&&bounds.maxX>=this.place.x&&bounds.minY<=this.place.y&&bounds.maxY>=this.place.y)){this.place=false;}},place:false,required_property:0,current_polygons:false,require_property:function(id){this.required_property=id;this.switch_focus(id);},has_required_property:function(){if(this.required_property){return true;}
return false;},add_place_marker:function(place){this.place=place;new MarkerPlace(place,map);},add_polygons:function(polygons){if(this.current_polygons){this.remove_polygon_overlays();};this.current_polygons=polygons;},display_polygons:function(){for(var index=0,len=this.current_polygons.length;index<len;++index){map.addOverlay(this.current_polygons[index]);};},remove_polygon_overlays:function(){if(this.current_polygons){for(var index=0,len=this.current_polygons.length;index<len;++index){map.removeOverlay(this.current_polygons[index]);}}},remove_polygons:function(){if(this.current_polygons){this.remove_polygon_overlays();}
this.current_polygons=null;update_poly_search('');},refresh_polygons:function(){this.remove_polygon_overlays();if(this.current_polygons){this.display_polygons(this.current_polygons);}},remove_property:function(id){var property=this._marker_manager.property(id);property.remove();},empty:function(){this._marker_manager.empty();map.clearOverlays();},add_lots:function(incoming_lots,condo_buildings,id){var building=null;this.unselect();$('search_results').removeClassName('loading');$('search_results_header').removeClassName('waiting').addClassName('done');if(!PageUpdater.is_current_id(id)){return false;}
PageUpdater.set_default('gmap');this.empty();this._marker_manager.add_new_lots(incoming_lots,condo_buildings,{add_to_list:true,list_id:'results_wrapper',class_suffixes:[""," alt"]});if(this.place){new MarkerPlace(this.place,map);}
if(this.has_required_property()){this.switch_focus(this.required_property);this.open_selected();this.required_property=0;}
this.refresh_polygons();tabs.do_map_event('after_update');resizePage.resizeSearch(false);new Ajax.Request('/map/update_stats',{parameters:getQuery({page:'1'}),onFailure:function(){PageUpdater.set_default('gmap');}});},has_property:function(id){return this._marker_manager.has_property(id);},property:function(id){return this._marker_manager.property(id);},is_selected:function(id){return this._marker_manager.is_selected(id);},has_selected_property:function(id){return this._marker_manager.has_selected_property(id);},selected_property:function(){return this._marker_manager.selected_property();},open_selected:function(){if(current_lots.has_selected_property()&&current_lots.selected_property().has_marker()){if(current_lots.selected_property().on_map()){current_lots.selected_property().open_bubble();}}
else{EstatelyLog('no marker, so no bubble');}},switch_focus:function(id){this._marker_manager.switch_focus(id);},unselect:function(){this.switch_focus(0);},selected_id:function(){return this._marker_manager.selected_id;}};function toggleSavedHomeFilter(no_update){var filterControl=$('toggle_saved_props');if(filterControl.value===true){filterControl.selectedIndex=0;}else{filterControl.selectedIndex=1;}
if(!no_update){update_map();}}
window.transit_search_timer=false;function transit_search_observer(){field=$('transit_stops');if(window.transit_search_timer)window.clearTimeout(window.transit_search_timer);if(!field.disabled)window.transit_search_timer=window.setTimeout("form_observer(field);",900);};window.full_text_timer=false;function full_text_observer(){field=$('full_text');if(window.full_text_timer){window.clearTimeout(window.full_text_timer);}
if(!field.disabled){window.full_text_timer=window.setTimeout("form_observer(field);",900);}}
function form_observer(field){var fieldLabel=$(field).previous('label').innerHTML.replace(':','');if(field.selectedIndex!==undefined){var eventLabel=field[field.selectedIndex].innerHTML;}else{var eventLabel=field.getValue();}
EstatelyEvent('Map - Search Filters','Set: '+fieldLabel+' - '+field.id,eventLabel);if(field.value>=0&&field.type!='text'&&field.className!='no_min_max'){vals=field.id.split('_');var min_max=vals[0];vals.shift();vals=vals.join('_');var min_value=parseInt($('min_'+vals).value,10);var max_value=parseInt($('max_'+vals).value,10);if(min_max=='min'){if((min_value>max_value)&&(max_value>=0)){$('max_'+vals).selectedIndex=0;};}
else if(min_max=='max'){if((max_value<min_value)&&(min_value>=0)){$('min_'+vals).selectedIndex=0;};};}
update_map();}
function update_map(page){if(AllowUpdate>0){var results_container=$('search_results');$('search_results').addClassName('loading');$('search_results_header').removeClassName('done').addClassName('waiting');$('results_wrapper').update();updateMapCenter();PageUpdater.set_loading('gmap');var query=getQuery({page:page});query['ajax_id']=PageUpdater.get_id();new Ajax.Request('/map/update',{parameters:query,onFailure:function(){alert(Content.search_error_txt);PageUpdater.set_default('gmap');}});}
else{EstatelyLog('AllowUpdate is off!');};}
function do_without_map_update(f){try{AllowUpdate-=1;EstatelyLog('in do_without_map_update, AllowUpdate is: '+AllowUpdate);f();AllowUpdate+=1;}
catch(e){EstatelyLog('error: '+e.toString());AllowUpdate+=1;throw e;};}
function getQuery(opts){var bounds=mapBounds();var query=$('search_filters').serialize(true);query['min_x']=bounds.minX;query['max_x']=bounds.maxX;query['min_y']=bounds.minY;query['max_y']=bounds.maxY;query['order']=$('order_by').value;query['location']=$('search_location').value;query['location_buffer']=$('place_search_buffer').value;;if(opts.page)query['page']=opts.page;query['search_poly']=$('search_poly').value;var req_prop=current_lots.has_required_property();if(current_lots.has_required_property()){query['required_property']=current_lots.required_property;}
return query;}
function update_poly_search(str){$('search_poly').value=str;}
function onMap(point){var bounds=mapBounds();if(bounds.minX<=point.x&&bounds.maxX>=point.x&&bounds.minY<=point.y&&bounds.maxY>=point.y){return true;};return false;}
function mapBounds(){var bounds=map.getBounds();var min_x=bounds.getSouthWest();min_x=min_x.lng();var min_y=bounds.getSouthWest();min_y=min_y.lat();var max_x=bounds.getNorthEast();max_x=max_x.lng();var max_y=bounds.getNorthEast();max_y=max_y.lat();return{minX:min_x,maxX:max_x,minY:min_y,maxY:max_y};}
function updateMapCenter(){var bounds=mapBounds();var width=bounds.maxX-bounds.minX;var height=bounds.maxY-bounds.minY;map.queryCenter=map.getCenter();map.maxY=bounds.maxY+height*0.2;map.maxX=bounds.maxX+width*0.2;map.minY=bounds.minY-height*0.2;map.minX=bounds.minX-width*0.2;}
function reportBug(msg,url,line){new Ajax.Request('/map/javascript_error',{method:'get',parameters:{msg:msg,error_url:url,line:line}});}
function current_page(){var page=1;var current_page_span=$$('.results_pager .current')[0];if(current_page_span){page=current_page_span.innerHTML;}
return page;}
var ZillowLogo={logo:null,add:function(){if(this.logo!=null){return false;}
this.logo=new ZL();map.addControl(this.logo);}};ZL=function(){};ZL.prototype=new GControl();ZL.prototype.initialize=function(map){var container=document.createElement('div');container.innerHTML='<a href="http://www.zillow.com/" rel="nofollow" style="background:none;padding:0;margin:0;outline:0;" target="_blank"><img src="/images/logos/zillow_neighborhoods.gif" /></a>';map.getContainer().appendChild(container);return container;};ZL.prototype.getDefaultPosition=function(){return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT,new GSize(73,21));};function infoWindowOpen(){moveEnd.opening_window=true;}
moveEnd.opening_window=false;function moveEnd(){if(!moveEnd.opening_window){dragEnd();}
moveEnd.opening_window=false;}
function dragEnd(){current_lots.do_map_drag();var bounds=mapBounds();if(!(bounds.minX>=map.minX&&bounds.maxX<=map.maxX&&bounds.minY>=map.minY&&bounds.maxY<=map.maxY)){current_lots.unselect();update_map();}}
function onunLoad(){GUnload();}
function toggle_search_option(id){Element.hide(id);}
function edit_saved_search_name(id){Element.hide('search_name_'+id);Element.show('search_name_'+id+'_edit');}
function cancel_saved_search_edit(id){Element.hide('search_name_'+id+'_edit');Element.show('search_name_'+id);}
function toggle_star(dont_update){var field=$('toggle_saved_props');if(field.selectedIndex==0){field.selectedIndex=1;}
else{field.selectedIndex=0;}
if(!dont_update){update_map();}}
function moveMapElements(){var gmLogo=$('gmap').select('img[src*="poweredby.png"]');var gmZoom=$('gmap').select('div[title*="zoom"]');var gmScale=$('gmap').select('#gmap_magnifyingglass');if(!!gmLogo.length&&!!gmScale.length&&!!gmZoom.length){gmLogo[0].up('div').setStyle({left:'',right:'2px',bottom:'10px'});gmZoom[0].up('.gmnoprint').setStyle('top: 35px');gmScale[0].previous().setStyle({left:'',right:'4px',bottom:'54px'});}else{if(typeof(i)==='undefined'){var i=1;}
else if(++i==10){return false;}
moveMapElements.delay(.25);}}
function update_order_by(val,user){change_order_by(val,user);update_map();}
function change_order_by(val,user){var order=null;if(update_order_by.current==val){if(update_order_by.order=='asc'){order='desc';}
else{order='asc';}}else{if($('sort_'+update_order_by.current)){set_order_img(update_order_by.current,'');};order='asc';}
set_order_img(val,order,user);update_order_by.current=val;update_order_by.order=order;$('order_by').value=val+'_'+update_order_by.order;}
function set_order_img(type,order,user){if(order=='desc'){$('sort_'+type).removeClassName('ascending').addClassName('descending');}
else if(order=='asc'){$('sort_'+type).removeClassName('descending').addClassName('ascending');}
else{$('sort_'+type).removeClassName('ascending').removeClassName('descending');}
if(user===true){EstatelyEvent('Map - Search Results','Sort: '+type,order);}}
function clear_search_options(){children=$A($('search_boxes').childNodes);var f=function gimmee(div){if(div.id&&div.id.indexOf('search_')!=-1&&div.style.display!='none'){remove_search_option(div.id);}}
children.each(f);}
function search_option_check(option){var activate_search=false;children=$A($(option).childNodes);var f=function gimme(each_option){if(each_option.options){if(parseInt(each_option.value,10)>=0){activate_search=true;}}}
children.each(f);if(activate_search){update_map();}}
function change_search_option(select,new_value){var drop_down=$(select);drop_down[drop_down.length-1].value=new_value;}
function reset_search_item(el){el=$('el');switch(ele.type.toLowerCase()){case'select-one':if(ele.id=='toggle_saved_props'){toggle_star(true);}
else{ele.selectedIndex=0;}
break;case'text':ele.value='';break;case'hidden':ele.value=''
break;case'radio':if(ele.value=='both'&&ele.name=='property_type'){ele.checked=true;}
break;}}
function update_search(options){var f=function(){current_lots.unselect();map.closeInfoWindow();EstatelyLog('starting the search setup in tab: '+tabs.get_tab());if(options.location&&options.location!=''){set_location_search(options.location,{buffer:options.location_buffer});location_search(false,{skip_open_map:true});}
else if(options.max_x&&options.max_y&&options.min_x&&options.min_y){var zoom=12;EstatelyLog(options.max_x+', '+options.max_y+', '+options.min_x+', '+options.min_y);var center=new GLatLng((parseFloat(options.max_y)+parseFloat(options.min_y))/2,(parseFloat(options.max_x)+parseFloat(options.min_x))/2);var bounds=new GLatLngBounds();bounds.extend(new GLatLng(options.max_y,options.max_x));bounds.extend(new GLatLng(options.min_y,options.min_x));var zoom=map.getBoundsZoomLevel(bounds);map.setCenter(center,zoom);}
else{EstatelyLog('PROBLEM WITH SAVED SEARCH - not moving the map!');};if(options.search_order){clear_search_options();new_search_options=$A(options.search_order.split(','));new_search_options.each(function(option){$('hidden_search_subjects').value='search_'+option;add_search_option();});}else{EstatelyLog('No search_order!');};var elements=Form.getElements(document.search_form);for(var i=0;i<elements.length;i++){if(options[elements[i].name]){if(elements[i].type=='radio'){if(elements[i].value==options[elements[i].name]){elements[i].checked=true;};}else{elements[i].value=options[elements[i].name];};};};};var ff=function(){EstatelyLog('doing search!');do_without_map_update(f);update_map();};show_map({after_open:ff});};var TransitSearch={labelElementId:'transit_stops_label',inputElementId:'transit_stops',showPopup:function(){this.popupDiv.setStyle('top:200px;right:300px');this.fetchRoutes();Element.show(this.popupDiv);},hidePopup:function(){Element.hide(this.popupDiv);},getSelectedRoutes:function(){var value=$F(this.inputElementId);return(value=='')?[]:value.split(',');},setSelectedRoutes:function(newRoutes){if(newRoutes){newRoutes=newRoutes.map(function(route){return route.strip();}).reject(function(route){return(route.length==0);});}else{newRoutes=[];}
var oldRoutes=this.getSelectedRoutes();$(this.inputElementId).value=newRoutes.join(',');var selectedRoutes=this.getSelectedRoutes();if(!selectedRoutes||!selectedRoutes.length){$(this.labelElementId).update('<a href="#" rel="nofollow" onclick="TransitSearch.showPopup(); return false;">(Select Transit)</a>');$(this.inputElementId).value='';}else{var hasRail=!!selectedRoutes.find(function(x){return!x.match(/^\d*$/);});var hasBus=!!selectedRoutes.find(function(x){return!!x.match(/^\d*$/);});if(hasRail&&hasBus){$(this.labelElementId).innerHTML='<a href="#" rel="nofollow" onclick="TransitSearch.showPopup(); return false;">Trains/Busses</a>';}else if(hasRail&&!hasBus){$(this.labelElementId).innerHTML='<a href="#" rel="nofollow" onclick="TransitSearch.showPopup(); return false;">Train Stations</a>';}else{$(this.labelElementId).innerHTML='<a href="#" rel="nofollow" onclick="TransitSearch.showPopup(); return false;">Bus Stops</a>';}}},fetchRoutes:function(){this.popupContentDiv.update('<div class="loading_routes">Searching for nearby transit...</div>');var params={map_bounds:Object.toJSON(mapBounds())};var selectedRoutes=this.getSelectedRoutes();if(selectedRoutes!=null){if(selectedRoutes.length>0){params['selected_routes[]']=selectedRoutes;}else{params['selected_routes[]']='';}}
new Ajax.Updater(this.popupContentDiv,'/map/transit_routes',{parameters:params});},formOnSubmit:function(selectedLines){var busRoutes=selectedLines['bus_routes'];selectedLines=Object.keys(selectedLines);selectedLines.remove('bus_routes');busRoutes.split(',').each(function(busRoute){selectedLines.push(busRoute.strip());});this.setSelectedRoutes(selectedLines);this.hidePopup();},init:function(initialSelectedRoutes){this.setSelectedRoutes(initialSelectedRoutes);var closeButton=new Element('div',{'class':'close_button'});Event.observe(closeButton,'click',function(){this.hidePopup();}.bindAsEventListener(this));this.popupDiv=new Element('div',{style:'right: 0px; top: 0px; display: none;','class':'transit_popbox'});this.popupDiv.appendChild(closeButton);this.popupContentDiv=new Element('div',{style:'width: 200px; padding-top:10px'});this.popupDiv.appendChild(this.popupContentDiv);document.body.appendChild(this.popupDiv);}}
Event.observe(window,'load',function(){if(!$('transit_stops')){return false;}
if(initial_transit_stops!=null){TransitSearch.init(initial_transit_stops.split(','));}else{TransitSearch.init(null);}})
if(typeof(Control)=='undefined')
var Control={};Control.Tabs=Class.create();Object.extend(Control.Tabs,{instances:[],findByTabId:function(id){return Control.Tabs.instances.find(function(tab){return tab.links.find(function(link){return link.key==id;});});}});Object.extend(Control.Tabs.prototype,{initialize:function(tab_list_container,options){this.activeContainer=false;this.activeLink=false;this.containers=$H({});this.links=[];Control.Tabs.instances.push(this);this.options={beforeChange:Prototype.emptyFunction,afterChange:Prototype.emptyFunction,hover:false,linkSelector:'li a',setClassOnContainer:false,activeClassName:'active',defaultTab:'first',autoLinkExternal:true,targetRegExp:/#(.+)$/,showFunction:Element.show,hideFunction:Element.hide};Object.extend(this.options,options||{});(typeof(this.options.linkSelector=='string')?$(tab_list_container).getElementsBySelector(this.options.linkSelector):this.options.linkSelector($(tab_list_container))).findAll(function(link){return(/^#/).exec(link.href.replace(window.location.href.split('#')[0],''));}).each(function(link){this.addTab(link);}.bind(this));this.containers.values().each(Element.hide);if(this.options.defaultTab=='first')
this.setActiveTab(this.links.first());else if(this.options.defaultTab=='last')
this.setActiveTab(this.links.last());else
this.setActiveTab(this.options.defaultTab);var targets=this.options.targetRegExp.exec(window.location);if(targets&&targets[1]){targets[1].split(',').each(function(target){this.links.each(function(target,link){if(link.key==target){this.setActiveTab(link);throw $break;}}.bind(this,target));}.bind(this));}
if(this.options.autoLinkExternal){$A(document.getElementsByTagName('a')).each(function(a){if(!this.links.include(a)){var clean_href=a.href.replace(window.location.href.split('#')[0],'');if(clean_href.substring(0,1)=='#'){if(this.containers.keys().include(clean_href.substring(1))){$(a).observe('click',function(event,clean_href){this.setActiveTab(clean_href.substring(1));}.bindAsEventListener(this,clean_href));}}}}.bind(this));}},addTab:function(link){this.links.push(link);link.key=link.getAttribute('href').replace(window.location.href.split('#')[0],'').split('/').last().replace(/#/,'');this.containers[link.key]=$(link.key);link[this.options.hover?'onmouseover':'onclick']=function(link){if(window.event)
Event.stop(window.event);this.setActiveTab(link);return false;}.bind(this,link);},setActiveTab:function(link){if(!link)
return;if(typeof(link)=='string'){this.links.each(function(_link){if(_link.key==link){this.setActiveTab(_link);throw $break;}}.bind(this));}else{this.notify('beforeChange',this.activeContainer);if(this.activeContainer)
this.options.hideFunction(this.activeContainer);this.links.each(function(item){(this.options.setClassOnContainer?$(item.parentNode):item).removeClassName(this.options.activeClassName);}.bind(this));(this.options.setClassOnContainer?$(link.parentNode):link).addClassName(this.options.activeClassName);this.activeContainer=this.containers[link.key];this.activeLink=link;this.options.showFunction(this.containers[link.key]);this.notify('afterChange',this.containers[link.key]);}},next:function(){this.links.each(function(link,i){if(this.activeLink==link&&this.links[i+1]){this.setActiveTab(this.links[i+1]);throw $break;}}.bind(this));return false;},previous:function(){this.links.each(function(link,i){if(this.activeLink==link&&this.links[i-1]){this.setActiveTab(this.links[i-1]);throw $break;}}.bind(this));return false;},first:function(){this.setActiveTab(this.links.first());return false;},last:function(){this.setActiveTab(this.links.last());return false;},notify:function(event_name){try{if(this.options[event_name])
return[this.options[event_name].apply(this.options[event_name],$A(arguments).slice(1))];}catch(e){if(e!=$break)
throw e;else
return false;}}});if(typeof(Object.Event)!='undefined')
Object.Event.extend(Control.Tabs);function addInfoWindowToMarker(marker,info,options){GEvent.addListener(marker,"click",function(){marker.openInfoWindowHtml(info,options);});return marker;}
function addInfoWindowTabsToMarker(marker,info,options){GEvent.addListener(marker,"click",function(){marker.openInfoWindowTabsHtml(info,options);});return marker;}
function addPropertiesToLayer(layer,getTile,copyright,opacity,isPng){layer.getTileUrl=getTile;layer.getCopyright=copyright;layer.getOpacity=opacity;layer.isPng=isPng;return layer;}
function addOptionsToIcon(icon,options){for(var k in options){icon[k]=options[k];}
return icon;}
function addCodeToFunction(func,code){if(func==undefined)
return code;else{return function(){func();code();}}}
function addGeocodingToMarker(marker,address){marker.orig_initialize=marker.initialize;orig_redraw=marker.redraw;marker.redraw=function(force){};marker.initialize=function(map){new GClientGeocoder().getLatLng(address,function(latlng){if(latlng){marker.redraw=orig_redraw;marker.orig_initialize(map);marker.setPoint(latlng);}});};return marker;}
GMap2.prototype.centerAndZoomOnMarkers=function(markers){var bounds=new GLatLngBounds(markers[0].getPoint(),markers[0].getPoint());for(var i=1,len=markers.length;i<len;i++){bounds.extend(markers[i].getPoint());}
this.centerAndZoomOnBounds(bounds);}
GMap2.prototype.centerAndZoomOnPoints=function(points){var bounds=new GLatLngBounds(points[0],points[0]);for(var i=1,len=points.length;i<len;i++){bounds.extend(points[i]);}
this.centerAndZoomOnBounds(bounds);}
GMap2.prototype.centerAndZoomOnBounds=function(bounds){var center=bounds.getCenter();this.setCenter(center,this.getBoundsZoomLevel(bounds));}
function setWindowDims(elem){if(window.innerWidth){elem.style.height=(window.innerHeight)+'px;';elem.style.width=(window.innerWidth)+'px;';}else if(document.body.clientWidth){elem.style.width=(document.body.clientWidth)+'px';elem.style.height=(document.body.clientHeight)+'px';}}
ManagedMarker=function(markers,minZoom,maxZoom){this.markers=markers;this.minZoom=minZoom;this.maxZoom=maxZoom;}
function addMarkersToManager(manager,managedMarkers){for(var i=0,length=managedMarkers.length;i<length;i++){mm=managedMarkers[i];manager.addMarkers(mm.markers,mm.minZoom,mm.maxZoom);}
manager.refresh();return manager;}
var INVISIBLE=new GLatLng(0,0);window.onunload=GUnload;function build_place_map(data){var points=data.points;for(var i=0,len=points.length;i<len;i++){points[i]=new GLatLng(points[i].y,points[i].x);}
var bounds=new GLatLngBounds(points[0],points[0]);for(var i=1,len=points.length;i<len;i++){bounds.extend(points[i]);}
var center=bounds.getCenter();place_map=new GMap2(document.getElementById("place_map"));place_map.setCenter(center,place_map.getBoundsZoomLevel(bounds));place_map.addControl(new GLargeMapControl());place_map.addControl(new GMapTypeControl());for(var j=0,len=data.polygons.length;j<len;j++){place_map.addOverlay(data.polygons[j]);}}
function bindMapAndLink(marker,link_id,mouseover_image,mouseout_image)
{var mouseOverFunc=function(){if($(link_id)){$(link_id).addClassName('highlight');}
marker.setImage(mouseover_image)};var mouseOutFunc=function(){if($(link_id)){$(link_id).removeClassName('highlight');}
marker.setImage(mouseout_image);};if(link_id){$(link_id).onmouseover=mouseOverFunc;$(link_id).onmouseout=mouseOutFunc;}
GEvent.addListener(marker,'mouseover',mouseOverFunc);GEvent.addListener(marker,'mouseout',mouseOutFunc);}
function add_place_to_map(place_name,point,map,icon,link_id,hover_image,normal_image){var marker=new GMarker(new GLatLng(point.y,point.x),{title:place_name,icon:icon});map.addOverlay(addInfoWindowToMarker(marker,place_name));if(link_id){bindMapAndLink(marker,link_id,hover_image,normal_image)}}
var DetailsPageMap={setupMap:function(propType,houseX,houseY,schools,parks,places,stops){var housePoint=new GLatLng(houseY,houseX);var baseIcon=new GIcon();baseIcon.shadow="/images/markers/shadow_square.png";baseIcon.iconSize=new GSize(36,38);baseIcon.shadowSize=new GSize(47,38);baseIcon.iconAnchor=new GPoint(18,28);baseIcon.infoWindowAnchor=new GPoint(17,12);baseIcon.infoShadowAnchor=new GPoint(17,12);var map=new GMap2($('neighborhood_map'));map.setCenter(housePoint,13);map.addControl(new GSmallMapControl());map.addControl(new GMapTypeControl());GEvent.addListener(map,'click',function(marker){if(marker!=null&&marker._tabName!=null){swapHoodTab(marker._tabName);}});var houseMarker;if(propType=='CondProperty')
houseMarker=new GMarker(housePoint,{'icon':cicon});else
houseMarker=new GMarker(housePoint,{'icon':icon});map.addOverlay(houseMarker);var schoolMarkers=[];var parkMarkers=[];var transitMarkers=[];var placeMarkers=[];var markerMap=$A([[schools,schoolMarkers,'hoodSchools'],[parks,parkMarkers,'hoodParks'],[places,placeMarkers,'hoodPlaces'],[stops,transitMarkers,'hoodTransit']]);markerMap.each(function(x){var markerInfos=x[0];var markerArray=x[1];var tabName=x[2];$A(markerInfos).each(function(markerInfo){var icon=new GIcon(baseIcon);icon.image=markerInfo.icon;var opts={title:markerInfo.name,'icon':icon};var marker=new GMarker(new GLatLng(markerInfo.y,markerInfo.x),opts);markerArray.push(marker);map.addOverlay(marker);marker._tabName=tabName;var infoWindowContent='<div class="info_bubble">'+$(markerInfo.link_id).up("p").innerHTML+'</div>';bindMapAndLink(marker,$(markerInfo.link_id),markerInfo.hover_icon,markerInfo.icon);addInfoWindowToMarker(marker,infoWindowContent);$(markerInfo.link_id).onclick=function(){marker.openInfoWindowHtml(infoWindowContent);return false;};});});$('toggleSchoolMarkers').observe('click',function(e){schoolMarkers.each(function(marker){e.target.checked?marker.show():marker.hide();});});$('toggleParkMarkers').observe('click',function(e){parkMarkers.each(function(marker){e.target.checked?marker.show():marker.hide();});});$('toggleTransitMarkers').observe('click',function(e){transitMarkers.each(function(marker){e.target.checked?marker.show():marker.hide();});});$('togglePlaceMarkers').observe('click',function(e){placeMarkers.each(function(marker){e.target.checked?marker.show():marker.hide();});});}}
function MortgageDisplay(principal,interest_rate){this.maximum_interest_rate=0.10;this.maximum_percentage_down=1.00;this.years_options=[5,10,30];this.maximumPayment=maximumPayment;this.buildSliders=buildSliders;this.createRadioButtonsInside=createRadioButtonsInside;this.changeMortgageYears=changeMortgageYears;this.changeMortgageInterestRate=changeMortgageInterestRate;this.changeMortgageDownpaymentPercentage=changeMortgageDownpaymentPercentage;this.changeMortgagePayment=changeMortgagePayment;this.changeMortgageDownpayment=changeMortgageDownpayment;this.setMortgageFromCookie=setMortgageFromCookie;this.registerListenersForInputs=registerListenersForInputs;this.updateSliders=updateSliders;window.mortgage_box=this;this.mortgage=new Mortgage();this.mortgage.principal=principal;this.mortgage.interest_rate=interest_rate;this.setMortgageFromCookie();this.buildSliders();this.createRadioButtonsInside($('year_buttons'));this.updateSliders();this.registerListenersForInputs();}
function setMortgageFromCookie(){if(getCookie('mortgage_years'))
this.mortgage.years=getCookie('mortgage_years');if(getCookie('mortgage_interest_rate'))
this.mortgage.interest_rate=getCookie('mortgage_interest_rate');if(getCookie('mortgage_downpayment'))
this.mortgage.setDownpayment(getCookie('mortgage_downpayment'));}
function changeMortgageYears(value){if(value){this.mortgage.years=value;setCookie('mortgage_years',value);this.updateSliders();}}
function changeMortgageInterestRate(value){if(value!=this.mortgage.interest_rate){this.mortgage.interest_rate=value;setCookie('mortgage_interest_rate',value);this.updateSliders();}}
function changeMortgageDownpaymentPercentage(value){if(value!=this.mortgage.downpayment_percentage){this.mortgage.downpayment_percentage=value;setCookie('mortgage_downpayment',this.mortgage.downpayment());this.updateSliders();}}
function changeMortgageDownpayment(value){if(value!=this.mortgage.downpayment()){this.mortgage.setDownpayment(value);setCookie('mortgage_downpayment',this.mortgage.downpayment());this.updateSliders();}}
function changeMortgagePayment(value){if(value!=this.mortgage.payment()){this.mortgage.setDownpaymentPercentageToAchievePayment(value);this.updateSliders();}}
function buildSliders(){this.interest_rate_slider=new Control.Slider('interest_rate_slider_handle','interest_rate_slider_track',{range:$R(0.00001,this.maximum_interest_rate),onChange:function(event){window.mortgage_box.changeMortgageInterestRate(event);},onSlide:function(event){$('interest_rate_input').focus();window.mortgage_box.changeMortgageInterestRate(event);}});var downpayment_percentage_slider_values=[];for(i=0;i<this.mortgage.principal/1000;i++)
downpayment_percentage_slider_values[i]=i*1000/this.mortgage.principal;downpayment_percentage_slider_values[i]=1.00;this.downpayment_percentage_slider=new Control.Slider('downpayment_percentage_slider_handle','downpayment_percentage_slider_track',{values:downpayment_percentage_slider_values,onChange:function(event){window.mortgage_box.changeMortgageDownpaymentPercentage(event);},onSlide:function(event){$('downpayment_input').focus();window.mortgage_box.changeMortgageDownpaymentPercentage(event);}});this.payment_slider=new Control.Slider('payment_slider_handle','payment_slider_track',{range:$R(0,this.maximumPayment()),onChange:function(event){window.mortgage_box.changeMortgagePayment(event);},onSlide:function(event){$('payment_input').focus();window.mortgage_box.changeMortgagePayment(event);}});}
function maximumPayment(){var maximum_payment_mortgage=new Mortgage();maximum_payment_mortgage.principal=this.mortgage.principal;maximum_payment_mortgage.years=this.mortgage.years;maximum_payment_mortgage.interest_rate=this.maximum_interest_rate;maximum_payment_mortgage.downpayment_percentage=0;return(maximum_payment_mortgage.payment());}
function createRadioButtonsInside(parent_element){for(i=0;i<this.years_options.length;i++){var button=document.createElement('input');button.setAttribute('type','radio');button.setAttribute('name','years_input');button.setAttribute('id','years_input_'+i);button.setAttribute('value',this.years_options[i]);var label=document.createElement('label');label.setAttribute('for','years_input_'+i);var text=document.createTextNode(this.years_options[i]+' years ');label.appendChild(button);label.appendChild(text);parent_element.appendChild(label);}}
function registerListenersForInputs(){for(i=0;i<this.years_options.length;i++){$('years_input_'+i).observe('click',function(event){window.mortgage_box.changeMortgageYears(event.target.value);});}
$('mortgage_form').observe('submit',function(event){event.stop();});var pause=1000;$('interest_rate_input').observe('keyup',function(event){window.setTimeout(function(){window.mortgage_box.changeMortgageInterestRate(complexParseFloat($('interest_rate_input').value)/100);},pause);});$('downpayment_input').observe('keyup',function(event){window.setTimeout(function(){window.mortgage_box.changeMortgageDownpayment(complexParseFloat($('downpayment_input').value));},pause);});$('payment_input').observe('keyup',function(event){window.setTimeout(function(){window.mortgage_box.changeMortgagePayment(complexParseFloat($('payment_input').value));},pause);});$('interest_rate_input').observe('keydown',function(event){if(event.keyCode==38)
window.mortgage_box.changeMortgageInterestRate(window.mortgage_box.mortgage.interest_rate+0.001);else if(event.keyCode==40)
window.mortgage_box.changeMortgageInterestRate(window.mortgage_box.mortgage.interest_rate-0.001);});$('downpayment_input').observe('keydown',function(event){if(event.keyCode==38)
window.mortgage_box.changeMortgageDownpayment(window.mortgage_box.mortgage.downpayment()+1000);else if(event.keyCode==40)
window.mortgage_box.changeMortgageDownpayment(window.mortgage_box.mortgage.downpayment()-1000);});$('payment_input').observe('keydown',function(event){if(event.keyCode==38)
window.mortgage_box.changeMortgagePayment(window.mortgage_box.mortgage.payment()+100);else if(event.keyCode==40)
window.mortgage_box.changeMortgagePayment(window.mortgage_box.mortgage.payment()-100);});}
function updateSliders(){this.payment_slider.range=$R(0,this.maximumPayment());for(i=0;i<this.years_options.length;i++)
if(this.years_options[i]==this.mortgage.years)
$('years_input_'+i).checked=true;if(this.mortgage.downpayment_percentage<0)
this.mortgage.downpayment_percentage=0;if(this.mortgage.interest_rate!=this.interest_rate_slider.value)
this.interest_rate_slider.setValue(this.mortgage.interest_rate);if(this.mortgage.downpayment_percentage!=this.downpayment_percentage_slider.value)
this.downpayment_percentage_slider.setValue(this.mortgage.downpayment_percentage);if(this.mortgage.payment()!=this.payment_slider.value)
this.payment_slider.setValue(this.mortgage.payment());var mortgageHeaderLink=$('mortgage_header_link');if(!!mortgageHeaderLink)
mortgageHeaderLink.innerHTML=number_to_currency(this.mortgage.payment(),0)+' per month';$('interest_rate_input').value=Math.round(this.mortgage.interest_rate*10000)/100;$('downpayment_input').value=number_to_currency(this.mortgage.principal*this.mortgage.downpayment_percentage,0);$('downpayment_percentage_input').innerHTML=Math.round(this.mortgage.downpayment_percentage*100)+'%';$('payment_input').value=number_to_currency(this.mortgage.payment(),0);}
function Mortgage(){this.years=30.0;this.payments_per_year=12.0;this.downpayment_percentage=0.2;this.effectiveInterestRatePerMonth=effectiveInterestRatePerMonth;this.numberOfPayments=numberOfPayments;this.annuityFactor=annuityFactor;this.payment=payment;this.downpayment=downpayment;this.setDownpayment=setDownpayment;this.setDownpaymentPercentageToAchievePayment=setDownpaymentPercentageToAchievePayment;}
function downpayment(){return(this.principal*this.downpayment_percentage);}
function setDownpayment(value){return(this.downpayment_percentage=parseFloat(value)/this.principal);}
function effectiveInterestRatePerMonth(){var x=1+parseFloat(this.interest_rate)/parseFloat(this.payments_per_year);var y=12/parseFloat(this.payments_per_year);var z=Math.pow(x,y)-1;return(z);}
function numberOfPayments(){return(this.years*parseFloat(this.payments_per_year));}
function annuityFactor(){var x=1/(1+this.effectiveInterestRatePerMonth());var y=Math.pow(x,this.numberOfPayments());var z=(1-y)/this.effectiveInterestRatePerMonth();return(z);}
function payment(){var x=this.principal-(this.principal*parseFloat(this.downpayment_percentage));return(x/this.annuityFactor());}
function setDownpaymentPercentageToAchievePayment(value){this.downpayment_percentage=(this.principal-value*this.annuityFactor())/parseFloat(this.principal);}
if(!Control)var Control={};Control.Slider=Class.create({initialize:function(handle,track,options){var slider=this;if(Object.isArray(handle)){this.handles=handle.collect(function(e){return $(e)});}else{this.handles=[$(handle)];}
this.track=$(track);this.options=options||{};this.axis=this.options.axis||'horizontal';this.increment=this.options.increment||1;this.step=parseInt(this.options.step||'1');this.range=this.options.range||$R(0,1);this.value=0;this.values=this.handles.map(function(){return 0});this.spans=this.options.spans?this.options.spans.map(function(s){return $(s)}):false;this.options.startSpan=$(this.options.startSpan||null);this.options.endSpan=$(this.options.endSpan||null);this.restricted=this.options.restricted||false;this.maximum=this.options.maximum||this.range.end;this.minimum=this.options.minimum||this.range.start;this.alignX=parseInt(this.options.alignX||'0');this.alignY=parseInt(this.options.alignY||'0');this.trackLength=this.maximumOffset()-this.minimumOffset();this.handleLength=this.isVertical()?(this.handles[0].offsetHeight!=0?this.handles[0].offsetHeight:this.handles[0].style.height.replace(/px$/,"")):(this.handles[0].offsetWidth!=0?this.handles[0].offsetWidth:this.handles[0].style.width.replace(/px$/,""));this.active=false;this.dragging=false;this.disabled=false;if(this.options.disabled)this.setDisabled();this.allowedValues=this.options.values?this.options.values.sortBy(Prototype.K):false;if(this.allowedValues){this.minimum=this.allowedValues.min();this.maximum=this.allowedValues.max();}
this.eventMouseDown=this.startDrag.bindAsEventListener(this);this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.update.bindAsEventListener(this);this.handles.each(function(h,i){i=slider.handles.length-1-i;slider.setValue(parseFloat((Object.isArray(slider.options.sliderValue)?slider.options.sliderValue[i]:slider.options.sliderValue)||slider.range.start),i);h.makePositioned().observe("mousedown",slider.eventMouseDown);});this.track.observe("mousedown",this.eventMouseDown);document.observe("mouseup",this.eventMouseUp);document.observe("mousemove",this.eventMouseMove);this.initialized=true;},dispose:function(){var slider=this;Event.stopObserving(this.track,"mousedown",this.eventMouseDown);Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);this.handles.each(function(h){Event.stopObserving(h,"mousedown",slider.eventMouseDown);});},setDisabled:function(){this.disabled=true;},setEnabled:function(){this.disabled=false;},getNearestValue:function(value){if(this.allowedValues){if(value>=this.allowedValues.max())return(this.allowedValues.max());if(value<=this.allowedValues.min())return(this.allowedValues.min());var offset=Math.abs(this.allowedValues[0]-value);var newValue=this.allowedValues[0];this.allowedValues.each(function(v){var currentOffset=Math.abs(v-value);if(currentOffset<=offset){newValue=v;offset=currentOffset;}});return newValue;}
if(value>this.range.end)return this.range.end;if(value<this.range.start)return this.range.start;return value;},setValue:function(sliderValue,handleIdx){if(!this.active){this.activeHandleIdx=handleIdx||0;this.activeHandle=this.handles[this.activeHandleIdx];this.updateStyles();}
handleIdx=handleIdx||this.activeHandleIdx||0;if(this.initialized&&this.restricted){if((handleIdx>0)&&(sliderValue<this.values[handleIdx-1]))
sliderValue=this.values[handleIdx-1];if((handleIdx<(this.handles.length-1))&&(sliderValue>this.values[handleIdx+1]))
sliderValue=this.values[handleIdx+1];}
sliderValue=this.getNearestValue(sliderValue);this.values[handleIdx]=sliderValue;this.value=this.values[0];this.handles[handleIdx].style[this.isVertical()?'top':'left']=this.translateToPx(sliderValue);this.drawSpans();if(!this.dragging||!this.event)this.updateFinished();},setValueBy:function(delta,handleIdx){this.setValue(this.values[handleIdx||this.activeHandleIdx||0]+delta,handleIdx||this.activeHandleIdx||0);},translateToPx:function(value){return Math.round(((this.trackLength-this.handleLength)/(this.range.end-this.range.start))*(value-this.range.start))+"px";},translateToValue:function(offset){return((offset/(this.trackLength-this.handleLength)*(this.range.end-this.range.start))+this.range.start);},getRange:function(range){var v=this.values.sortBy(Prototype.K);range=range||0;return $R(v[range],v[range+1]);},minimumOffset:function(){return(this.isVertical()?this.alignY:this.alignX);},maximumOffset:function(){return(this.isVertical()?(this.track.offsetHeight!=0?this.track.offsetHeight:this.track.style.height.replace(/px$/,""))-this.alignY:(this.track.offsetWidth!=0?this.track.offsetWidth:this.track.style.width.replace(/px$/,""))-this.alignX);},isVertical:function(){return(this.axis=='vertical');},drawSpans:function(){var slider=this;if(this.spans)
$R(0,this.spans.length-1).each(function(r){slider.setSpan(slider.spans[r],slider.getRange(r))});if(this.options.startSpan)
this.setSpan(this.options.startSpan,$R(0,this.values.length>1?this.getRange(0).min():this.value));if(this.options.endSpan)
this.setSpan(this.options.endSpan,$R(this.values.length>1?this.getRange(this.spans.length-1).max():this.value,this.maximum));},setSpan:function(span,range){if(this.isVertical()){span.style.top=this.translateToPx(range.start);span.style.height=this.translateToPx(range.end-range.start+this.range.start);}else{span.style.left=this.translateToPx(range.start);span.style.width=this.translateToPx(range.end-range.start+this.range.start);}},updateStyles:function(){this.handles.each(function(h){Element.removeClassName(h,'selected')});Element.addClassName(this.activeHandle,'selected');},startDrag:function(event){if(Event.isLeftClick(event)){if(!this.disabled){this.active=true;var handle=Event.element(event);var pointer=[Event.pointerX(event),Event.pointerY(event)];var track=handle;if(track==this.track){var offsets=Position.cumulativeOffset(this.track);this.event=event;this.setValue(this.translateToValue((this.isVertical()?pointer[1]-offsets[1]:pointer[0]-offsets[0])-(this.handleLength/2)));var offsets=Position.cumulativeOffset(this.activeHandle);this.offsetX=(pointer[0]-offsets[0]);this.offsetY=(pointer[1]-offsets[1]);}else{while((this.handles.indexOf(handle)==-1)&&handle.parentNode)
handle=handle.parentNode;if(this.handles.indexOf(handle)!=-1){this.activeHandle=handle;this.activeHandleIdx=this.handles.indexOf(this.activeHandle);this.updateStyles();var offsets=Position.cumulativeOffset(this.activeHandle);this.offsetX=(pointer[0]-offsets[0]);this.offsetY=(pointer[1]-offsets[1]);}}}
Event.stop(event);}},update:function(event){if(this.active){if(!this.dragging)this.dragging=true;this.draw(event);if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(event);}},draw:function(event){var pointer=[Event.pointerX(event),Event.pointerY(event)];var offsets=Position.cumulativeOffset(this.track);pointer[0]-=this.offsetX+offsets[0];pointer[1]-=this.offsetY+offsets[1];this.event=event;this.setValue(this.translateToValue(this.isVertical()?pointer[1]:pointer[0]));if(this.initialized&&this.options.onSlide)
this.options.onSlide(this.values.length>1?this.values:this.value,this);},endDrag:function(event){if(this.active&&this.dragging){this.finishDrag(event,true);Event.stop(event);}
this.active=false;this.dragging=false;},finishDrag:function(event,success){this.active=false;this.dragging=false;this.updateFinished();},updateFinished:function(){if(this.initialized&&this.options.onChange)
this.options.onChange(this.values.length>1?this.values:this.value,this);this.event=null;}});function jumpToNotes(){EstatelyEvent('Listing (active)','Jump to Notes');Effect.ScrollTo('walk_score');(function(){new Effect.Highlight('home_notes_wrappper',{'endcolor':'#F1F4F8','duration':2.5});}).delay(1);}
function jumpToMortgage(){EstatelyEvent('Listing (active)','Jump to Mortgage Calculator');Effect.ScrollTo('home_notes_wrappper');(function(){new Effect.Highlight('mortgage_calculator_wrappper',{'endcolor':'#F1F4F8','duration':2.5});}).delay(1);}
function jumpToElement(element){if(!element){EstatelyEvent('JumpToElement element is undefined');}
Effect.ScrollTo(element,{'offset':-75,'duration':0.5});(function(){new Effect.Highlight(element,{'startcolor':'#fcf8bd','duration':0.75});}).delay(1.25);(function(){new Effect.Highlight(element,{'startcolor':'#fcf8bd','duration':3});}).delay(2.05);}
EstatelyShowing={verify:function(path){if(typeof(path)!=='string'){return false;}
if(!$('request_showing_form')){return false;}
this.path=path;var form_data=Form.serialize($('request_showing_form'),true);form_data['path']=path;document.body.style.cursor='progress';new Ajax.Request('/clients/request_showing',{asynchronous:true,evalJS:true,method:'get',onComplete:function(request){document.body.style.cursor='default';},onFailure:function(request){alert('We were unable to receive your showing request. Please try again.');},onSuccess:function(request){EstatelyEvent('Other - Showings','Listing Funnel: '+path,'Impression');EstatelyEvent('Other - Showings','Listing','Impression');generalSpotlight.open(request.responseText,true);try{pageTracker._trackPageview('/showing_request/listing/verify');}
catch(e){};},parameters:form_data});},complete:function(response){if(!response){return false;}
if(response.startsWith('Element.update("clients_request_showing_error_messages"')){eval(response);return false;}
EstatelyEvent('Other - Showings','Listing Funnel: '+this.path,'Conversion');EstatelyEvent('Other - Showings','Listing','Conversion');try{pageTracker._trackPageview('/showing_request/listing/complete');}
catch(e){};$('showing_verify_form').update(response);$('schedule_showing').update(response);$$('#schedule_showing p.close_successful').first().hide();$$('a.take_action').each(function(el){el.hide();});$('schedule_showing_toolbar').hide();this.path=undefined;}};function emailListing(house_id){document.body.style.cursor='progress';new Ajax.Request('/listings/email_light_box',{asynchronous:true,evalScripts:true,method:'get',onComplete:function(request){document.body.style.cursor='default';},onFailure:function(request){alert('We were unable to process your request. Please try again.');},onSuccess:function(request){generalSpotlight.open(request.responseText,true);},parameters:{id:house_id}});}
function swapHoodTab(section){var tab=Element.up($(section+'TabLink'));if(tab.hasClassName('on')){return false;};EstatelyEvent('Listing (active)','Neighborhood Overview','Tab: '+section.gsub('hood',''));$$('.neighborhood_wrapper .on').each(function(el){el.removeClassName('on');});tab.addClassName('on');$(section).addClassName('on');}