var Profiles={load:function(){$$('#send_action_alert').invoke('observe','click',this._showActionAlertForm);$$('#map_search_submit').invoke('observe','click',this._locationSearch);$$('#map_search').invoke('observe','keypress',this._locationSearchIfEnter);$$('#new_message').invoke('observe','click',this._showNewMessageForm);$$('#remove_image').invoke('observe','click',this._removeImage);if($('search_form')){this._observeSearchForm();}
if(window.HMSmallMap&&$(HMSmallMap.SMALL_MAP_ID)){this._createProfileMap();}},_removeImage:function(e){e.stop();if(HMUtils.confirm()){var url=e.element().href;Requester.Delete(url,{onSuccess:this._onRemoveImageSuccess,onFailure:$error.curry("Your profile image could not be removed.")});}},_onRemoveImageSuccess:function(xhr){$info("Your profile image has been removed.");$('profile_sidebar').replace(xhr.responseText);},_observeSearchForm:function(){this.requests=0;new Form.Observer('search_form',1.0,this._onSearchFormUpdate);},_onSearchFormUpdate:function(element,value){new Ajax.Updater('profile_list_div','/profiles',{asynchronous:true,method:'get',parameters:value,onLoading:this._onProfileListUpdateStart,onComplete:this._onProfileListUpdateFinish,onFailure:$error.curry("Sorry, something went wrong...")});},_onProfileListUpdateStart:function(){this.requests++;$$('.spinner').invoke('show');},_onProfileListUpdateFinish:function(){this.requests--;if(!this.requests){$$('.spinner').invoke('hide');}},_showNewMessageForm:function(e){Messages.showNewMessage(this.up('h2').down('#username').innerHTML,e);},_showActionAlertForm:function(event){event.stop();Modalbox.show("/action_alerts/new",{title:"New action alert",width:680,afterLoad:this._afterActionAlertFormLoad});},_afterActionAlertFormLoad:function(){$$('.submit').invoke('observe','click',this._submitActionAlertForm);},_submitActionAlertForm:function(event){event.stop();var form=$('new_message_form');Requester.post(form.action,{link:this,parameters:form.serialize(),onSuccess:function(){Modalbox.hideWithMessage("Action alert sent.")},onFailure:function(xhr){$error(xhr.responseText)}});},_createProfileMap:function(){var lat=$('profile_lat');var lng=$('profile_lng');var zoom=$('profile_zoom');var mapTypeField=$('profile_map_type');var positionAvailable=(lat&&lng&&zoom&&lat.value&&lng.value&&zoom.value);var onEditProfilePage=!!($('edit_profile_page'));if(positionAvailable||onEditProfilePage){var handlers={};var defaultPosition=undefined;var defaultZoom=undefined;var mapType=(mapTypeField&&HMMap.getMapTypeByName(mapTypeField.value))||G_PHYSICAL_MAP;if(onEditProfilePage){handlers.moveend=this._updateCoordinates;handlers.maptypechanged=this._updateMapType;}
if(positionAvailable){defaultPosition={lat:lat.value,lng:lng.value};defaultZoom=parseInt(zoom.value,10);}
this._profileMap=new HMSmallMap({mapTypeControl:'dropdown',mapType:mapType,defaultZoom:defaultZoom||3,defaultPosition:defaultPosition,handlers:handlers});}},_updateCoordinates:function(){var latLng=this._profileMap.getCenter();$('profile_lat').value=latLng.lat();$('profile_lng').value=latLng.lng();$('profile_zoom').value=this._profileMap.getZoom();},_updateMapType:function(){$('profile_map_type').value=this._profileMap.getMapTypeString();},_locationSearchIfEnter:function(event){if(event.keyCode==13){event.preventDefault();this._locationSearch();}},_locationSearch:function(){this._profileMap.findAddressAndMove($('map_search').value);}};HMUtils.bindMethods(Profiles,'load','_removeImage','_showActionAlertForm','_updateMapType','_updateCoordinates','_afterActionAlertFormLoad','_onSearchFormUpdate','_onProfileListUpdateStart','_onProfileListUpdateFinish','_locationSearchIfEnter','_locationSearch');Event.observe(document,'dom:loaded',Profiles.load);var Maps={init:function(){HMUtils.bindClick('delete_button',this._deleteSelected.wrap(this._ifAnythingSelected));HMUtils.bindClick('edit_button',this._showEdit.wrap(this._ifProperSelection));HMUtils.bindClick('view_maps_button',Maps._showMaps.wrap(Maps._ifAnythingSelected));HMUtils.bindClick('select_all_maps',this._setChecked.curry(true));HMUtils.bindClick('unselect_all_maps',this._setChecked.curry(false));HMUtils.bindClick('add_to_shared_button',Maps._addToSharedMaps.wrap(Maps._ifAnythingSelected));HMUtils.bindClick('create_button',function(){MapCreateForm.showForm(null)});HMUtils.bindClick('lock_button',Maps._lockMaps.curry(true).wrap(HMUtils.confirm).wrap(Maps._ifAnythingSelected));HMUtils.bindClick('unlock_button',Maps._lockMaps.curry(false).wrap(HMUtils.confirm).wrap(Maps._ifAnythingSelected));},_lockMaps:function(lock,e){e.stop();e.element().blur();var ids=Maps._getChecked().pluck('value');var url=lock?'/maps/lock':'/maps/unlock';var cssClassMethod=lock?'addClassName':'removeClassName';Requester.put(url,{parameters:{'ids[]':ids},onSuccess:function(xhr){ids.each(function(id){$('map_list_element_'+id)[cssClassMethod]('locked')});Maps._setChecked(false);$info("Selected maps have been "+(lock?'locked':'unlocked')+".");},onFailure:function(xhr){$warning(xhr.responseText)},onError:function(){$error("Oops! Something went wrong.")}});},_setChecked:function(value,e){if(e){e.stop();e.element().blur();}
$$('div.saved_maps_list input[type=checkbox]').clap('checked',value);},_ifAnythingSelected:function(f,e){e.stop();e.element().blur();if(Maps._getChecked().empty()){$warning("You have to select at least one map");}else{f.apply(this,HMUtils.argumentsSubset(arguments,1));}},_ifProperSelection:function(f,e){e.stop();e.element().blur();var checked=Maps._getChecked();if(checked.empty()){$warning("You have to select map which you want to edit.");}else if(checked.size()>1){$warning("You have to select only one map.");}else if(!isAdmin&&checked.first().up('.saved_maps_list').hasClassName('shared_maps')){$warning("You can't edit shared maps, only those that you've created.");}else if(!isAdmin&&checked.first().up('.map').hasClassName('locked')){$warning("You can't edit this map - it's been locked by the administrator.");}else{f(checked.first().value);}},_getChecked:function(){return $$('div.saved_maps_list input:checked[type=checkbox]');},_deleteSelected:function(){var comment="";if(!$$('.shared_maps input:checked[type=checkbox]').empty()){comment=" (Shared maps will not be completely deleted, they'll just be removed from your profile.)";}
if(confirm("Are you sure?"+comment)){var ids=Maps._getChecked().pluck('value');Requester.Delete('/maps/delete_multiple',{parameters:{'ids[]':ids},onSuccess:function(){$info("Selected maps have been deleted.");ids.each(function(id){$('map_list_element_'+id).remove()});},onFailure:function(xhr){$error(xhr.responseText)}});}},_deleteSelectedFeatured:function(){var ids=Maps._getChecked().pluck('value');Requester.Delete('/featured_maps/delete_multiple?'+HMUtils.arrayParameter('ids',ids),{onSuccess:function(){ids.each(function(id){$('map_list_element_'+id).remove();});new Ajax.Updater('mark_as_featured','/featured_maps/add_featured_box',{method:'get'});},onFailure:function(xhr){$error(xhr.responseText)}});},_showEdit:function(mapId){var name=$('map_list_element_'+mapId).down('a').innerHTML;Modalbox.show('/maps/'+mapId+'/edit',{title:name,width:550,afterLoad:this._afterEditFormLoad,afterHide:HMUtils.unloadTinyMCE,onFailure:function(xhr){Modalbox.hide();$warning(xhr.responseText);}});},_afterEditFormLoad:function(){$('submit_new_map').observe('click',this._submitEditForm);MapCreateForm.initializeTinyMCE();MapCreateForm.initializeOnOff();},_submitEditForm:function(e){e.stop();MapCreateForm.updateFromTinyMCE();var link=e.element();var form=link.up('form');var mapId=form.readAttribute('id').getId();Requester.put('/maps/'+mapId,{link:link,parameters:form.serialize(),onSuccess:this._onEditFormSuccess.curry(mapId),onFailure:function(xhr){$warning(xhr.responseText)}});},_onEditFormSuccess:function(mapId){Modalbox.hideWithMessage("Map updated successfully");var mapDiv=$('map_list_element_'+mapId);mapDiv.down('a').update($F('map_name'));mapDiv.down('.description').update($F('map_description'));},_showMaps:function(e){document.location.href='/markers?maps='+Maps._getChecked().pluck('value').join();},_addToSharedMaps:function(e){var mapIds=this._getChecked().pluck('value');Requester.post('/maps/add_multiple_to_shared',{link:e.element(),parameters:{'map_ids[]':mapIds},onSuccess:this._onAddToSharedSuccess,onFailure:function(){$error("Error while adding maps")}});},_onAddToSharedSuccess:function(){this._setChecked(false);$info("Selected maps have been added to your shared maps.");}};HMUtils.bindMethods(Maps,'init','_showEdit','_submitEditForm','_afterEditFormLoad','_addToSharedMaps','_onAddToSharedSuccess');Event.observe(document,'dom:loaded',Maps.init);var Messages={CREATE_MESSAGE_PATH:'/messages',DELETE_MESSAGES_PATH:'/messages/delete_multiple',load:function(){var submitDeleteMessages=this._submitDeleteMessages.wrap(HMUtils.confirm).wrap(this._ifMessageSelected);$$('#compose_button').invoke('observe','click',this.showNewMessage.curry(''));$$('#select_all_messages').invoke('observe','click',this._setChecked.curry(true));$$('#unselect_all_messages').invoke('observe','click',this._setChecked.curry(false));$$('#delete_messages_button').invoke('observe','click',submitDeleteMessages);$$('#forward_messages_check_box').invoke('observe','click',this._onForwardMessagesChanged);$$('#new_reply .submit').invoke('observe','click',this._onReplySubmit);$$('#collapse_button').invoke('observe','click',this._expandOrCollapseAll);$$('.thread_message').each(function(e){this._initMessage(e)}.bind(this));this._initExpandOrCollapseButton();},_onForwardMessagesChanged:function(){var checked=$('forward_messages_check_box').checked;Requester.put('/messages/set_forward_messages',{parameters:{forward_messages:(checked?'1':'')},onSuccess:function(){$info("Message forwarding turned "+(checked?"ON":"OFF")+".")},onFailure:function(){$error("Sorry, something went wrong...")}});},_selectedMessages:function(){return $('thread_list').select('input:checked[type=checkbox]');},_setChecked:function(value,event){event.stop();$$('table.messages input[type=checkbox]').clap('checked',value);},_ifMessageSelected:function(f){if(this._selectedMessages().length>0){f.call($A(arguments).slice(1));}else{$warning('You have to check at least one message thread.');}},_submitDeleteMessages:function(){var selectedIds=this._selectedMessages().map(function(ch){return ch.value});Requester.Delete(this.DELETE_MESSAGES_PATH,{parameters:{'selected_ids[]':selectedIds,folder:$('folder').value,page:$('page').value},onSuccess:this._onDeleteMessagesSuccess,onFailure:function(response){$warning(response.responseText)}});},_onDeleteMessagesSuccess:function(xhr){$info("Messages deleted.");$$('.messages_page').first().update(xhr.responseText);this.load();},modalBoxLoaded:function(){$('submit_button').observe('click',this._submitNewMessageForm);},showNewMessage:function(username,event){event.stop();event.element().blur();Modalbox.show("/messages/new?to="+username,{title:"New Message",width:530});},_submitNewMessageForm:function(e){e.stop();Requester.post(this.CREATE_MESSAGE_PATH,{link:e.element(),parameters:$('new_message_form').serialize(),onSuccess:function(){Modalbox.hideWithMessage('Message sent.')},onFailure:function(xhr){$warning(xhr.responseText)}});},_initMessage:function(div){div.select('.collapse_link a, .expand_link a').invoke('observe','click',this._changeCollapsedState);div.observe('click',function(e){var collapsed=div.hasClassName('collapsed');var area=e.element();var isALink=(area.tagName=='A');var isPartOfHeader=(area.hasClassName('username')||area.hasClassName('message_info'));if((collapsed&&!isALink)||(!collapsed&&isPartOfHeader)){this._changeCollapsedState.call(div,e);}}.bind(this));},_changeCollapsedState:function(e){e.stop();var div=$(this);if(!div.hasClassName('thread_message')){div=div.up('.thread_message');}
div.toggleClassName('collapsed');Messages._initExpandOrCollapseButton();},_onReplySubmit:function(e){e.stop();var form=$('new_reply').down('form');Requester.post(form.action,{link:e.element(),parameters:form.serialize(),onSuccess:this._onReplySuccess,on400:this._onReplyValidationError,onFailure:function(xhr){$error(xhr.responseText)}});},_onReplySuccess:function(xhr){$('new_reply').insert({before:xhr.responseText});$$('#new_reply textarea').first().value='';$('errors').update('');this._initMessage($$('.thread_message').last());},_onReplyValidationError:function(xhr){$('new_reply').replace(xhr.responseText);$$('#new_reply .submit').invoke('observe','click',this._onReplySubmit);},_expandOrCollapseAll:function(event){event.stop();if(this.mode=="collapse"){$$('.thread_message').invoke('addClassName','collapsed');Messages._setExpandOrCollapseButtonMode("expand");}else{$$('.thread_message').invoke('removeClassName','collapsed');Messages._setExpandOrCollapseButtonMode("collapse");}},_setExpandOrCollapseButtonMode:function(mode){var button=$('collapse_button');button.mode=mode;button.innerHTML=(mode=="collapse")?"Collapse All Messages":"Expand All Messages";},_initExpandOrCollapseButton:function(){var button=$('collapse_button');if(button){var collapsed=$$('.collapsed');this._setExpandOrCollapseButtonMode((collapsed.length>0)?"expand":"collapse");}}};HMUtils.bindMethods(Messages,'load','modalBoxLoaded','_ifMessageSelected','_submitDeleteMessages','_submitNewMessageForm','_onReplySubmit','_onReplySuccess','_onReplyValidationError','_onDeleteMessagesSuccess');Event.observe(document,'dom:loaded',Messages.load);if(!window.GMarkerExtensions){var GMarkerPrototypeExtensions={hmOpenStaticToolTip:function(){var markerPos=this.map.fromLatLngToContainerPixel(this.getLatLng());var mapPos=HMUtils.findElementPosition(this.map.getContainer());var mapSize=this.map.getSize();var xInRange=(markerPos.x>=0&&markerPos.x<mapSize.width);var yInRange=(markerPos.y>=0&&markerPos.y<mapSize.height);if(xInRange&&yInRange){HMMarkerTooltip.show(this.name,{x:mapPos.x+markerPos.x+2,y:mapPos.y+markerPos.y-16});}},hmCloseToolTip:function(){HMMarkerTooltip.hide();},hmOpenMovingToolTip:function(){HMMarkerTooltip.show(this.name);},hmClone:function(){var newMarker=new GMarker(this.getLatLng(),{icon:this.getIcon(),draggable:true});GMarker.hmCopyMarkerFields(this,newMarker);if(!this.draggingEnabled()){newMarker.disableDragging();}
return newMarker;}};var GMarkerExtensions={HABITATMAP_MARKER_COLORS:['orange','blue','yellow','green','magenta','cyan'],HABITATMAP_MARKER_FIELDS:['id','name','address','color','assigned_map_ids'],hmInstallExtensions:function(){if(window.GMarker&&window.HMUtils&&!GMarkerExtensions._installed){GMarkerExtensions._installed=true;HMUtils.extend(GMarker,GMarkerExtensions);HMUtils.extend(GMarker.prototype,GMarkerPrototypeExtensions);}},hmCopyMarkerFields:function(source,target){var fields=GMarker.HABITATMAP_MARKER_FIELDS;var n=fields.length;for(var i=0;i<n;i++){target[fields[i]]=source[fields[i]];}},hmGetMarkerColor:function(index){var colors=GMarker.HABITATMAP_MARKER_COLORS;if(!(index&&index>=0&&index<colors.length)){index=0;}
return colors[index];},hmGetMarkerIcon:function(index){var icon=new GIcon();icon.image=HABITATMAP_URL+'/images/markers/'+GMarker.hmGetMarkerColor(index)+'_map.png';icon.iconSize=new GSize(23,33);icon.iconAnchor=new GPoint(4,28);icon.infoWindowAnchor=new GPoint(5,2);return icon;},hmGetCenterPointIcon:function(){var icon=new GIcon();icon.image=HABITATMAP_URL+'/images/markers/centerpoint_x.png';icon.iconSize=new GSize(23,23);icon.iconAnchor=new GPoint(11,11);return icon;},hmBuildCenterPointMarker:function(markerJSON){if(!markerJSON.lat||!markerJSON.lng){HMUtils.debug('no lat or lng given!');}
var latlng=new GLatLng(parseFloat(markerJSON.lat),parseFloat(markerJSON.lng));var point=new GMarker(latlng,{icon:GMarker.hmGetCenterPointIcon(),clickable:false});point.disableDragging();return point;}};GMarkerExtensions.hmInstallExtensions();}
if(!window.HMMap){var HMMap=HMClass.extend({init:function(elementId,options){if(!GBrowserIsCompatible()){HMUtils.error('Your browser is not compatible with Google Maps. '+'Try latest version of Mozilla Firefox or Google Chrome.');}
var $D=HMDelegate.create;this.buildMarkerFromJSONDelegate=$D(this,this.buildMarkerFromJSON);this.extendBoundsByLatLngDelegate=$D(this,this.extendBoundsByLatLng);this.extendPolyBoundsDelegate=$D(this,this.extendPolyBounds);this.getLatLngCallbackDelegate=$D(this,this.getLatLngCallback);this.checkZoomForTerrainMapDelegate=$D(this,this._checkZoomForTerrainMap);this.onMarkerMouseOverDelegate=$D(this,this.onMarkerMouseOver);this.onMarkerMouseOutDelegate=$D(this,this.onMarkerMouseOut);this.onMarkerClickDelegate=$D(this,this.onMarkerClick);this.onMapMouseOutDelegate=$D(this,this.onMapMouseOut);this.onPolyMouseOverDelegate=$D(this,this.onPolyMouseOver);this.onPolyMouseOutDelegate=$D(this,this.onPolyMouseOut);this.onPolyClickDelegate=$D(this,this.onPolyClick);this._options=options=options||{};this._controllers=options.controllers||{};this._markers=[];this._polies=[];this._bounds=null;this._previousMapType=null;this._displayLines=true;this._groupMarkers=(options.groupMarkers!==undefined)?options.groupMarkers:true;this._currentTooltipElement=null;this._element=HMUtils.findObj(elementId);this._map=this._createGoogleMap();this._setInitialPosition();this.setMapType();this._checkZoomForTerrainMap();this.centerMap();if(window.HMColorMarkerClusterer){this._markerClusterer=new HMColorMarkerClusterer(this._map,this._markers,HMMap.MARKER_CLUSTERER_OPTIONS);}else if(this._groupMarkers){throw"groupMarkers is enabled, but HMColorMarkerClusterer is not available";}
if(options.initialMarkerJSON){var marker=this.buildMarkerFromJSONDelegate(options.initialMarkerJSON,options.initialMarkerDraggable);this.addMarker(marker);}else if(options.initialMarker){this.addMarker(options.initialMarker);}
var handlers=options.handlers;if(handlers){var handler;for(var key in handlers){(handler=handlers[key])&&GEvent.addListener(this._map,key,handler);}}
GEvent.addListener(this._map,"zoomend",this.checkZoomForTerrainMapDelegate);},_createGoogleMap:function(){var map=new GMap2(this._element,this._options.mapOptions);map.addControl(new GScaleControl());map.addControl(this._createMapControl(this._options.mapControlSize));map.addControl(this._createMapTypeControl(this._options.mapTypeControl));map.enableScrollWheelZoom();map.addMapType(G_PHYSICAL_MAP);GEvent.addListener(map,'mouseout',this.onMapMouseOutDelegate);return map;},changeMapTypeTo:function(mapType){this._map.setMapType(mapType||G_HYBRID_MAP);},setMapType:function(){this.changeMapTypeTo(this._options.mapType);},onMapMouseOut:function(source){if(this._currentTooltipElement){HMMarkerTooltip.hide(true);this._currentTooltipElement=false;}},_createMapControl:function(size){switch(size){case'small':return new GSmallMapControl();case'small_zoom':return new GSmallZoomControl3D();default:return new GLargeMapControl3D();}},_createMapTypeControl:function(type){switch(type){case'full':return new GMapTypeControl();case'dropdown':return new GMenuMapTypeControl();default:return new GHierarchicalMapTypeControl();}},_setInitialPosition:function(){if(this._options.initialMarker){this._defaultLatLng=this._options.initialMarker.getLatLng();}else{var latLng=this._options.initialMarkerJSON||this._options.defaultPosition||HMMap.DEFAULT_POSITION;this._defaultLatLng=new GLatLng(latLng.lat,latLng.lng);}
this._defaultZoom=this._options.defaultZoom||HMMap.DEFAULT_ZOOM;},setDisplayLines:function(display){this._displayLines=display;},getOptions:function(){return this._options;},hide:function(){this._element.style.visibility='hidden';},show:function(){this._element.style.visibility='visible';},refreshMap:function(){this.centerMap(this._map.getCenter());},checkResize:function(){this._map.checkResize();},_checkZoomForTerrainMap:function(){if(this.getZoom()>=15&&this.getMapType()==G_PHYSICAL_MAP){this.changeMapTypeTo(G_HYBRID_MAP);this._previousMapType=G_PHYSICAL_MAP;}
else if(this.getZoom()<15&&this._previousMapType){this.changeMapTypeTo(this._previousMapType);this._previousMapType=null;}},centerMap:function(where,zoom){this._map.setCenter(where||this._defaultLatLng,zoom||this._defaultZoom);},getCenter:function(){return this._map.getCenter();},getCenterAsHash:function(){var center=this.getCenter();return{lat:center.lat(),lng:center.lng()};},getZoom:function(){return this._map.getZoom();},getLocation:function(){return{defaultZoom:this.getZoom(),defaultPosition:this.getCenterAsHash()};},getMapType:function(){return this._map.getCurrentMapType();},getMapTypeString:function(){var currentType=this.getMapType();var result;switch(currentType){case G_NORMAL_MAP:result="Map";break;case G_PHYSICAL_MAP:result="Terrain";break;case G_SATELLITE_MAP:result="Satellite";break;default:result="Hybrid";}
return result;},autoZoom:function(){var poliesNum=this._polies.length;var markersNum=this._markers.length;var noPolies=(poliesNum===0);var noMarkers=(markersNum===0);var oneMarker=(markersNum==1);if(noMarkers&&noPolies){return;}
this._bounds=new GLatLngBounds();this.extendBounds(HMUtils.collect(this._markers,'getLatLng'));var zoom;if(oneMarker&&noPolies){zoom=HMMap.ZOOM_LEVEL_FOR_SINGLE_MARKER;}else{HMUtils.each(this._polies,this.extendPolyBoundsDelegate);zoom=this._map.getBoundsZoomLevel(this._bounds);}
this.centerMap(this._bounds.getCenter(),zoom);},extendPolyBounds:function(source,i){this.extendBounds(i.getVertices());},extendBounds:function(latlngs){HMUtils.each(latlngs,this.extendBoundsByLatLngDelegate);},extendBoundsByLatLng:function(source,i){this._bounds.extend(i);},findAddressAndMove:function(address,callback){if(!address||address==''){return;}
var coder=new GClientGeocoder();this.getLatLngCallbackDelegate.delegate.args=[callback];coder.getLatLng(address,this.getLatLngCallbackDelegate);},getLatLngCallback:function(source,callback,latLng){if(latLng){this.centerMap(latLng,HMMap.ZOOM_LEVEL_FOR_LOCATION);if(callback){callback(latLng);}}else{HMUtils.warning('Address not found.');}},addCenterPoint:function(json){this.centerPoint=GMarker.hmBuildCenterPointMarker(json);this._map.addOverlay(this.centerPoint);},addMarker:function(marker){this.addMarkers([marker]);},addMarkers:function(markers){HMUtils.each(markers,this.initMarker,this);this._markers=this._markers.concat(markers);this._addMarkersToMap();},initMarker:function(marker){marker.map=this._map;if(marker.name){GEvent.addListener(marker,'mouseover',this.onMarkerMouseOverDelegate);GEvent.addListener(marker,'mouseout',this.onMarkerMouseOutDelegate);GEvent.addListener(marker,'click',this.onMarkerClickDelegate);}},onMarkerMouseOver:function(source){_currentTooltipElement=source;HMMarkerTooltip.show(source.name);},onMarkerMouseOut:function(source){this._currentTooltipElement=null;HMMarkerTooltip.hide();},onMarkerClick:function(marker){HMMarkerTooltip.hide(true);},_addMarkersToMap:function(){if(this._groupMarkers){this._markerClusterer.addMarkers(this._markers);}else{HMUtils.each(this._markers,this._map.addOverlay,this._map);}},_removeMarkersFromMap:function(){if(this._groupMarkers){this._markerClusterer.clearMarkers();}else{this._removeOverlays(this._markers);}},getGroupMarkers:function(){return this._groupMarkers;},setMarkerGrouping:function(grouping){if(grouping&&!this._markerClusterer){throw"can't enable marker grouping, marker clusterer is not available";}
this._removeMarkersFromMap();this.setGroupMarkers(grouping);this._addMarkersToMap();},setGroupMarkers:function(group){this._groupMarkers=group;},addMarkerFromJSON:function(json){this.addMarkersFromJSON([json]);},addMarkersFromJSON:function(json){this.addMarkers(this.getMarkersFromJson(json));},clear:function(){this.clearMarkers();this.clearPolies();},clearMarkers:function(){this._removeMarkersFromMap();this._markers=[];this.clearCenterPoint();},addPolies:function(polies){HMUtils.each(polies,this.addPoly,this);},addPoly:function(poly){this._polies.push(poly);this._map.addOverlay(poly);poly.map=this._map;GEvent.addListener(poly,'mouseover',this.onPolyMouseOverDelegate);GEvent.addListener(poly,'mouseout',this.onPolyMouseOutDelegate);GEvent.addListener(poly,'click',this.onPolyClickDelegate);},onPolyClick:function(source){var handler=this._options.polyClickHandler;var layer=source.layer;if(handler&&layer.isEditable()){handler(layer);}},onPolyMouseOver:function(source){this._currentTooltipElement=source;HMMarkerTooltip.showAndPreserve(source.layer.getName());},onPolyMouseOut:function(source){this._currentTooltipElement=null;HMMarkerTooltip.hide(true);},clearPolies:function(){this._removeOverlays(this._polies);this._polies=[];},addLayers:function(layers){this.clearPolies();HMUtils.each(layers,function(layer){this.addPolies(layer.polies);},this);},addLayersFromJSON:function(json){var layers=HMLayer.createFromJSON(json);this.addLayers(layers);},_removeOverlays:function(overlays){HMUtils.each(overlays,function(m){this._map.removeOverlay(m);},this);},clearCenterPoint:function(){if(this.centerPoint){this._map.removeOverlay(this.centerPoint);delete this.centerPoint;}},removeLayer:function(layer){HMUtils.each(HMUtils.collect(this._polies,function(p){return p;}),function(poly){var oldPoly=HMUtils.findFirstAndRemove(this._polies,function(p){return p.layer.getId()==layer.getId();});if(oldPoly){this._map.removeOverlay(oldPoly);}},this);},refreshLayer:function(layer){this.removeLayer(layer);this.addPolies(layer.polies);},getMarkers:function(){return this._markers;},refreshMarker:function(id,json){if(json){this.removeMarker(id);this.addMarkerFromJSON(json);}else{var marker=this.removeMarker(id);this.addMarker(marker);}},removeMarker:function(id){var oldMarker=HMUtils.findFirstAndRemove(this._markers,function(marker){return marker.id==id;});if(oldMarker){this._markerClusterer.removeMarker(oldMarker);this._map.removeOverlay(oldMarker);}
return oldMarker;},findMarker:function(id){return HMUtils.findFirst(this._markers,function(marker){return marker.id==id;});},updateMarkers:function(markers){this.clearMarkers();this.addMarkers(markers);},updateMarkersFromJSON:function(json){this.updateMarkers(this.getMarkersFromJson(json));},getMarkersFromJson:function(json){return HMUtils.collect(json,this.buildMarkerFromJSONDelegate);},buildMarkerFromJSON:function(source,markerJSON,draggable){if(markerJSON.lat===undefined||markerJSON.lng===undefined){HMUtils.debug('no lat or lng given!');}
var latLng=new GLatLng(parseFloat(markerJSON.lat),parseFloat(markerJSON.lng));var colorId=parseInt(markerJSON.color_id,10);var colorNumber=isNaN(colorId)?this.findColorForMarker(markerJSON):colorId;var marker=new GMarker(latLng,{icon:GMarker.hmGetMarkerIcon(colorNumber),draggable:true});GMarker.hmCopyMarkerFields(markerJSON,marker);marker.color=GMarker.hmGetMarkerColor(colorNumber);if(!draggable){marker.disableDragging();}
return marker;},findColorForMarker:function(markerJSON){return 0;},mapBoundsForQueryAsHash:function(type){var bounds=this._map.getBounds();var sw=bounds.getSouthWest();var ne=bounds.getNorthEast();var param='search_'+type;var hash={};hash[param+"[n]"]=ne.lat();hash[param+"[s]"]=sw.lat();hash[param+"[w]"]=sw.lng();hash[param+"[e]"]=ne.lng();return hash;},mapBoundsForQuery:function(type){return HMUtils.hashToQueryParameters(this.mapBoundsForQueryAsHash(type));},onSearchSuccess:function(markers,location,radius,currentView){this.clearCenterPoint();this.updateMarkersFromJSON(markers);if(location){this.addCenterPoint(location);this.centerMap(this.centerPoint.getLatLng(),HMMap.MILES_TO_ZOOM[radius.toString()]);}
else if(!currentView){this.autoZoom();}},getAttributesForPermalink:function(){return{t:this.getMapTypeString().toLowerCase(),z:this.getZoom(),lat:this.getCenter().lat(),lng:this.getCenter().lng(),nogrp:!this.getGroupMarkers()};}});HMUtils.extend(HMMap,{ZOOM_LEVEL_FOR_SINGLE_MARKER:15,ZOOM_LEVEL_FOR_LOCATION:14,DEFAULT_ZOOM:4,DEFAULT_POSITION:{lat:39.232253,lng:-96.591797},MILES_TO_ZOOM:{'1':14,'5':12,'10':11,'20':10},MARKER_CLUSTERER_OPTIONS:{gridSize:25},MAPPING:{map:'G_NORMAL_MAP',hybrid:'G_HYBRID_MAP',satellite:'G_SATELLITE_MAP',terrain:'G_PHYSICAL_MAP'},getMapTypeByName:function(name){return window[HMMap.MAPPING[name.toLowerCase()]];}});}
var HMSmallMap=HMMap.extend({init:function(options){var defaultOptions={mapControlSize:'small_zoom',groupMarkers:false,defaultZoom:HMSmallMap.DEFAULT_ZOOM_LEVEL};this._super(HMSmallMap.SMALL_MAP_ID,HMUtils.extend(defaultOptions,options));}});HMUtils.extend(HMSmallMap,{SMALL_MAP_ID:'small_map',DEFAULT_ZOOM_LEVEL:15});