HMMarkerTooltip={name:"hmMarkerTooltip",offsetX:0,offsetY:22,tip:null,init:function(){this.tip=document.getElementById(this.name);if(!this.tip){this.tip=document.createElementNS?document.createElementNS("http://www.w3.org/1999/xhtml","div"):document.createElement("div");this.tip.setAttribute("id",this.name);document.getElementsByTagName("body").item(0).appendChild(this.tip);}},onMouseMove:function(event){var x=0,y=0;if(document.all){x=(document.documentElement&&document.documentElement.scrollLeft)?document.documentElement.scrollLeft:document.body.scrollLeft;y=(document.documentElement&&document.documentElement.scrollTop)?document.documentElement.scrollTop:document.body.scrollTop;x+=window.event.clientX;y+=window.event.clientY;}else{x=event.pageX;y=event.pageY;}
HMMarkerTooltip.tip.style.left=(x+HMMarkerTooltip.offsetX)+"px";HMMarkerTooltip.tip.style.top=(y+HMMarkerTooltip.offsetY)+"px";},show:function(text,position){this.tip.innerHTML=text;this.tip.style.display="block";if(position){this.tip.style.left=position.x+"px";this.tip.style.top=position.y+"px";this.stopMoving();}else{this.startMoving();}},showAndPreserve:function(text){this.preservedText=text;this.show(text);},hide:function(clearPreservedText){if(clearPreservedText){this.preservedText=null;}
if(this.preservedText){this.tip.innerHTML=this.preservedText;}else{this.tip.style.display='none';this.tip.innerHTML="";this.stopMoving();}},startMoving:function(){HMUtils.observe(document,'mousemove',this.onMouseMove);},stopMoving:function(){HMUtils.stopObserving(document,'mousemove',this.onMouseMove);}};function HMMarkerClusterer(map,opt_markers,opt_opts){var clusters_=[];var map_=map;var maxZoom_=null;var me_=this;var gridSize_=60;var sizes=[53,56,66,78,90];var styles_=[];var leftMarkers_=[];var mcfn_=null;var zoomOnClick_=true;var calculator_=function(markers){var index=0;var count=markers.length;var dv=count;while(dv!==0){dv=parseInt(dv/10,10);index++;}
var stylesCount=this.getStyles().length;if(stylesCount<index){index=stylesCount;}
if(count>=1000){count='999+';}
return{'text':count,'index':index};};var i=0;for(i=1;i<=5;++i){styles_.push({'url':'http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/images/m'+i+'.png','height':sizes[i-1],'width':sizes[i-1]});}
if(typeof opt_opts==='object'&&opt_opts!==null){if(typeof opt_opts.gridSize==='number'&&opt_opts.gridSize>0){gridSize_=opt_opts.gridSize;}
if(typeof opt_opts.maxZoom==='number'){maxZoom_=opt_opts.maxZoom;}
if(typeof opt_opts.styles==='object'&&opt_opts.styles!==null&&opt_opts.styles.length!==0){styles_=opt_opts.styles;}
if(typeof opt_opts.calculator==='function'){calculator_=opt_opts.calculator;}
if(typeof opt_opts.zoomOnClick==='boolean'){zoomOnClick_=opt_opts.zoomOnClick;}}
this.setCalculator=function(calculator){calculator_=calculator;};this.getCalculator=function(){return GEvent.callback(this,calculator_);};this.isZoomOnClick=function(){return zoomOnClick_;};function addLeftMarkers_(){if(leftMarkers_.length===0){return;}
var leftMarkers=[];for(i=0;i<leftMarkers_.length;++i){if(isMarkerInViewport_(leftMarkers_[i])){me_.addMarker(leftMarkers_[i],true,null,null,true);}else{leftMarkers.push(leftMarkers_[i]);}}
leftMarkers_=leftMarkers;}
this.getStyles=function(){return styles_;};this.clearMarkers=function(){for(var i=0;i<clusters_.length;++i){if(typeof clusters_[i]!=="undefined"&&clusters_[i]!==null){clusters_[i].clearMarkers();}}
clusters_=[];leftMarkers_=[];};function isMarkerInViewport_(marker){return map_.getBounds().containsLatLng(marker.getLatLng());}
function reAddMarkers_(markers){var len=markers.length;var clusters=[];for(var i=len-1;i>=0;--i){me_.addMarker(markers[i].marker,true,markers[i].isAdded,clusters,true);}
addLeftMarkers_();}
this.addMarker=function(marker,opt_isNodraw,opt_isAdded,opt_clusters,opt_isNoCheck){if(opt_isNoCheck!==true){if(!isMarkerInViewport_(marker)){leftMarkers_.push(marker);return;}}
var isAdded=opt_isAdded;var clusters=opt_clusters;var pos=map_.fromLatLngToDivPixel(marker.getLatLng());if(typeof isAdded!=="boolean"){isAdded=false;}
if(typeof clusters!=="object"||clusters===null){clusters=clusters_;}
var length=clusters.length;var cluster=null;for(var i=length-1;i>=0;i--){cluster=clusters[i];var center=cluster.getCenter();if(center===null){continue;}
center=map_.fromLatLngToDivPixel(center);if(pos.x>=center.x-gridSize_&&pos.x<=center.x+gridSize_&&pos.y>=center.y-gridSize_&&pos.y<=center.y+gridSize_){cluster.addMarker({'isAdded':isAdded,'marker':marker});if(!opt_isNodraw){cluster.redraw_();}
return;}}
cluster=new HMCluster(this,map);cluster.addMarker({'isAdded':isAdded,'marker':marker});if(!opt_isNodraw){cluster.redraw_();}
clusters.push(cluster);if(clusters!==clusters_){clusters_.push(cluster);}};this.removeMarker=function(marker){for(var i=0;i<clusters_.length;++i){if(clusters_[i]&&clusters_[i].removeMarker(marker)){clusters_[i].redraw_();return;}}};this.redraw_=function(){var clusters=this.getClustersInViewport_();for(var i=0;i<clusters.length;++i){clusters[i].redraw_(true);}};this.getClustersInViewport_=function(){var clusters=[];var curBounds=map_.getBounds();for(var i=0;i<clusters_.length;i++){if(clusters_[i].isInBounds(curBounds)){clusters.push(clusters_[i]);}}
return clusters;};this.getMaxZoom_=function(){return maxZoom_;};this.getMap_=function(){return map_;};this.getGridSize_=function(){return gridSize_;};this.getTotalMarkers=function(){var result=0;for(var i=0;i<clusters_.length;++i){result+=clusters_[i].getTotalMarkers();}
return result;};this.getTotalClusters=function(){return clusters_.length;};this.resetViewport=function(){var clusters=this.getClustersInViewport_();var tmpMarkers=[];var removed=0;var curZoom=map_.getZoom();for(var i=0;i<clusters.length;++i){var cluster=clusters[i];var oldZoom=cluster.getCurrentZoom();if(oldZoom===null){continue;}
if(curZoom!==oldZoom){var mks=cluster.getMarkers();for(var j=0;j<mks.length;++j){var newMarker={'isAdded':false,'marker':mks[j].marker};tmpMarkers.push(newMarker);}
cluster.clearMarkers();removed++;for(j=0;j<clusters_.length;++j){if(cluster===clusters_[j]){clusters_.splice(j,1);}}}}
reAddMarkers_(tmpMarkers);this.redraw_();};this.addMarkers=function(markers){for(var i=0;i<markers.length;++i){this.addMarker(markers[i],true);}
this.redraw_();};this.getParentCluster=function(marker){return marker.parentCluster_;};if(typeof opt_markers==="object"&&opt_markers!==null){this.addMarkers(opt_markers);}
mcfn_=GEvent.addListener(map_,"moveend",function(){me_.resetViewport();});}
function HMCluster(markerClusterer){var center_=null;var markers_=[];var markerClusterer_=markerClusterer;var map_=markerClusterer.getMap_();var clusterMarker_=null;var zoom_=map_.getZoom();var this_=this;this.getMarkers=function(){return markers_;};this.getMarkerClusterer=function(){return markerClusterer_;};this.isInBounds=function(bounds){if(center_===null){return false;}
if(!bounds){bounds=map_.getBounds();}
var sw=map_.fromLatLngToDivPixel(bounds.getSouthWest());var ne=map_.fromLatLngToDivPixel(bounds.getNorthEast());var centerxy=map_.fromLatLngToDivPixel(center_);var inViewport=true;var gridSize=markerClusterer.getGridSize_();if(zoom_!==map_.getZoom()){var dl=map_.getZoom()-zoom_;gridSize=Math.pow(2,dl)*gridSize;}
if(ne.x!==sw.x&&(centerxy.x+gridSize<sw.x||centerxy.x-gridSize>ne.x)){inViewport=false;}
if(inViewport&&(centerxy.y+gridSize<ne.y||centerxy.y-gridSize>sw.y)){inViewport=false;}
return inViewport;};this.getCenter=function(){return center_;};this.addMarker=function(marker){if(center_===null){center_=marker.marker.getLatLng();}
marker.marker.parentCluster_=this_;markers_.push(marker);};this.removeMarker=function(marker){for(var i=0;i<markers_.length;++i){if(marker===markers_[i].marker){if(markers_[i].isAdded){map_.removeOverlay(markers_[i].marker);}
delete markers_[i].marker.parentCluster_;markers_.splice(i,1);return true;}}
return false;};this.getCurrentZoom=function(){return zoom_;};this.redraw_=function(isForce){if(!isForce&&!this.isInBounds()){return;}
zoom_=map_.getZoom();var i=0;var mz=markerClusterer.getMaxZoom_();if(mz===null){mz=map_.getCurrentMapType().getMaximumResolution();}
if(zoom_>mz||this.getTotalMarkers()===1){for(i=0;i<markers_.length;++i){if(markers_[i].isAdded){if(markers_[i].marker.isHidden()){markers_[i].marker.show();}}else{map_.addOverlay(markers_[i].marker);markers_[i].isAdded=true;}}
if(clusterMarker_!==null){clusterMarker_.hide();}}else if(this.getTotalMarkers()>1){for(i=0;i<markers_.length;++i){if(markers_[i].isAdded&&(!markers_[i].marker.isHidden())){markers_[i].marker.hide();}}
var sums=markerClusterer_.getCalculator()(this.getRealMarkers());if(clusterMarker_===null){clusterMarker_=new HMClusterMarker_(center_,sums,markerClusterer_.getStyles(),markerClusterer_.getGridSize_(),this_);map_.addOverlay(clusterMarker_);}else{if(clusterMarker_.isHidden()){clusterMarker_.show();}
clusterMarker_.setSums(sums);clusterMarker_.redraw(true);}}};this.clearMarkers=function(){if(clusterMarker_!==null){map_.removeOverlay(clusterMarker_);}
for(var i=0;i<markers_.length;++i){if(markers_[i].isAdded){map_.removeOverlay(markers_[i].marker);}
delete markers_[i].marker.parentCluster_;}
markers_=[];};this.getTotalMarkers=function(){return markers_.length;};this.getRealMarkers=function(){var result=[];for(var i=0;i<markers_.length;++i){result.push(markers_[i].marker);}
return result;};}
function HMClusterMarker_(latlng,sums,styles,padding,cluster){var index=sums.index;this.useStyle(styles[index-1]);this.styleDirty_=false;this.latlng_=latlng;this.index_=index;this.styles_=styles;this.text_=sums.text;this.padding_=padding;this.sums_=sums;this.cluster_=cluster;}
HMMarkerClusterer.loadClusterMarker=function(){HMClusterMarker_.prototype=new GOverlay();HMClusterMarker_.prototype.useStyle=function(style){this.url_=style.url;this.height_=style.height;this.width_=style.width;this.textColor_=style.opt_textColor;this.anchor_=style.opt_anchor;this.textSize_=style.opt_textSize;};HMClusterMarker_.prototype.initialize=function(map){this.map_=map;var div=document.createElement("div");var latlng=this.latlng_;var pos=this.getPosFromLatLng(latlng);div.style.cssText=this.createCss(pos);div.innerHTML=this.text_;map.getPane(G_MAP_MARKER_PANE).appendChild(div);var padding=this.padding_;var cluster=this.cluster_;GEvent.addDomListener(div,"click",function(){GEvent.trigger(cluster.getMarkerClusterer(),"clusterclick",cluster);if(cluster.getMarkerClusterer().isZoomOnClick()){var pos=map.fromLatLngToDivPixel(latlng);var sw=new GPoint(pos.x-padding,pos.y+padding);sw=map.fromDivPixelToLatLng(sw);var ne=new GPoint(pos.x+padding,pos.y-padding);ne=map.fromDivPixelToLatLng(ne);var zoom=map.getBoundsZoomLevel(new GLatLngBounds(sw,ne),map.getSize());map.setCenter(latlng,zoom);}});this.div_=div;};HMClusterMarker_.prototype.getPosFromLatLng=function(latlng){var pos=this.map_.fromLatLngToDivPixel(latlng);pos.y-=this.height_;return pos;};HMClusterMarker_.prototype.createCss=function(pos){var mstyle="";if(document.all){mstyle='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="'+this.url_+'");';}else{mstyle="background:url("+this.url_+");";}
var txtColor=this.textColor_?this.textColor_:'black';var txtSize=this.textSize_?this.textSize_:11;if(typeof this.anchor_==="object"){if(typeof this.anchor_[0]==="number"&&this.anchor_[0]>0&&this.anchor_[0]<this.height_){mstyle+='height:'+(this.height_-this.anchor_[0])+'px;padding-top:'+this.anchor_[0]+'px;';}else{mstyle+='height:'+this.height_+'px;';}
if(typeof this.anchor_[1]==="number"&&this.anchor_[1]>0&&this.anchor_[1]<this.width_){mstyle+='width:'+(this.width_-this.anchor_[1])+'px;padding-left:'+this.anchor_[1]+'px;text-align:center;';}else{mstyle+='width:'+this.width_+'px;text-align:center;';}}else{mstyle+='height:'+this.height_+'px;line-height:'+(txtSize+3)+'px;';mstyle+='width:'+this.width_+'px;text-align:center;';}
return mstyle+' cursor:pointer;top:'+pos.y+"px;left:"+
pos.x+"px;color:"+txtColor+";position:absolute;font-size:"+txtSize+"px;"+'font-family:Times New Roman,serif;font-weight:bold';};HMClusterMarker_.prototype.remove=function(){this.div_.parentNode.removeChild(this.div_);};HMClusterMarker_.prototype.copy=function(){return new HMClusterMarker_(this.latlng_,this.sums_,this.text_,this.styles_,this.padding_,this.cluster_);};HMClusterMarker_.prototype.redraw=function(force){if(!force){return;}
var pos=this.getPosFromLatLng(this.latlng_);if(this.styleDirty_){this.styleDirty_=false;this.useStyle(this.styles_[this.index_-1]);this.div_.style.cssText=this.createCss(pos);}else{this.div_.style.top=pos.y+"px";this.div_.style.left=pos.x+"px";}};HMClusterMarker_.prototype.hide=function(){this.div_.style.display="none";};HMClusterMarker_.prototype.show=function(){this.div_.style.display="";};HMClusterMarker_.prototype.isHidden=function(){return this.div_.style.display==="none";};HMClusterMarker_.prototype.setSums=function(sums){if(sums.index!==this.index_){this.styleDirty_=true;}
this.sums_=sums;this.text_=sums.text;this.index_=sums.index;this.div_.innerHTML=sums.text;};};if(window.GOverlay){HMMarkerClusterer.loadClusterMarker();}
var HMThumbnailViewer={enableTitle:true,enableAnimation:true,definefooter:'<div class="footerbar">X</div>',defineLoading:'<img src="/images/spinners/progress.gif" /> Loading Image...',scrollbarwidth:16,opacitystring:'filter:progid:DXImageTransform.Microsoft.alpha(opacity=10); -moz-opacity: 0.1; opacity: 0.1',targetlinks:[],createThumbBox:function(){this.standardbody=document.body;this.thumbBox=this._createDiv('thumbBox',this.definefooter);this.thumbBox.onclick=HMDelegate.create(this,this.closeit);this.thumbImage=this._createDiv('thumbImage');this.thumbBox.appendChild(this.thumbImage);this.thumbLoading=this._createDiv('thumbLoading',this.defineLoading);this.thumbOverlay=this._createDiv('thumbOverlay');this.thumbOverlay.style.display='none';this.standardbody.appendChild(this.thumbBox);this.standardbody.appendChild(this.thumbLoading);this.standardbody.appendChild(this.thumbOverlay);},ie:function(){return document.all&&!window.opera;},_createDiv:function(divId,text){var div=document.createElement('div');if(divId){div.id=divId;}
if(text){div.innerHTML=text;}
return div;},centerDiv:function(divobj){var docWidth=document.documentElement.clientWidth;var docHeight=document.documentElement.clientHeight;var objWidth=divobj.clientWidth;var objHeight=divobj.clientHeight;var topPosition=Math.max((docHeight-objHeight)/2,0);divobj.style.left=(docWidth-objWidth)/2+"px";divobj.style.top=Math.floor(topPosition)+"px";divobj.style.visibility="visible";},showthumbBox:function(){this.fitImageToWindow();this.centerDiv(this.thumbBox);if(this.enableAnimation){this.currentopacity=0.1;this.opacitytimer=setInterval(this.opacityanimationBind,20);}
HMUtils.observe(window,"resize",this.fitImageToWindowBind);},loadimage:function(link){this.thumbOverlay.style.display='block';if(this.ie()){this.thumbOverlay.style.filter='alpha(opacity = 45)';}
else{this.thumbOverlay.style.opacity='0.45';}
if(this.thumbBox.style.visibility=="visible"){this.closeit();}
this.centerDiv(this.thumbLoading);this.featureImage=document.createElement('img');this.featureImage.setAttribute('style',this.opacitystring);this.featureImage.onload=this.featureImageLoadBind;this.featureImage.onerror=this.featureImageLoadErrorBind;this.featureImage.src=link.getAttribute("href");this.thumbImage.innerHTML='';this.thumbImage.appendChild(this.featureImage);if(this.enableTitle&&link.getAttribute("title")){this.thumbImage.appendChild(document.createElement('br'));this.thumbImage.appendChild(document.createTextNode(link.getAttribute("title")));}},featureImageLoad:function(){setTimeout(this.featureImageTimeoutBind,1000);},featureImageTimeout:function(){this.originalDimensions={width:this.featureImage.width,height:this.featureImage.height};this.thumbLoading.style.visibility="hidden";this.showthumbBox();},featureImageLoadError:function(){this.thumbLoading.style.visibility="hidden";},setimgopacity:function(value){var targetobject=this.featureImage;if(targetobject.filters&&targetobject.filters[0]){if(typeof targetobject.filters[0].opacity=="number"){targetobject.filters[0].opacity=value*100;}else{targetobject.style.filter="alpha(opacity="+value*100+")";}}else if(typeof targetobject.style.MozOpacity!="undefined"){targetobject.style.MozOpacity=value;}else if(typeof targetobject.style.opacity!="undefined"){targetobject.style.opacity=value;}else{this.stopanimation();}},opacityanimation:function(){this.setimgopacity(this.currentopacity);this.currentopacity+=0.1;if(this.currentopacity>1){this.stopanimation();}},stopanimation:function(){if(typeof this.opacitytimer!="undefined"){clearInterval(this.opacitytimer);}},fitImageToWindow:function(){var size=HMUtils.getViewportDimensions();if(this.originalDimensions.width>size.width-40||this.originalDimensions.height>size.height-50){var xscale=(size.width-40.0)/this.originalDimensions.width;var yscale=(size.height-50.0)/this.originalDimensions.height;var scale=Math.min(xscale,yscale);this.featureImage.width=this.originalDimensions.width*scale;this.featureImage.height=this.originalDimensions.height*scale;}else{this.featureImage.width=this.originalDimensions.width;this.featureImage.height=this.originalDimensions.height;}},closeit:function(){if(!this._initialized){return;}
this.stopanimation();HMUtils.stopObserving(window,"resize",this.fitImageToWindowBind);this.thumbBox.style.visibility="hidden";this.thumbLoading.style.visibility="hidden";this.thumbImage.innerHTML="";var thumbOverlay=document.getElementById('thumbOverlay');thumbOverlay.style.display='none';thumbOverlay.style.opacity='0';},cleanup:function(){if(!this._initialized){return;}
this.thumbLoading=null;if(this.featureImage){this.featureImage.onload=null;}
this.featureImage=null;this.thumbImage=null;for(var i=0;i<this.targetlinks.length;i++){this.targetlinks[i].onclick=null;}
this.thumbBox=null;},init:function(){this.onThumbnailClickBind=HMDelegate.create(this,this.onThumbnailClick);this.opacityanimationBind=HMDelegate.create(this,this.opacityanimation);this.fitImageToWindowBind=HMDelegate.create(this,this.fitImageToWindow);this.featureImageLoadBind=HMDelegate.create(this,this.featureImageLoad);this.featureImageLoadErrorBind=HMDelegate.create(this,this.featureImageLoadError);this.featureImageTimeoutBind=HMDelegate.create(this,this.featureImageTimeout);this.onPageLinkClickBind=HMDelegate.create(this,this.onPageLinkClick);if(!this.enableAnimation){this.opacitystring="";}
var pagelinks=document.getElementsByTagName("a");var pagelink;var rel;var n=pagelinks.length;for(var i=0;i<n;i++){pagelink=pagelinks[i];rel=pagelink.getAttribute("rel");if(rel&&rel=="thumbnail"){pagelink.onclick=this.onPageLinkClickBind;this.targetlinks[this.targetlinks.length]=pagelinks[i];}}
HMUtils.observe(window,"resize",HMDelegate.create(this,this.onResize));},onPageLinkClick:function(source){this.stopanimation();this.loadimage(source);return false;},onResize:function(){if(this.thumbBox.style.visibility=="visible"){this.centerDiv(this.thumbBox);}},initForThumbnailLinks:function(){if(!this._initialized){this.createThumbBox();this.init();this._initialized=true;}
var links=document.getElementsByTagName('a');var link;var n=links.length;for(var i=0;i<n;i++){link=links[i];if(link.rel=="thumbnail"){link.onclick=this.onThumbnailClickBind;}}},onThumbnailClick:function(source,e){var event=e||window.event;event.cancelBubble=true;if(event.stopPropagation)event.stopPropagation();this.openForLink(source);return false;},openForLink:function(link){this.stopanimation();this.loadimage(link);}};HMUtils.observe(window,"unload",HMUtils.bind(HMThumbnailViewer,'cleanup'));var MouseBoundaryCrossing=function(){};MouseBoundaryCrossing.prototype.update=function(evt,landmark){evt=evt||window.event;var eventType=evt.type;this.landmark=landmark;this.inLandmark=false;this.leftLandmark=false;this.enteredLandmark=false;switch(eventType){case'mouseout':this.toElement=evt.relatedTarget||evt.toElement;this.fromElement=evt.target||evt.srcElement;break;case'mouseover':this.toElement=evt.target||evt.srcElement;this.fromElement=evt.relatedTarget||evt.fromElement;break;default:throw(new Error('Event type "'+eventType+'" is irrelevant'));}
if(!this.toElement||!this.fromElement){throw(new Error('Event target(s) undefined'));}
var from=this.findLandmark(this.fromElement);var to=this.findLandmark(this.toElement);if(from==landmark&&to==landmark){this.inLandmark=true;}
else if(from==landmark&&to!=landmark){this.leftLandmark=true;this.inLandmark=(eventType=="mouseout");}
else if(from!=landmark&&to==landmark){this.enteredLandmark=true;this.inLandmark=(eventType=="mouseover");}};MouseBoundaryCrossing.prototype.findLandmark=function(element){var tmp=element;while(this.loopCondition(tmp)){if(tmp==this.landmark)return tmp;tmp=tmp.parentNode;}};MouseBoundaryCrossing.prototype.loopCondition=function(element){var result;try{result=(element.nodeType==1);}
catch(e){result=false}
return result;};var PolylineEncoder=function(numLevels,zoomFactor,verySmall,forceEndpoints){var i;if(!numLevels){numLevels=18;}
if(!zoomFactor){zoomFactor=2;}
if(!verySmall){verySmall=0.00001;}
if(!forceEndpoints){forceEndpoints=true;}
this.numLevels=numLevels;this.zoomFactor=zoomFactor;this.verySmall=verySmall;this.forceEndpoints=forceEndpoints;this.zoomLevelBreaks=new Array(numLevels);for(i=0;i<numLevels;i++){this.zoomLevelBreaks[i]=verySmall*Math.pow(zoomFactor,numLevels-i-1);}}
PolylineEncoder.prototype.dpEncode=function(points){var absMaxDist=0;var stack=[];var dists=new Array(points.length);var maxDist,maxLoc,temp,first,last,current;var i,encodedPoints,encodedLevels;var segmentLength;if(points.length>2){stack.push([0,points.length-1]);while(stack.length>0){current=stack.pop();maxDist=0;segmentLength=Math.pow(points[current[1]].lat()-points[current[0]].lat(),2)+
Math.pow(points[current[1]].lng()-points[current[0]].lng(),2);for(i=current[0]+1;i<current[1];i++){temp=this.distance(points[i],points[current[0]],points[current[1]],segmentLength);if(temp>maxDist){maxDist=temp;maxLoc=i;if(maxDist>absMaxDist){absMaxDist=maxDist;}}}
if(maxDist>this.verySmall){dists[maxLoc]=maxDist;stack.push([current[0],maxLoc]);stack.push([maxLoc,current[1]]);}}}
encodedPoints=this.createEncodings(points,dists);encodedLevels=this.encodeLevels(points,dists,absMaxDist);return{encodedPoints:encodedPoints,encodedLevels:encodedLevels,encodedPointsLiteral:encodedPoints.replace(/\\/g,"\\\\")}}
PolylineEncoder.prototype.dpEncodeToJSON=function(points,color,weight,opacity){var result;if(!opacity){opacity=0.9;}
if(!weight){weight=3;}
if(!color){color="#0000ff";}
result=this.dpEncode(points);return{color:color,weight:weight,opacity:opacity,points:result.encodedPoints,levels:result.encodedLevels,numLevels:this.numLevels,zoomFactor:this.zoomFactor}}
PolylineEncoder.prototype.dpEncodeToGPolyline=function(points,color,weight,opacity){if(!opacity){opacity=0.9;}
if(!weight){weight=3;}
if(!color){color="#0000ff";}
return new GPolyline.fromEncoded(this.dpEncodeToJSON(points,color,weight,opacity));}
PolylineEncoder.prototype.dpEncodeToGPolygon=function(pointsArray,boundaryColor,boundaryWeight,boundaryOpacity,fillColor,fillOpacity,fill,outline){var i,boundaries;if(!boundaryColor){boundaryColor="#0000ff";}
if(!boundaryWeight){boundaryWeight=3;}
if(!boundaryOpacity){boundaryOpacity=0.9;}
if(!fillColor){fillColor=boundaryColor;}
if(!fillOpacity){fillOpacity=boundaryOpacity/3;}
if(fill==undefined){fill=true;}
if(outline==undefined){outline=true;}
boundaries=new Array(0);for(i=0;i<pointsArray.length;i++){boundaries.push(this.dpEncodeToJSON(pointsArray[i],boundaryColor,boundaryWeight,boundaryOpacity));}
return new GPolygon.fromEncoded({polylines:boundaries,color:fillColor,opacity:fillOpacity,fill:fill,outline:outline});}
PolylineEncoder.prototype.distance=function(p0,p1,p2,segLength){var u,out;if(p1.lat()===p2.lat()&&p1.lng()===p2.lng()){out=Math.sqrt(Math.pow(p2.lat()-p0.lat(),2)+Math.pow(p2.lng()-p0.lng(),2));}
else{u=((p0.lat()-p1.lat())*(p2.lat()-p1.lat())+(p0.lng()-p1.lng())*(p2.lng()-p1.lng()))/segLength;if(u<=0){out=Math.sqrt(Math.pow(p0.lat()-p1.lat(),2)+Math.pow(p0.lng()-p1.lng(),2));}
if(u>=1){out=Math.sqrt(Math.pow(p0.lat()-p2.lat(),2)+Math.pow(p0.lng()-p2.lng(),2));}
if(0<u&&u<1){out=Math.sqrt(Math.pow(p0.lat()-p1.lat()-u*(p2.lat()-p1.lat()),2)+
Math.pow(p0.lng()-p1.lng()-u*(p2.lng()-p1.lng()),2));}}
return out;}
PolylineEncoder.prototype.createEncodings=function(points,dists){var i,dlat,dlng;var plat=0;var plng=0;var encoded_points="";for(i=0;i<points.length;i++){if(dists[i]!=undefined||i==0||i==points.length-1){var point=points[i];var lat=point.lat();var lng=point.lng();var late5=Math.floor(lat*1e5);var lnge5=Math.floor(lng*1e5);dlat=late5-plat;dlng=lnge5-plng;plat=late5;plng=lnge5;encoded_points+=this.encodeSignedNumber(dlat)+
this.encodeSignedNumber(dlng);}}
return encoded_points;}
PolylineEncoder.prototype.computeLevel=function(dd){var lev;if(dd>this.verySmall){lev=0;while(dd<this.zoomLevelBreaks[lev]){lev++;}
return lev;}}
PolylineEncoder.prototype.encodeLevels=function(points,dists,absMaxDist){var i;var encoded_levels="";if(this.forceEndpoints){encoded_levels+=this.encodeNumber(this.numLevels-1)}else{encoded_levels+=this.encodeNumber(this.numLevels-this.computeLevel(absMaxDist)-1)}
for(i=1;i<points.length-1;i++){if(dists[i]!=undefined){encoded_levels+=this.encodeNumber(this.numLevels-this.computeLevel(dists[i])-1);}}
if(this.forceEndpoints){encoded_levels+=this.encodeNumber(this.numLevels-1)}else{encoded_levels+=this.encodeNumber(this.numLevels-this.computeLevel(absMaxDist)-1)}
return encoded_levels;}
PolylineEncoder.prototype.encodeNumber=function(num){var encodeString="";var nextValue,finalValue;while(num>=0x20){nextValue=(0x20|(num&0x1f))+63;encodeString+=(String.fromCharCode(nextValue));num>>=5;}
finalValue=num+63;encodeString+=(String.fromCharCode(finalValue));return encodeString;}
PolylineEncoder.prototype.encodeSignedNumber=function(num){var sgn_num=num<<1;if(num<0){sgn_num=~(sgn_num);}
return(this.encodeNumber(sgn_num));}
PolylineEncoder.latLng=function(y,x){this.y=y;this.x=x;}
PolylineEncoder.latLng.prototype.lat=function(){return this.y;}
PolylineEncoder.latLng.prototype.lng=function(){return this.x;}
PolylineEncoder.pointsToLatLngs=function(points){var i,latLngs;latLngs=new Array(0);for(i=0;i<points.length;i++){latLngs.push(new PolylineEncoder.latLng(points[i][0],points[i][1]));}
return latLngs;}
PolylineEncoder.pointsToGLatLngs=function(points){var i,gLatLngs;gLatLngs=new Array(0);for(i=0;i<points.length;i++){gLatLngs.push(new GLatLng(points[i][0],points[i][1]));}
return gLatLngs;}
var CookieScript={getCookie:function(check_name){var a_all_cookies=document.cookie.split(';');var a_temp_cookie='';var cookie_name='';var cookie_value='';var b_cookie_found=false;for(i=0;i<a_all_cookies.length;i++)
{a_temp_cookie=a_all_cookies[i].split('=');cookie_name=a_temp_cookie[0].replace(/^\s+|\s+$/g,'');if(cookie_name==check_name)
{b_cookie_found=true;if(a_temp_cookie.length>1)
{cookie_value=unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g,''));}
return cookie_value;break;}
a_temp_cookie=null;cookie_name='';}
if(!b_cookie_found)
{return null;}},setCookie:function(name,value,expires,path,domain,secure){var today=new Date();today.setTime(today.getTime());if(expires)
{expires=expires*1000*60*60*24;}
var expires_date=new Date(today.getTime()+(expires));document.cookie=name+"="+escape(value)+
((expires)?";expires="+expires_date.toGMTString():"")+
((path)?";path="+path:"")+
((domain)?";domain="+domain:"")+
((secure)?";secure":"");},deleteCookie:function(name,path,domain){if(CookieScript.getCookie(name)){document.cookie=name+"="+
((path)?";path="+path:"")+
((domain)?";domain="+domain:"")+";expires=Thu, 01-Jan-1970 00:00:01 GMT";}}};function HMColorMarkerClusterer(map,markers,options){this._map=map;this._markerClusterers={};this.options=options;}
HMColorMarkerClusterer.prototype.addMarkers=function(markers){var colorMarkers={};for(var i in markers){var color=markers[i].color;if(color!==undefined){if(!colorMarkers.hasOwnProperty(color)){colorMarkers[color]=[];}
colorMarkers[color].push(markers[i]);}}
this.clearMarkers();for(var c in colorMarkers){this._addColorMarkers(c,colorMarkers[c]);}};HMColorMarkerClusterer.prototype._addColorMarkers=function(color,colorMarkers){if(!this._markerClusterers.hasOwnProperty(color)){this.options.styles=[{url:HABITATMAP_URL+'/images/markers/'+color+'_cluster.png',height:40,width:31,opt_textColor:'white',opt_textSize:14}];this._markerClusterers[color]=new HMMarkerClusterer(this._map,colorMarkers,this.options);}else{this._markerClusterers[color].addMarkers(colorMarkers);}};HMColorMarkerClusterer.prototype.clearMarkers=function(){for(var c in this._markerClusterers){this._markerClusterers[c].clearMarkers();}};HMColorMarkerClusterer.prototype.removeMarker=function(marker){var mc=this._markerClusterers[marker.color];if(mc){mc.removeMarker(marker);}};var Layers={URL:"/layers",index:function(options){options=options||{};var requestOptions={parameters:options.parameters,onSuccess:function(xhr){options.onSuccess&&options.onSuccess(HMLayer.createFromJSON(xhr.responseJSON))},onError:options.onError,onFailure:options.onFailure};Requester.get(Layers.URL,requestOptions);},show:function(options){options=options||{};var requestOptions={onSuccess:function(xhr){options.onSuccess&&options.onSuccess(HMLayer.createFromJSON([xhr.responseJSON])[0]);},onError:options.onError,onFailure:options.onFailure};Requester.get(Layers.URL+"/"+options.parameters.id,requestOptions);},destroy:function(layer,options){Requester.Delete(Layers.URL+"/"+layer.getId(),options);}};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();}
var HMPolygonExtensions={hmInstallExtensions:function(){if(window.HMUtils&&window.GPolyline&&window.GPolygon&&!this._installed){this._installed=true;HMUtils.extend(HMUtils.extend(GPolyline.prototype,this),{_getTooltipLocation:function(){return this.getVertex(0);}});HMUtils.extend(HMUtils.extend(GPolygon.prototype,this),{_getTooltipLocation:function(){return this.getBounds().getCenter();}});}},getVertices:function(){var count=this.getVertexCount();var array=new Array(count);for(var i=0;i<count;i++){array[i]=this.getVertex(i);}
return array;}};HMPolygonExtensions.hmInstallExtensions();var HMLayer=function(properties,polies){this.properties=properties;this.polies=polies;HMUtils.each(polies,function(poly){poly.layer=this},this);};HMLayer.createFromJSON=function(json){return HMUtils.collect(json,function(layer){var polies=HMUtils.collect(layer.polies,function(poly){var p,polylineProperties={color:layer.color,weight:layer.weight,opacity:layer.opacity/100,points:poly.encoded_points,levels:poly.encoded_levels,zoomFactor:2,numLevels:18};if(poly.type=="Polyline"){p=new GPolyline.fromEncoded(polylineProperties);}
else if(poly.type=="Polygon"){p=new GPolygon.fromEncoded({polylines:[polylineProperties],fill:true,outline:true,color:layer.fill_color,opacity:layer.fill_opacity/100});}
else{throw"wrong poly type";}
return p;});delete layer.polies;return new HMLayer(layer,polies);});};HMUtils.extend(HMLayer.prototype,{displayOnIndex:function(){return this.properties.display_on_index;},isEditable:function(){return this.properties.editable;},isLines:function(){return this.properties.lines;},getId:function(){return this.properties.id;},getMapId:function(){return this.properties.map_id;},getName:function(){return this.properties.name;},getFillColor:function(){return this.properties.fill_color},getColor:function(){return this.properties.color;}});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 HMMarkerIndex=HMClass.extend({init:function(indexDiv,map,options){this._div=$(indexDiv);this._eachMapIdDelegate=$D(this,this._eachMapId);this._filterLayersDelegate=$D(this,this._filterLayers);this._eachLayerDelegate=$D(this,this._eachLayer);this._addMarkerClassNameDelegate=$D(this,this._addMarkerClassName);this._markerKeyCount=$('markerKeyCount');this._layersDiv=(new Element('div',{id:'layers_list'}));this._layersDiv.hide();this._div.insert({top:this._layersDiv});this._map=map;this._clickHandler=options&&options.clickHandler;},clearMarkers:function(){this._div.childElements().reject(function(e){return(/layer/).test(e.id)}).invoke('remove');},clearLayers:function(){this._layersDiv.update('');this._layersDiv.hide();},clearAll:function(){this.clearLayers();this.clearMarkers();},setMarkerKeyCount:function(n){this._markerKeyCount.update(n);},insertLayers:function(layers){layers.reverse(false).select(this._filterLayersDelegate).each(this._eachLayerDelegate);this._refreshMarkerColors();this._layersDiv.show();},_filterLayers:function(source,layer){return layer.displayOnIndex();},_eachLayer:function(source,layer){var templateName=layer.isLines()?'LINES_LAYER_TEMPLATE':'SHAPE_LAYER_TEMPLATE';var template=HMMarkerIndex[templateName];var properties=$H(layer.properties).toObject();if(!Prototype.Browser.IE){properties.opacity/=100;properties.fill_opacity/=100;}
var element,before=this._layersDiv.childElements().find(function(i){return i.down('.name').innerHTML.toLowerCase()>layer.getName().toLowerCase();});element=before?before.insert({before:template.evaluate(properties)}).previous():this._layersDiv.insert({bottom:template.evaluate(properties)}).childElements().last();element.observe('click',$D(this,this._onLayerClick,layer));},_onLayerClick:function(source,layer,event){if(layer.isEditable()){EditLayerModalbox.editLayer(layer,this._map.getLocation());}},removeLayer:function(layer){var entry=$("layer_"+layer.getId());if(entry){entry.remove();}},refreshLayer:function(layer){var element=$("layer_"+layer.getId());if(element){element.down('.layer_color').setStyle({backgroundColor:layer.getFillColor(),border:"1px solid "+layer.getColor()}).next('.layer_name').update(layer.getName());}else{this.insertLayers([layer]);}},insertListElements:function(markers){markers.each(this._insertListElement,this);this._refreshMarkerIndex();},insertListElement:function(marker){this._insertListElement(marker);this._refreshMarkerIndex();},removeListElementWithId:function(id){$$('div#marker_list_element_'+id+', div[id^=marker_list_element_'+id+'_]').invoke('remove');this._refreshMarkerIndex();},removeAllListElements:function(){$$('div.marker_list_element').invoke('remove');},unselectMarkerNames:function(){$$('#markers_list div span').invoke('removeClassName','selected');},reinitialize:function(mapIds){this.clearMarkers();HMUtils.each($A(mapIds).sort(),this._reinitializeMarkerListGroup,this);},_reinitializeMarkerListGroup:function(i){this._div.insert({bottom:HMMarkerIndex.MAP_BLOCK_TEMPLATE.evaluate({id:i})});},_eachMapId:function(source,marker,id){var element=$('marker_list_group_'+id);if(element){this._insertListElement(marker,element);}},_insertListElement:function(marker,target){if(!target||typeof target=="number"){var ids=marker.assigned_map_ids;if(ids){this._eachMapIdDelegate.delegate.args=[marker];ids.each(this._eachMapIdDelegate);return;}else{target=this._div;}}
var resultMarker;if(target.hasClassName('marker_list_group')){var id=target.id;var group=parseInt(id.substring(id.lastIndexOf('_')+1),10);var markerCopy=marker.hmClone();markerCopy.assigned_map_ids=[group];markerCopy.id=marker.id+'_'+group;markerCopy.color=GMarker.hmGetMarkerColor(this._map.findColorForMarker(markerCopy));resultMarker=markerCopy;}else{resultMarker=marker;}
target.insert({bottom:HMMarkerIndex.MARKER_ITEM_TEMPLATE.evaluate(resultMarker)});var element=$('marker_list_element_'+resultMarker.id);element.observe('mouseover',marker.hmOpenStaticToolTip.bind(marker));element.observe('mouseout',marker.hmCloseToolTip.bind(marker));element.observe('click',$D(this,this._onMarkerClick,marker));},_onMarkerClick:function(source,marker,event){source.addClassName('selected');this._clickHandler&&this._clickHandler(marker);},_refreshMarkerIndex:function(){this._cleanUpMarkerGroups();this._refreshMarkerColors();},_refreshMarkerColors:function(){this._div.select('.item').invoke('removeClassName','odd').invoke('removeClassName','even').each(this._addMarkerClassNameDelegate);},_addMarkerClassName:function(source,element,i){var odd=Boolean(i%2);element.addClassName(odd?'odd':'even');if(element.hasClassName('line')){element.down().src='/images/map/line_layer_icon_'+(odd?'grey':'white')+'.png'}},_cleanUpMarkerGroups:function(){$$('#markers_list .marker_list_group').each(function(group){if(group.empty()){group.remove();}});var lastGroup=$$('#markers_list .marker_list_group').last();if(lastGroup){lastGroup.addClassName('last');}}});HMUtils.extend(HMMarkerIndex,{MARKER_ITEM_TEMPLATE:new Template('<div class="item odd clearfix" id="marker_list_element_#{id}">'+'<img class="icon" src="'+HABITATMAP_URL+'/images/markers/#{color}_mapkey.png" alt="Marker_key_icon"/>'+'<span class="name">#{name}</span>'+'</div>'),MAP_BLOCK_TEMPLATE:new Template('<div id="marker_list_group_#{id}" class="marker_list_group"></div>'),SHAPE_LAYER_TEMPLATE:new Template('<div id="layer_#{id}" class="item shape odd clearfix">'+'<span class="icon" style="border-color: #{color}; background-color:#{fill_color}; '+'opacity: #{fill_opacity}; filter: alpha(opacity=#{fill_opacity})">&nbsp;</span>'+'<span class="name">#{name}</span>'+'</div>'),LINES_LAYER_TEMPLATE:new Template('<div id="layer_#{id}" class="item line layer odd clearfix">'+'<img class="icon" src="/images/map/line_layer_icon_white.png" style="background-color: #{color}; '+'opacity: #{opacity}; filter: alpha(opacity=#{opacity});"/>'+'<span class="name">#{name}</span>'+'</div>')});var HMMapIndex=HMClass.extend({_selectedMaps:[],_mapColors:{},_usedColors:[],init:function(indexDiv,map,options){this._div=$(indexDiv);this._mapKeyCount=$('mapKeyCount');this._map=map;this._options=options||{};this.onLabelClickedDelegate=$D(this,this._onLabelClick);this.onInputClickedDelegate=$D(this,this._onInputClick);this.onItemMouseOutDelegate=$D(this,this._onItemMouseOut);this.onBoxMouseOverDelegate=$D(this,this._onBoxMouseOver);this.itemToBoxDelegate=$D(this,this._itemToBox);this.itemToLabelDelegate=$D(this,this._itemToLabel);this.itemToInputDelegate=$D(this,this._itemToInput);this.itemToTooltipDelegate=$D(this,this._itemToTooltip);this.currentTooltipItem=null;this.mbc=new MouseBoundaryCrossing();},getSelectedMaps:function(){return this._selectedMaps;},selectMapsWithColors:function(mapIds,colorIds){var mapsWithoutColor=[];var mapId,colorId,mapElement;this.reset();if(!colorIds){colorIds=[];}
for(var i=0;i<mapIds.length;i++){mapId=mapIds[i];colorId=colorIds[i];mapElement=this._div.down('#map_'+mapId);if(colorId!==undefined&&!this._usedColors[colorId]){this._selectMapWithColor(mapElement,mapId,colorId);}else{mapsWithoutColor.push(mapElement||mapId);}}
HMUtils.each(mapsWithoutColor,this.selectMap,this);},selectMap:function(mapElement){if(typeof mapElement=="number"){this._selectFreeColorForMap(mapElement);this._selectedMaps.push(mapElement);}else{var id=this._getMapElementId(mapElement);this._selectFreeColorForMap(id);this._selectedMaps.push(id);this._setMapSelection(mapElement,true);}},_selectMapWithColor:function(mapElement,mapId,colorId){this._usedColors[colorId]=true;this._mapColors[mapId]=colorId;this._selectedMaps.push(mapId);if(mapElement){this._setMapSelection(mapElement,true);}},selectOnlyMap:function(mapElement){var otherMaps=this._getAllMapListElements().reject(function(elem){return elem==mapElement});otherMaps.each(this.unselectMap.bind(this));var id=this._getMapElementId(mapElement);this._selectedMaps=[id];this._mapColors={};this._usedColors=[];this._selectFreeColorForMap(id);this._setMapSelection(mapElement,true);},unselectMap:function(mapElement){var id=this._getMapElementId(mapElement);this._releaseMapColor(id);this._setMapSelection(mapElement,false);this._selectedMaps.remove(id);},reset:function(){this._selectedMaps=[];this._mapColors={};this._usedColors=[];},clear:function(){this.reset();this._div.innerHTML="";this.setMapKeyCount(0);},getColorForMap:function(mapId){return this._mapColors[mapId];},_showTooltip:function(item){var tooltip=item.down('.tooltip');var tooltipShadow=tooltip.previous();var offset=item.cumulativeOffset();var tooltipLeft=offset[0]-354;var tooltipTop=offset[1]-24-item.up().scrollTop;tooltip.setStyle({top:tooltipTop+'px',left:tooltipLeft+'px'});tooltipShadow.setStyle({top:(tooltipTop-3)+'px',left:(tooltipLeft-3)+'px'});tooltipShadow.down().setStyle({height:(tooltip.getHeight()-20)+'px'});tooltip.show();tooltipShadow.show();if(this.currentTooltipItem&&this.currentTooltipItem!=item){this._hideTooltip(this.currentTooltipItem);}
this.currentTooltipItem=item;},_hideTooltip:function(item){var tooltip=item.down('.tooltip');tooltip.hide();tooltip.previous().hide();},_itemToBox:function(source,item){return item.down('.box');},_itemToLabel:function(source,item){return item.down('label');},_itemToInput:function(source,item){return item.down('input');},_itemToTooltip:function(source,item){return item.down('.tooltip');},_attachMapListEvents:function(items){items=items||this._div.select('.item');var boxes=items.map(this.itemToBoxDelegate);var labels=items.map(this.itemToLabelDelegate);var inputs=items.map(this.itemToInputDelegate);var tooltips=items.map(this.itemToTooltipDelegate);items.invoke('observe','mouseout',this.onItemMouseOutDelegate);labels.invoke('observe','click',this.onLabelClickedDelegate);inputs.invoke('observe','click',this.onInputClickedDelegate);boxes.invoke('observe','mouseover',this.onBoxMouseOverDelegate);},_onLabelClick:function(label,event){var item=label.up('.item');this.selectOnlyMap(item);this._onItemClick(item);},_onInputClick:function(input,event){var item=input.up('.item');if(input.checked){this.selectMap(item);}else{this.unselectMap(item);}
this._onItemClick(item);},_onItemClick:function(item){this._hideTooltip(item);this._map.requestDataForMaps(this._selectedMaps);},_onBoxMouseOver:function(box,event){this.mbc.update(event,box);if(this.mbc.enteredLandmark){this._showTooltip(box.up('.item'));}},_onItemMouseOut:function(item,event){this.mbc.update(event,item);if(this.mbc.leftLandmark){this._hideTooltip(item);}},_setMapSelection:function(mapElement,selected){var box=mapElement.down('.box');var name=box.down('label');var checkbox=box.down('input');checkbox.checked=selected;if(selected&&box.hasClassName('withMarkers')){var id=checkbox.value;var colorName=this._getColorName(this._mapColors[id]);var imageUrl=HABITATMAP_URL+'/images/markers/'+colorName+'_mapkey.png';var background='url('+imageUrl+') no-repeat 98% center';box.setStyle({background:background});}
else{box.setStyle({background:'none'});}},_selectFreeColorForMap:function(mapId){var colorPos=0;while(this._usedColors[colorPos]){colorPos++;}
this._usedColors[colorPos]=true;this._mapColors[mapId]=colorPos;return this._getColorName(colorPos);},_releaseMapColor:function(mapId){var color=this._mapColors[mapId];if(color===undefined){return;}
delete this._mapColors[mapId];this._usedColors[color]=false;},_getColorName:function(colorNum){return GMarker.HABITATMAP_MARKER_COLORS[colorNum%GMarker.HABITATMAP_MARKER_COLORS.length];},_getAllMapListElements:function(){return this._div.select('.item');},_getMapElementId:function(element){return element.down('input').value;},setMapKeyCount:function(n){this._mapKeyCount.update(n);},resetScroll:function(){this._div.scrollTop=0;}});var HMExtendedMapIndex=HMMapIndex.extend({init:function(indexDiv,map,options){this._super(indexDiv,map,options);this.onDrawLinesDelegate=$D(this,this.onDrawLines);this.onDeleteMapDelegate=$D(this,this.onDeleteMap);this.onAddToSharedMapsDelegate=$D(this,this.onAddToSharedMaps);this.onAddToSharedMapsCreateDelegate=$D(this,this.onAddToSharedMapsCreate);this.onAddToSharedMapsCompleteDelegate=$D(this,this.onAddToSharedMapsComplete);this.onAddToSharedMapsSuccessDelegate=$D(this,this.onAddToSharedMapsSuccess);},show:function(){this._div.setStyle({visibility:'visible'});},hide:function(){this._div.setStyle({visibility:'hidden'});},reloadContents:function(html){this._div.update(html);var elements=this._div.childElements();var firstElement=this._div.firstDescendant();var updateElementsBind=this._updateElements.bind(this);if(elements.empty()||elements.first().hasClassName('noResults')){this.setMapKeyCount(0);}else{elements.each(updateElementsBind);this._attachMapListEvents();this.setMapKeyCount(elements.length);}},displayTheHabitatMap:function(){var img=HABITATMAP_URL+'/images/markers/orange_mapkey.png';this._div.update('<div class="clearfix item odd the_habitatmap">'+'<div class="box clearfix withMarkers selected" style="background: url('+img+') no-repeat 98% center;">'+'<input type="checkbox" class="map_checkbox" checked="checked" disabled="disabled" />'+'<label>The HabitatMap</label>'+'</div>'+'</div>');this.setMapKeyCount(1);},deleteMap:function(element){var url=element.href;var successHandler=function(){var entry=element.up('.item');var checkbox=entry.down('input');if(checkbox.checked){this.unselectMap(entry);this._map.requestDataForMaps(this._selectedMaps);}
entry.remove();this._refreshMapListColors();}.bind(this);Requester.Delete(url,{onSuccess:successHandler,onFailure:function(xhr){HMUtils.error(xhr.responseText)}});},getColorList:function(){var colors=this._mapColors;return HMUtils.collect(this._selectedMaps,function(mapId){return colors[mapId]});},_updateElements:function(element){this._refreshMapEntryColor(element);if(!element.hasClassName('pagination')&&this._selectedMaps.include(this._getMapElementId(element))){this._setMapSelection(element,true);}},_reloadElement:function(element,html){element.replace(html);element=$(element.id);this._refreshMapEntryColor(element);this._attachMapListEvents([element]);if(this._selectedMaps.include(this._getMapElementId(element))){this._setMapSelection(element,true);}
return element;},_attachMapListEvents:function(items){this._super(items);$$('.tooltip a.draw_lines').invoke('observe','click',this.onDrawLinesDelegate);$$('.tooltip a.delete_map').invoke('observe','click',this.onDeleteMapDelegate);$$('.tooltip a.add_to_shared_maps').invoke('observe','click',this.onAddToSharedMapsDelegate);},onDrawLines:function(source,event){event.stop();this._showDrawLines(source);this._hideTooltip(source.up('.item'));},_showDrawLines:function(element){var href=element.href;var mapId=(/(?:maps\/)(\d+)(?:\/layers)/).exec(href)[1];EditLayerModalbox.show(href,Object.extend({mapId:mapId},this._map.getLocation()));},onDeleteMap:function(source,event){event.stop();if(confirm("Are you sure?")){this.deleteMap(source);}},onAddToSharedMaps:function(source,event){event.stop();this.onAddToSharedMapsCreateDelegate.delegate.args=this.onAddToSharedMapsCompleteDelegate.delegate.args=this.onAddToSharedMapsSuccessDelegate.delegate.args=[source];Requester.post(source.href,{onCreate:this.onAddToSharedMapsCreateDelegate,onComplete:this.onAddToSharedMapsCompleteDelegate,onSuccess:this.onAddToSharedMapsSuccessDelegate});},onAddToSharedMapsCreate:function(source,link){link.hide();link.next().show();},onAddToSharedMapsComplete:function(source,link){link.next().hide();},onAddToSharedMapsSuccess:function(source,link,xhr){var item=link.up('.item');var name=item.down('label').innerHTML;this._hideTooltip(item);item=this._reloadElement(item,xhr.responseText);this._showTooltip(item);$info('&ldquo;'+name+'&rdquo; has been added to your shared maps.');},_refreshMapEntryColor:function(element){var className=(!element.previous()||element.previous().hasClassName('even'))?'odd':'even';element.addClassName(className);element.removeClassName(className=='even'?'odd':'even');},_refreshMapListColors:function(){this._div.select('.item').each(this._refreshMapEntryColor);}});if(!window.HMMapWithPanels){var HMMapWithPanels=HMMap.extend({init:function(mapDiv,options){options=options||{};this._super(mapDiv,options);var $D=HMDelegate.create;this.onLayersSuccessDelegate=$D(this,this.onLayersSuccess);this.onDataForMapsSuccessDelegate=$D(this,this.onDataForMapsSuccess);this.requestingMarkers=false;this.requestingLayers=false;this.dontZoomAfterMarkerLoad=false;if(options.markerIndexDiv){var handlers=options.handlers;this._markerIndex=new HMMarkerIndex(options.markerIndexDiv,this,{clickHandler:handlers&&handlers.click});}
if(options.mapIndexDiv){var MapClass=(options.mapIndexFullVersion)?HMExtendedMapIndex:HMMapIndex;this._mapIndex=new MapClass(options.mapIndexDiv,this);}},setDisplayLines:function(display,dontZoom){this._super(display,dontZoom);this.getMarkerIndex().clearLayers();if(this._displayLines){this.requestLayers(this.getMapIndex().getSelectedMaps(),true);}
else{this.clearPolies();}},getMarkerIndex:function(){return this._markerIndex;},getMapIndex:function(){return this._mapIndex;},addMarkers:function(markers){var markerIndex=this.getMarkerIndex();this._super(markers);if(markerIndex){this.updateMarkerKeyCount();markerIndex.insertListElements(markers);}},removeMarker:function(id){var markerIndex=this.getMarkerIndex();var removed=this._super(id);if(markerIndex){this.updateMarkerKeyCount();markerIndex.removeListElementWithId(id);}
return removed;},clear:function(){this._super();this.getMarkerIndex().clearAll();this.getMapIndex().clear();},clearMarkers:function(){this._super();var markerIndex=this.getMarkerIndex();if(markerIndex){this.updateMarkerKeyCount();markerIndex.removeAllListElements();}},findColorForMarker:function(markerJSON){var mapIndex=this.getMapIndex();var ids=markerJSON.assigned_map_ids;if(ids&&mapIndex){var c=mapIndex.getColorForMap(ids[0])||0;return c%GMarker.HABITATMAP_MARKER_COLORS.length;}},requestDataForMaps:function(mapIds){this.getMarkerIndex().clearLayers();this.clearPolies();if(mapIds.empty()){this.clearMarkers();}else{this.requestingMarkers=true;this.onDataForMapsSuccessDelegate.delegate.args=[mapIds];Markers.markerSearch.request({parameters:{maps:mapIds.join()},onSuccess:this.onDataForMapsSuccessDelegate,counter:'leave'});if(this._displayLines){this.requestLayers(mapIds);}}},onDataForMapsSuccess:function(source,mapIds,xhr){var markers=xhr.responseJSON.markers;var markerIndex=this.getMarkerIndex();this.requestingMarkers=false;if(markers.empty()){HMUtils.info(((mapIds.length>1)?'These maps have':'This map has')+' no markers assigned.');markerIndex.clearMarkers();this.clearMarkers();}else{markerIndex.reinitialize(mapIds);this.updateMarkersFromJSON(markers);}
if(!this.requestingLayers&&!this.dontZoomAfterMarkerLoad){this.autoZoom();}},addLayers:function(layers){var markerIndex=this.getMarkerIndex();if(markerIndex){markerIndex.insertLayers(layers);}
this._super(layers);},requestLayers:function(mapsIds,dontZoomAfterMarkerLoad){var errorCallback=HMUtils.errorMessage("while requesting layers.");var controller=(this._options.controllers&&this._options.controllers.layers)||Layers;this.requestingLayers=true;this.dontZoomAfterMarkerLoad=dontZoomAfterMarkerLoad;controller.index({parameters:{'maps_ids[]':mapsIds},onSuccess:this.onLayersSuccessDelegate,onError:errorCallback,onFailure:errorCallback});},onLayersSuccess:function(source,layers){this.requestingLayers=false;this.addLayers(layers);if(!this.requestingMarkers&&!this.dontZoomAfterMarkerLoad){this.autoZoom();}},removeLayer:function(layer){var markerIndex=this.getMarkerIndex();this._super(layer);if(markerIndex){markerIndex.removeLayer(layer);}},refreshLayer:function(layer){var markerIndex=this.getMarkerIndex();this._super(layer);if(markerIndex){markerIndex.refreshLayer(layer);}},onSearchSuccess:function(markers,location,radius,currentView){this.getMarkerIndex().clearAll();this._super(markers,location,radius,currentView);this.updateMarkerKeyCount();},updateMarkerKeyCount:function(){this.getMarkerIndex().setMarkerKeyCount(this._markers.length);}});}
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});var HMLinesMap=HMMap.extend({init:function(options){options=HMUtils.extend(options||{},{mapOptions:{size:new GSize(800,400)}});this._super('lines_map',options);this._mapId=options.mapId;this._layer=options.layer;this._currentPoly=null;this._class=null;this._strokeStyle=null;this._fillStyle=null;this._poliesBeingEdited=[];this._layerBeingEdited=null;this._encoder=new PolylineEncoder();this.onGetMarkersSuccessDelegate=$D(this,this._onGetMarkersSuccess);this.onGetLayersSuccessDelegate=$D(this,this._onGetLayersSuccess);this.enableVerticesEditingDelegate=$D(this,this._enableVerticesEditing);this.deleteVertexDelegate=$D(this,this._deleteVertex);this.encodePolyDelegate=$D(this,this._encodePoly);this.onMapClickedDelegate=$D(this,this._onMapClicked);this.gLatLngEqualityTestDelegate=$D(this,this._gLatLngEqualityTest);this.onDeleteShapeDelegate=$D(this,this._onDeleteShape);this.isLayerEditedDelegate=$D(this,this._isLayerEdited);this.endlineDelegate=$D(this,this._endline);this.mapClickedHandler=GEvent.addListener(this._map,'click',this.onMapClickedDelegate);this._getMarkers();this._getLayers();},setPolyClass:function(klass){this._class=klass;this._setPolyType();},setStrokeStyle:function(options){this._strokeStyle=options;this._getAllPolies().invoke('setStrokeStyle',this._strokeStyle);},setFillStyle:function(options){this._fillStyle=options;this._getAllPolies().select(function(p){return p instanceof GPolygon;}).invoke('setFillStyle',this._fillStyle);},isDrawing:function(){return Boolean(this._currentPoly);},empty:function(){return this._poliesBeingEdited.empty();},getEncoded:function(){return this._poliesBeingEdited.map(this.encodePolyDelegate);},_encodePoly:function(source,poly){var encoded=this._encode(poly.getVertices());return{encoded_points:encoded.encodedPoints,encoded_levels:encoded.encodedLevels,type:(poly instanceof GPolygon)?'Polygon':'Polyline'};},_encode:function(vertices){return this._encoder.dpEncode(vertices);},_setPolyType:function(){if(this.isDrawing()){this._map.removeOverlay(this._currentPoly);this._startDrawing(this._currentPoly.getVertices());}},_polyVertexClicked:function(poly,latLng){this._latLngForEqualityTest=latLng;return poly.getVertices().any(this.gLatLngEqualityTestDelegate);},_gLatLngEqualityTest:function(source,latLng){return latLng.equals(this._latLngForEqualityTest);},_polyClicked:function(poly,overlayLatLng){var vertexClicked=this._polyVertexClicked(poly,overlayLatLng);if(!vertexClicked){var deleteLink=(new Element('a',{href:'#'})).update('Delete line/shape');deleteLink.className='deleteLineShape';this.onDeleteShapeDelegate.delegate.args=[poly];deleteLink.onclick=this.onDeleteShapeDelegate;this._map.openInfoWindow(overlayLatLng,deleteLink);}},_onDeleteShape:function(source,poly){if(confirm('Are you sure?')){this._map.closeInfoWindow();this._map.removeOverlay(poly);this._poliesBeingEdited.remove(poly);if(this._poliesBeingEdited.empty()){GEvent.trigger(this,'last_layer_removed');}}},_lastVertexClicked:function(overlay){var poly=this._currentPoly;return(overlay instanceof GMarker)&&overlay.getLatLng().equals(poly.getVertex(poly.getVertexCount()-1));},_onMapClicked:function(source,overlay,latlng,overlayLatLng){if(overlay){if(this._isOverlayPoly(overlay)){if(this._isOverlayEdited(overlay)){this._polyClicked(overlay,overlayLatLng);}else{this._otherCase(latlng);}}
else if(this.isDrawing()&&this._isShapeNotValid(overlay)){$error('Polygon shape must have more than 2 vertices.');this._map.removeOverlay(this._currentPoly);this._currentPoly=null;}}else{this._otherCase(latlng);}},_isShapeNotValid:function(overlay){var poly=this._currentPoly;return this._lastVertexClicked(overlay)&&(poly instanceof GPolygon)&&poly.getVertexCount()<3;},_isOverlayPoly:function(overlay){return(overlay instanceof GPolygon)||(overlay instanceof GPolyline);},_isOverlayEdited:function(overlay){return this._poliesBeingEdited.include(overlay);},_otherCase:function(latlng){if(!this._class){$warning("Please select either Shape or Line");}else if(!this.isDrawing()){this._startDrawing(latlng);}},_startDrawing:function(latlngs){var poly=this._currentPoly=this._instantizePoly(latlngs);this._map.addOverlay(poly);poly.enableDrawing();GEvent.addListener(poly,'endline',this.endlineDelegate);if(this.empty()){GEvent.trigger(this,'first_layer_added');}},_endline:function(source){this._poliesBeingEdited.push(source);this.enableVerticesEditingDelegate.delay(1,source);this._currentPoly=null;},_getMapId:function(){return this._mapId||this._layer.getMapId();},_getMarkers:function(){new Ajax.Request('/markers.json?maps='+this._getMapId(),{method:'get',onSuccess:this.onGetMarkersSuccessDelegate,onFailure:$error.curry("Oops! Something went wrong!"),onError:$error.curry("Oops! Something went wrong!")});},_onGetMarkersSuccess:function(source,xhr){this.addMarkersFromJSON(xhr.responseJSON.markers);},_getLayers:function(){Layers.index({parameters:{maps_ids:this._getMapId()},onSuccess:this.onGetLayersSuccessDelegate});},_onGetLayersSuccess:function(source,layers){this._addLayers(this._layer,layers);},_addLayers:function(layerBeingEdited,layers){this._layerBeingEdited=layerBeingEdited;var forEditing=this._layerBeingEdited&&HMUtils.findFirstAndRemove(layers,this.isLayerEditedDelegate);this.addLayers(layers,true);if(forEditing){this._addPoliesForEditing(forEditing.polies);}},_isLayerEdited:function(source,layer){return layer.getId()==this._layerBeingEdited.getId();},_addPoliesForEditing:function(polies){this.addPolies(polies);this._poliesBeingEdited=polies;polies.each(this.enableVerticesEditingDelegate);},_enableVerticesEditing:function(source,poly){poly.enableEditing({onEvent:'mouseover'});poly.disableEditing({onEvent:'mouseout'});GEvent.addListener(poly,'click',this.deleteVertexDelegate);},_deleteVertex:function(source,latlng,index){if(typeof index=="number"){source.deleteVertex(index);}},_getAllPolies:function(){return this._poliesBeingEdited.concat(this._currentPoly).compact();},_instantizePoly:function(latlngs){var latlngsArr=Object.isArray(latlngs)?latlngs:[latlngs];var stroke=this._strokeStyle;var fill=this._fillStyle;return new this._class(latlngsArr,stroke.color,stroke.weight,stroke.opacity,fill&&fill.color,fill&&fill.opacity);}});if(!window.HMWidget){var HMWidget={WIDGET_FOOTER_WIDTH:21,initializeModalboxIfPossible:function(marker){var IE=!!(window.attachEvent&&navigator.userAgent.indexOf('Opera')===-1);if(IE){window.attachEvent('onload',function(){HMWidget._initializeModalbox(marker)});}else{HMWidget._initializeModalbox(marker);}},_initializeModalbox:function(marker){HMThumbnailViewer.initForThumbnailLinks();HMUtils.updateModalboxFootnotes();if(document.getElementById(HMSmallMap.SMALL_MAP_ID)){HMMarkerTooltip.init();new HMSmallMap({initialMarkerJSON:marker});}},initializeEnvironment:function(){this._insertStylesheets();HMMarkerTooltip.init();HMLyteBox.initLyteBox();},loadMap:function(divId){var mapData=HMWidgetInstance.maps[divId];var containingDiv=document.getElementById('habitatmap_widget_'+divId);if(!containingDiv||!mapData){return;}
containingDiv.innerHTML="";var centerColumn=this._createDiv('center_column');containingDiv.appendChild(centerColumn);var footer=this._createDiv('widget_footer');containingDiv.appendChild(footer);footer.innerHTML="<a href=\""+this._generateMapURL(divId)+"\">"+"Visit HabitatMap.org to contribute to this map</a>";var map=this._createDiv('map','habitatmap_map_'+divId);this._setMapDimensionsFromDiv(map,containingDiv);centerColumn.appendChild(map);mapData.mapInstance=new HMMapWithPanels(map,{handlers:{click:this._showMarkerModalbox},showPolyTooltips:true,defaultPosition:mapData,defaultZoom:mapData.zoom,mapControlSize:'small_zoom',mapType:HMMap.getMapTypeByName(mapData.mapType)});mapData.mapInstance.setMarkerGrouping(!mapData.nogrp);mapData.mapInstance.findColorForMarker=function(markerJSON){return HMWidget._findColorForMarker(divId,markerJSON);};this._initializeColorHash(mapData);this._addMarkersAndLayersToMap(divId);},_createDiv:function(divClass,divId){var div=document.createElement('div');if(divClass){div.className=divClass;}
if(divId){div.id=divId;}
return div;},_findColorForMarker:function(divId,markerJSON){if(markerJSON.assigned_map_ids&&markerJSON.assigned_map_ids[0]!==undefined){var color=HMWidgetInstance.maps[divId].colorHash[markerJSON.assigned_map_ids[0]];return(color!==null)?color:0;}else{return 0;}},_initializeColorHash:function(mapData){mapData.colorHash={};mapData.colorIds=mapData.colorIds||[];for(var i=0;i<mapData.mapIds.length;i++){var color=mapData.colorIds[i];mapData.colorHash[mapData.mapIds[i]]=(color!==null)?color:i;}},_showMarkerModalbox:function(marker){if(marker&&marker.id){var url=HABITATMAP_URL+"/markers/"+marker.id+"?iframe=1";url+="&markerColor="+HMWidget._getMarkerColorId(marker);marker.hmCloseToolTip();hmMyLytebox.start({rel:'hm_lyteframe',rev:'width: 680px; scrolling: auto;',href:url,title:marker.name},false,true);}},_getMarkerColorId:function(marker){var divId=parseInt(marker.map.getContainer().id.split(/_/)[2],10);return marker.assigned_map_ids&&HMWidgetInstance.maps[divId].colorHash[marker.assigned_map_ids[0]];},_setMapDimensionsFromDiv:function(mapDiv,containingDiv){var footerWidth=HMWidget.WIDGET_FOOTER_WIDTH;mapDiv.style.width=this._getDimensionFromDiv(containingDiv,'width',500,300)+"px";mapDiv.style.height=this._getDimensionFromDiv(containingDiv,'height',400,300)-footerWidth+"px";},_generateMapURL:function(divId){var params=HMWidgetInstance.maps[divId];return HABITATMAP_URL+"/markers"+"?lat="+params.lat+"&lng="+params.lng+"&z="+params.zoom+"&t="+params.mapType+"&maps="+params.mapIds.join('_')+"&nopol="+(params.nopol?'1':'0')+"&nogrp="+(params.nogrp?'1':'0');},_getDimensionFromDiv:function(div,dimension,_default,min){var value=div.style[dimension];if(value){value=parseInt(value,10);if(value<min){value=min;div.style[dimension]=value+'px';}}else{value=_default;div.style[dimension]=value+'px';}
return value;},_addMarkersAndLayersToMap:function(divId){var mapData=HMWidgetInstance.maps[divId];mapData.mapInstance.updateMarkersFromJSON(mapData.markers);if(!mapData.nopol){mapData.mapInstance.addLayersFromJSON(mapData.layers);}},_insertStylesheets:function(){var head=document.getElementsByTagName('head')[0];this._insertCSSFile(head,'widget_bundle_packaged');},_insertCSSFile:function(head,name){var stylesheet=document.createElement('link');stylesheet.type='text/css';stylesheet.rel='stylesheet';stylesheet.href=HABITATMAP_URL+'/stylesheets/'+name+'.css';head.appendChild(stylesheet);}};}
var EditLayerModalbox={init:function(){this.afterLoadDelegate=$D(this,this.afterLoad);},afterLoad:function(source,options){LayerEditForm.initialize(options);},show:function(href,options){var map=Markers.map;options=Object.extend(options||{},{groupMarkers:map.getGroupMarkers(),mapType:map.getMapType()});options=Object.extend(options,Markers.map.getLocation());this.afterLoadDelegate.delegate.args=[options];Modalbox.show(href,{title:HMUtils.unset(options,'title')||"New line/shape",afterLoad:this.afterLoadDelegate,onFailure:function(xhr){Modalbox.hide();$error(xhr.responseText);},width:900});},editLayer:function(layer,options){var href="/layers/"+layer.properties.id+"/edit";HMMarkerTooltip.hide(true);this.show(href,Object.extend({layer:layer,title:layer.getName()},options||{}));}};var LayerEditForm={initialize:function(options){this._layer=options.layer;this.layerOptions=$('layer_options');this.lineOptions=$('line_options');this.shapeOptions=$('shape_options');this.shapeType=$('shape_type');this.colorPalette=$('color_palette');this.colorBoxes=this.colorPalette.select('.color_box');this.onColorClickedDelegate=$D(this,this._onColorClicked);this.colorBoxes.invoke('observe','click',this.onColorClickedDelegate);this.fillColorPalette=$('fill_color_palette');this.fillColorBoxes=this.fillColorPalette.select('.color_box');this.fillColorBoxes.invoke('observe','click',this.onColorClickedDelegate);this.form=$('layer_edit_form');this.form.onsubmit=$D(this,this._onSubmitForm);this.lineColor=$('layer_color');this.fillColor=$('layer_fill_color');this.btnDeleteLayer=$('delete_layer_button');this.lineOpacity=$('layer_opacity');this.fillOpacity=$('layer_fill_opacity');this.onChangeOpacityDelegate=$D(this,this._onChangeOpacity);this.lineOpacity.observe('change',this.onChangeOpacityDelegate);this.fillOpacity.observe('change',this.onChangeOpacityDelegate);this.lineWeight=$('layer_weight');this.lineWeight.observe('change',$D(this,this._onLineWeight));this.shapeType.select('input[type="radio"]').invoke('observe','click',$D(this,this._onPolyTypeClicked));this.shapeType.select('p *').invoke('observe','click',$D(this,this._focusOnMap));this._map=new HMLinesMap(options);if(!this.shapeType.select('input:checked').empty()){this._polyTypeClicked();}
if(this.btnDeleteLayer){this.btnDeleteLayer.observe('click',$D(this,this._onDeleteButtonClicked));}
this.onDeleteSuccessDelegate=$D(this,this._onDeleteSuccess);this.onSubmitSuccessDelegate=$D(this,this._onSubmitSuccess);this.onSubmitFailureDelegate=$D(this,this._onSubmitFailure);this.toHexDelegate=$D(this,this.toHex);this.serializePolyDelegate=$D(this,this._serializePoly);this.serializePolyKeyDelegate=$D(this,this._serializePolyKey);this._setFormColorValue();this._resetPolyStyle();this._handleMapEvents();},_focusOnMap:function(source){$('lines_map').focus();},_onPolyTypeClicked:function(source){this._polyTypeClicked();},_onChangeOpacity:function(source){this._resetPolyStyle();},_onLineWeight:function(source){this._resetPolyStyle();},_handleMapEvents:function(){GEvent.addListener(this._map,'first_layer_added',$D(this,this._lockTypeRadio));GEvent.addListener(this._map,'last_layer_removed',$D(this,this._unlockTypeRadio));},_lockTypeRadio:function(source){this.shapeType.select('input[type=radio]:not(:checked)')[0].disable().previous().addClassName('disabled');},_unlockTypeRadio:function(source){this.shapeType.select('input[type=radio]:disabled')[0].enable().previous().removeClassName('disabled');},_onDeleteButtonClicked:function(source,event){event.stop();if(confirm("Are you sure you want to delete this line/shape layer?")){Layers.destroy(this._layer,{onSuccess:this.onDeleteSuccessDelegate,onError:HMUtils.errorMessage("while deleting the layer"),onFailure:HMUtils.errorMessage("while deleting the layer")});}},_onDeleteSuccess:function(source){Modalbox.hide();Markers.map.removeLayer(this._layer);},_onColorClicked:function(source,e){e.findElement('.color_palette').down('.selected').removeClassName('selected');e.element().addClassName('selected');this._setFormColorValue();this._resetPolyStyle();},_setFormColorValue:function(){this.lineColor.value=this.getFormattedColor('color_palette');this.fillColor.value=this.getFormattedColor('fill_color_palette');},getFormattedColor:function(id){var style=$$('#'+id+' .selected')[0].getStyle("background-color");return(style.include('rgb'))?"#"+style.gsub(/[^\d]+/," ").strip().split(" ").map(this.toHexDelegate).join(""):style;},toHex:function(source,value){var hex=parseInt(value,10).toString(16);return hex.length==1?'0'+hex:hex;},_resetPolyStyle:function(){this._map.setStrokeStyle({color:$F(this.lineColor),weight:$F(this.lineWeight),opacity:this._getOpacity()});this._map.setFillStyle({color:$F(this.fillColor),opacity:this._getFillOpacity()});},_polyTypeClicked:function(){var klass=this._getPolyClass();this._map.setPolyClass(klass);this.layerOptions.show();this.lineOptions.show();(klass==GPolygon)?this.shapeOptions.show():this.shapeOptions.hide();},_getOpacity:function(){return this.lineOpacity.value/100;},_getFillOpacity:function(){return this.fillOpacity.value/100;},_getPolyClass:function(){return window["G"+this.shapeType.select('input:checked')[0].value];},_saveAndClose:function(){$error('not implemented');},_addAnother:function(){this._map.finishDrawing();this._startDrawing();},_onSubmitForm:function(source){if(this._map.isDrawing()){$warning('You have to finish what you are currently drawing (double click).');return false;}
if(this._map.empty()){$warning('You have to draw at least one shape or line to save.');return false;}
var formData=source.serialize(true);var parameters;if(formData._method=='put'){delete formData._method;parameters={_method:'put'};}
formData=Object.toQueryString(formData);var layersData=this._map.getEncoded().map(this.serializePolyDelegate).join('&');var url=source.action+'?'+formData+'&'+layersData;Requester.post(url,{link:this.form.down('input[type=submit]'),parameters:parameters,onSuccess:this.onSubmitSuccessDelegate,onError:$error.curry('Oops! Something went wrong.'),onFailure:this.onSubmitFailureDelegate});return false;},_serializePoly:function(source,i){return $H(i).map(this.serializePolyKeyDelegate).join('&');},_serializePolyKey:function(source,i){return'layer[polies][]['+i.key+']'+'='+i.value;},_onSubmitSuccess:function(source,xhr){Modalbox.hideWithMessage('Lines saved.');Markers.map.refreshLayer(HMLayer.createFromJSON([xhr.responseJSON])[0]);Markers.map.autoZoom();},_onSubmitFailure:function(source,xhr){$warning(xhr.responseText);}};var ImageUploadHandler={init:function(){$('hide_upload_form').onclick=this.restoreEditWindow.bind(this);},insertImage:function(image_src_,image_thumb_src,caption,image_width,image_alt_,image_id_){var ed=tinyMCE.activeEditor;var args={vspace:'',hspace:'',border:'',align:''};var style='';ed.getWin().focus();ed.focus();ed.getWin().focus();tinymce.extend(args,{src:image_thumb_src,alt:image_alt_});var el=ed.selection.getNode();if(el&&el.nodeName=='IMG'){ed.dom.setAttribs(el,args);}else{brs=ed.getDoc().getElementsByTagName('br').length;ed.execCommand('mceInsertContent',false,'<div class="editor_image">'+'<a href="'+image_src_+'" rel="thumbnail"><img id="__mce_tmp" /></a>'+'<label style="width: '+image_width+'px">'+caption+'</label></div>',{skip_undo:1});ed.dom.setAttribs('__mce_tmp',args);el=ed.getDoc().getElementById('__mce_tmp');var div=el.parentNode.parentNode;this.checkNesting(div);if(ed.getDoc().getElementsByTagName('br').length>brs){if(div.previousSibling&&div.previousSibling.nodeName=='BR'){Element.remove(div.previousSibling);}}
ed.dom.setAttrib('__mce_tmp','id','');ed.undoManager.add();}
ed.selection.collapse(true);},checkNesting:function(div){var testNode=div;var root,nested,stop;do{testNode=testNode.parentNode;root=Element.hasClassName(testNode,'mceContentBody');nested=Element.hasClassName(testNode,'editor_image');stop=root||nested;}
while(!stop);if(nested){Element.insert(testNode,{after:Element.remove(div)});}},onUploadSuccess:function(filename,thumb,caption,width){tinyMCE.activeEditor.focus();this.restoreEditWindow();this.insertImage(filename,thumb,caption,width,'image','image');},onUploadFailure:function(message){tinyMCE.activeEditor.focus();this.restoreEditWindow();$error(message);},restoreEditWindow:function(){$('image_upload').down('form').reset();$('image_upload').hide();$('edit_marker_form').show();Modalbox.restoreCaption();this.restoreScrollTop();this.restoreCursorPosition();return false;},storeScrollTop:function(){this.scrollTop=$('MB_content').scrollTop;},restoreScrollTop:function(){$('MB_content').scrollTop=this.scrollTop;},storeCursorPosition:function(editor){this.currentEditor=editor;this.cursorPosition=editor.selection.getBookmark();},restoreCursorPosition:function(){this.currentEditor.selection.moveToBookmark(this.cursorPosition);}};var MarkerEditForm={initialize:function(marker){this.createNewMarkerDelegate=$D(this,this._createNewMarker);this.createNewMarkerFromAddressDelegate=$D(this,this._createNewMarkerFromAddress);this.saveRteIdDelegate=$D(this,this._saveRteId);this.onEditSuccessDelegate=$D(this,this._onEditSuccess);this.onNewSuccessDelegate=$D(this,this._onNewSuccess);this.onFailureDelegate=$D(this,this._onFailure);this.onMapClickDelegate=$D(this,this._onMapClick);this._editMode=Boolean(marker);this._marker=marker;this._map=new HMSmallMap({initialMarker:marker,defaultPosition:marker?null:Markers.map.getCenterAsHash(),handlers:{click:marker?null:this.onMapClickDelegate}});this.form=$('edit_marker_form');this.form.onsubmit=$D(this,this._onSubmitForm);this.submit=this.form.down('input[type=submit]');this.lookupAddress=$('lookup_address');this.lookupAddress&&this.lookupAddress.observe('click',this._lookupAddress.bind(this));this._initTinyMCE();ImageUploadHandler.init();this.markerName=$('marker_name');this.markerNeighborhood=$('marker_neighborhood');this.markerNeighborhood&&this.markerNeighborhood.focus();this.markerName&&this.markerName.focus();marker&&this.markerName&&this._enableDraggingOnMarker(marker);},_onMapClick:function(source,overlay,latLng){this._createNewMarker(latLng);},_enableDraggingOnMarker:function(marker){marker.enableDragging();GEvent.addListener(marker,'drag',this._updateFormLatLng.curry(marker));},_createNewMarker:function(latLng){var marker=new GMarker(latLng,{icon:GMarker.hmGetMarkerIcon(),draggable:true});this._map.clearMarkers();this._map.addMarker(marker);this._updateFormLatLng(marker);this._enableDraggingOnMarker(marker);},_lookupAddress:function(event){event.stop();this._map.findAddressAndMove($F('marker_address'),this.createNewMarkerFromAddressDelegate);},_createNewMarkerFromAddress:function(source,latLng){this._createNewMarker(latLng);},_updateFormLatLng:function(marker){var latLng=marker.getLatLng();$('marker_lat').value=latLng.lat();$('marker_lng').value=latLng.lng();},_saveRteId:function(source,i){$(i).value=tinyMCE.editors[i].getContent();},_onSubmitForm:function(source){this.RTE_IDS.each(this.saveRteIdDelegate);this.submit.blur();this._editMode?this.requestEdit():this.requestCreate();return false;},requestEdit:function(){Requester.post('/markers/'+this._marker.id,{link:this.submit,parameters:this.form.serialize(),onSuccess:this.onEditSuccessDelegate,onFailure:this.onFailureDelegate});},requestCreate:function(){Requester.post('/markers/',{link:this.submit,parameters:this.form.serialize(),onSuccess:this.onNewSuccessDelegate,onFailure:this.onFailureDelegate});},_onFailure:function(source,xhr){$warning(xhr.responseText);},_onEditSuccess:function(source,xhr){Modalbox.hideWithMessage('Marker updated successfully');var json=xhr.responseJSON;json.assigned_map_ids=this._marker.assigned_map_ids;Markers.map.refreshMarker(this._marker.id,json);},_onNewSuccess:function(source,xhr){Modalbox.hideWithMessage('Marker created successfully');Markers.map.addMarkerFromJSON(xhr.responseJSON);},_initTinyMCE:function(){var selector_simple="tiny_mce_simple";var plugins="paste,uploadimage,footnote,media";var theme_advanced_buttons1="underline,link,unlink,code,removeformat";var theme_advanced_buttons1_add="pasteword,uploadImage,footnote,media";var extended_valid_elements="a[href|target|rel|class],"+"img[class|src|border=0|alt|title|hspace|vspace|width|height|align|name],"+"hr[class|width|size|noshade],"+"font[face|size|color|style],"+"span[class|align|style],"+"object[width|height|type|data|classid|codebase],"+"param[name|value],"+"embed[src|type|allowscriptaccess|allowfullscreen|width|height|flashvars|wmode]";var bodyClass="marker_footnotes=tinymce_footnotes";HMUtils.unloadTinyMCE();HMUtils.initializeTinyMCENoUnload({plugins:plugins,theme_advanced_buttons1_add:theme_advanced_buttons1_add,extended_valid_elements:extended_valid_elements,body_class:bodyClass});HMUtils.initializeTinyMCENoUnload({editor_selector:selector_simple,extended_valid_elements:extended_valid_elements});},RTE_IDS:$w('marker_occupant marker_details marker_footnotes')};HMUtils.bindMethods(MarkerEditForm,'initialize');var MapCreateForm={MARKER_LIST_HEADER_HTML:'<div class="modal_dialog_field">'+'<label>Assigned Markers</label>'+'<span class="on_off caption">'+'(select: <a href="#" class="all">all</a> / <a href="#" class="none">none</a>)'+'</span><br />'+'<div class="assigned_markers"></div>'+'</div>',MARKER_LIST_ENTRY_HTML:new Template('<p>'+'<input type="checkbox" checked="checked" name="map[marker_ids][]" id="marker_#{id}_checkbox" value="#{id}" /> '+'<label for="marker_#{id}_checkbox" class="marker_name">#{name}</label>'+'</p>'),showForm:function(markers,e){if(e){e.stop();e.element().blur();}
if(HMUtils.loggedIn()){Modalbox.show("/maps/new",{title:'New map',width:550,height:500,afterLoad:this.afterFormLoad.curry(markers),afterHide:HMUtils.unloadTinyMCE});}else{$warning("You must log in first to create maps.");}},afterFormLoad:function(markers){$('submit_new_map').observe('click',this.submitForm);this.initializeTinyMCE();if(markers){var markerList=this.MARKER_LIST_HEADER_HTML;$('map_modalbox').down('#map_keywords').up('div').insert({after:markerList});var markerEntries=markers.map(this.createMarkerHTML).join('');$('map_modalbox').down('.assigned_markers').insert({after:markerEntries});}
this.initializeOnOff();},createMarkerHTML:function(marker){return this.MARKER_LIST_ENTRY_HTML.evaluate(marker);},submitForm:function(e){e.stop();this.updateFromTinyMCE();Requester.post('/maps',{link:e.element(),parameters:$('new_map').serialize(),onSuccess:this.onSubmitSuccess,onFailure:function(xhr){$warning(xhr.responseText)}});},onSubmitSuccess:function(xhr){var mapBox=$$('.saved_maps_list').first();if(mapBox){var map=xhr.responseText;mapBox.insert({bottom:map});}
Modalbox.hideWithMessage("Map created successfully.");},initializeTinyMCE:function(){HMUtils.initializeTinyMCE();},initializeOnOff:function(){$$('.on_off .all').invoke('observe','click',this._allCheckboxesSetter(true));$$('.on_off .none').invoke('observe','click',this._allCheckboxesSetter(false));},_allCheckboxesSetter:function(value){return function(e){e.stop();$$('#map_modalbox input[type=checkbox]').clap('checked',value);};},updateFromTinyMCE:function(){$('map_description').value=tinyMCE.editors.map_description.getContent();}};HMUtils.bindMethods(MapCreateForm,'showForm','submitForm','afterFormLoad','createMarkerHTML');var MapMarkers={CREATE_PATH:'/map_markers/update_marker',init:function(){$('submit_map_marker').observe('click',this._submitForm);},_submitForm:function(e){e.stop();Requester.put(MapMarkers.CREATE_PATH,{parameters:this.up('form').serialize(),link:this,onFailure:function(){$error('Oops! Something went wrong. Please try again later.')},onSuccess:function(){Modalbox.hideWithMessage("Marker updated successfully!")}});}};HMUtils.bindMethods(MapMarkers,'init');var Search=Class.create({directions:['w','e','s','n'],initialize:function(markers,url,type){this.markers=markers;this.url=url;this.type=type;this.lastSearch=null;this.lastFullSearch=null;this.form=$('search_'+type+'_form');this.form.onsubmit=$D(this,this.onFormSubmit);this.keywords=$('search_'+type+'_keywords');this.tag=$('search_'+type+'_tag');this.address=$('search_'+type+'_address');this.currentView=$('search_'+type+'_current_view');this.radius=$('search_'+type+'_radius');this.searchIndicator=$(type+'_live_search_indicator');this.counter=$(type+'_matches_counter');this.submit=$('submit_'+type+'_search');this.submit.observe('click',$D(this,this.submitSearch));this.timeout=null;this.onInputKeydownDelegate=$D(this,this.onInputKeydown);this.onSuccessDelegate=$D(this,this.onSuccess);this.onCurrentViewClickDelegate=$D(this,this.onCurrentViewClick);this.onLiveSearchSuccessDelegate=$D(this,this.onLiveSearchSuccess);this.submitLiveSearchDelegate=$D(this,this.submitLiveSearch);this.onRadiusChangeDelegate=$D(this,this.onRadiusChange);this.initLiveSearch();},onFormSubmit:function(source){return false;},initLiveSearch:function($super){this.keywords.clear();this.keywords.observe('keydown',this.onInputKeydownDelegate);this.address.observe('keydown',this.onInputKeydownDelegate);this.currentView.checked=false;this.currentView.observe('click',this.onCurrentViewClickDelegate);this.address.disabled=false;this.address.clear();this.radius.observe('change',this.onRadiusChangeDelegate);},onInputKeydown:function(source,event){var key=event.which||event.keyCode;if(HMUtils.isModifier(key)){clearTimeout(this.timeout);this.timeout=this.submitLiveSearchDelegate.delay(1);}},onRadiusChange:function(source){this.submitLiveSearch();},onCurrentViewClick:function(source,event){var adr=this.address;adr.disabled=source.checked;if(adr.disabled){adr.addClassName('disabled');}else{adr.removeClassName('disabled');}
this.submitLiveSearch();},submitLiveSearch:function(){this.searchIndicator.show();this.tag.value='';this.lastSearch=this.searchParameters();Requester.get(this.url,{parameters:this.lastSearch+"&only_count=1",onSuccess:this.onLiveSearchSuccessDelegate});},onLiveSearchSuccess:function(source,xhr){var json=xhr.responseJSON;var tagCloud=json.tag_cloud;this.markers.updateTagCloud(tagCloud);this.setCounter(json.count);this.searchIndicator.hide();},setCounter:function(value){this.counter.show().down('span').update(value);},run:function(){this.lastFullSearch=this.lastSearch=this.searchParameters();this.performFullSearch();},runWithTag:function(tag){this.tag.value=tag;var params=this.lastSearch;params=params.replace(new RegExp("search_"+this.type+"%5Btag%5D=[^&]*&?"),'');params=params.replace(/no_cloud=1&?/,'');params=params+'&search_'+this.type+'%5Btag%5D='+tag+'&no_cloud=1';this.lastFullSearch=this.lastSearch=params;this.performFullSearch();},performFullSearch:function(){throw"Abstract method, implement in subclasses";},submitSearch:function(source){this.tag.value='';this.markers.unselectTag();this.markers.unselectFeaturedMaps();this.run();},searchParameters:function(initial){var mapView=this.currentView.checked;var params=this.form.serialize();if(mapView){if(initial&&searchParams){var hash={};var n=this.directions.length;var dir;for(var i=0;i<n;i++){dir=this.directions[i];hash['search_'+this.type+'['+dir+']']=searchParams[dir];}
params+="&"+HMUtils.hashToQueryParameters(hash);}else{params+="&"+this.markers.map.mapBoundsForQuery(this.type);}}
return params;}});var MarkerSearch=Class.create(Search,{initialize:function($super,markers,url){this.mapSpinner=$('map_spinner');this.onCounterLeaveDelegate=$D(this,this.onCounterLeave);this.onCounterTotalDelegate=$D(this,this.onCounterTotal);this.onCounterDefaultDelegate=$D(this,this.onCounterDefault);$super(markers,url,'marker');},initLiveSearch:function($super){$super();this.loadSearchParams();},loadSearchParams:function(){if(!window.searchParams){return;}
if(searchParams.a){this.address.value=searchParams.a;}
if(searchParams.k){this.keywords.value=searchParams.k;}
if(searchParams.r){this.radius.value=searchParams.r;}
if(searchParams.tag){this.tag.value=searchParams.tag;}
if(searchParams.cv=="1"){this.currentView.checked=true;}},requestMarker:function(id,options){Requester.get('/markers/'+id+'.json',options);},request:function(options){var onSuccess=options.onSuccess||function(){};switch(options.counter){case'leave':onSuccess=onSuccess.chain(this.onCounterLeaveDelegate);break;case'total':onSuccess=onSuccess.chain(this.onCounterTotalDelegate);break;default:onSuccess=onSuccess.chain(this.onCounterDefaultDelegate);}
delete options.counter;options.onSuccess=onSuccess;var url=this.url;if(options.paramString){url+=('?'+options.paramString);delete options.paramString;}
this.showMapSpinner();this.markers.onMarkerSearch();Requester.get(url,options);},onCounterTotal:function(source,xhr){this.submitLiveSearch();this.hideMapSpinner();},onCounterLeave:function(source,xhr){this.hideMapSpinner();},onCounterDefault:function(source,xhr){this.setCounter(xhr.responseJSON.count);this.hideMapSpinner();},performFullSearch:function(){this.request({parameters:this.lastFullSearch,counter:'leave',onSuccess:this.onSuccessDelegate});},onSuccess:function(source,xhr){var json=xhr.responseJSON;if(json.location_error){$warning("Location not found.");}else{var location=json.location;var markers=json.markers;var tagCloud=json.tag_cloud;var inCurrentView=(this.lastFullSearch.indexOf('search_marker%5Bcurrent_view%5D=1')!=-1);this.markers.map.onSearchSuccess(markers,location,this.radius.value,inCurrentView);if(tagCloud){this.markers.updateTagCloud(tagCloud);}}
this.setCounter(json.count);},showMapSpinner:function(){this.mapSpinner.show();},hideMapSpinner:function(){this.mapSpinner.hide();}});var MapSearch=Class.create(Search,{initialize:function($super,markers,url){$super(markers,url,'map');},request:function(options){this.searchIndicator.show();this.onSuccessDelegate.delegate.args=[HMUtils.unset(options||{},'initialLoad')];var url=HMUtils.unset(options||{},'url')||this.url;var requestOptions=Object.extend({parameters:null,onFailure:$error.curry('Oops! Something went wrong. Please try again later.')},this.chainOnSuccess(options||{},this.onSuccessDelegate));this.markers.onMapSearch();Requester.get(url,requestOptions);},onSuccess:function(source,initialLoad,xhr){var json=xhr.responseJSON;this.searchIndicator.hide();this.setCounter(json.count);this.markers.onMapSearchSuccess(json.html,json.tag_cloud,initialLoad);},chainOnSuccess:function(params,callback){params.onSuccess=params.onSuccess?params.onSuccess.chain(callback):callback;return params;},performFullSearch:function(){this.request({parameters:this.lastFullSearch});}});var Markers={TAG_CLOUD_FONTSIZE_RANGE:[12,18],TAG_CLOUD_ELEMENT_TEMPLATE:new Template('<a href="#" style="font-size: #{fontSize}px" class="#{cssClass}">#{name}</a>'),init:function(){HMMarkerTooltip.init();EditLayerModalbox.init();MarkerModalbox.init();this.markerSearch=new MarkerSearch(this,'/markers.json');this.mapSearch=new MapSearch(this,'/maps');this.featuredMaps=$$('.featuredMaps').first();this.hideMapLines=$('hide_lines');this.hideMapLines.observe('click',$D(this,this.onHideLines));this.noMarkerGrouping=$('no_marker_grouping');this.noMarkerGrouping.observe('click',$D(this,this.onNoMarkerGrouping));this.tagCloud=$$('.tagCloud').first();this.tagCloudContent=this.tagCloud.down('.content');this.createTagCloudElementDelegate=$D(this,this.createTagCloudElement);this.onTagClickDelegate=$D(this,this.onTagClick);this.tagValueDelegate=$D(this,this.tagValue);this.onLayersIndexSuccessDelegate=$D(this,this._onLayersIndexSuccess);this.switchMarkerGroupingDelegate=$D(this,this._switchMarkerGrouping);this.initFeaturedMapDelegate=$D(this,this._initFeaturedMap);this.onFeaturedMapDelegate=$D(this,this._onFeaturedMap);this.onRequestMarkersSuccessDelegate=$D(this,this._onRequestMarkersSuccess);this.featuredMapsClassToggler=new ClassToggler('selected');this.tagCloudClassToggler=new ClassToggler('selected');var location,zoom;if(!mapsIds||(startingPoint&&startingPoint.force)){if(startingPoint){location=startingPoint;zoom=startingPoint.zoom;}else{var savedLat=CookieScript.getCookie('lat');var savedLng=CookieScript.getCookie('lng');var savedZoom=CookieScript.getCookie('zoom');if(savedLat&&savedLng&&savedZoom){location={lat:savedLat,lng:savedLng};zoom=parseInt(savedZoom,10);}}}
this.map=new HMMapWithPanels('large_map',{markerIndexDiv:'markers_list',mapIndexDiv:'maps_list',mapIndexFullVersion:true,handlers:{moveend:$D(this,this._saveMapPosition),click:$D(this,this._onMarkerItemClick)},polyClickHandler:$D(this,this._onPolyClick),showPolyTooltips:true,controllers:{layers:Layers},defaultPosition:location,defaultZoom:zoom,mapType:initialMapType?HMMap.getMapTypeByName(initialMapType):G_PHYSICAL_MAP});if(searchParams){if(searchParams.nopol=="1"){this.hideMapLines.checked=true;}
if(searchParams.nogrp=="1"){this.noMarkerGrouping.checked=true;this.onNoMarkerGrouping(this.noMarkerGrouping);}}
if(mapsIds){this.map.hide();}
if($('markers_body')){$('markers_body').remove();}
this.searchTabs=new Tabs($$('.tab'),$$('.screen'),$D(this,this.onTabShow),$D(this,this.onTabHide));this._initFeaturedMaps();this._initMarkersUI();var waitForMaps=this._initMapsUI();if(!waitForMaps){this.getMarkers();}
this.preselectFeaturedMap();},preselectFeaturedMap:function(){var delegate=$D(this,this.checkFeaturedMapAnchorUrl);delegate.delegate.args=[document.location];var a=this.featuredMaps.select('a').find(delegate);this.featuredMapsClassToggler.toggle(a&&a.up());},checkFeaturedMapAnchorUrl:function(source,url,i){return i.href==url;},_onPolyClick:function(source,layer,options){EditLayerModalbox.editLayer(layer,options);},onTabShow:function(source){var element=this.hideMapLines.up();var mapsTabVisible=(source.currentIndex()==1);if(mapsTabVisible){element.show();}else{element.hide();}
this.map.clear();this.clearTagCloud();var search=(source.currentIndex()==1)?this.mapSearch:this.markerSearch;search.lastSearch=null;search.lastFullSearch=null;if(search.keywords.value||search.address.value||search.currentView.checked){search.submitLiveSearch();}
if(!mapsTabVisible){this.map.getMapIndex().displayTheHabitatMap();}},onTabHide:function(source){var search=(source.currentIndex()==1)?this.mapSearch:this.markerSearch;search.tag.value='';},onMapSearch:function(){var mapIndex=this.map.getMapIndex();mapIndex.hide();mapIndex.resetScroll();},onMarkerSearch:function(){},unselectFeaturedMaps:function(){this.featuredMapsClassToggler.toggle(null);},onHideLines:function(source){this.map.setDisplayLines(!source.checked);},onNoMarkerGrouping:function(source){this.markerSearch.showMapSpinner();this.switchMarkerGroupingDelegate.delegate.args=[!source.checked];setTimeout(this.switchMarkerGroupingDelegate,10);},_switchMarkerGrouping:function(source,enabled){this.map.setMarkerGrouping(enabled);this.markerSearch.hideMapSpinner();},hideMapLinesChecked:function(){return this.hideMapLines.checked;},unselectTag:function(){this.tagCloudClassToggler.toggle(null);},_onMarkerItemClick:function(source,marker){MarkerModalbox.showMarkerModalbox(marker);},_saveMapPosition:function(source){var latLng=this.map.getCenter();CookieScript.setCookie('lat',latLng.lat());CookieScript.setCookie('lng',latLng.lng());CookieScript.setCookie('zoom',this.map.getZoom());},getMarkers:function(options){var params=null,paramString=null,selected=null,showModalbox=false;if(options&&options.selected){selected=this.map.getMapIndex().getSelectedMaps();params={maps:selected.join()};}else if(markersIds){params={'markers_ids[]':markersIds};}else if(markerId){showModalbox=true;params={'markers_ids[]':[markerId]};}else if(mapSearchMarkerId){params={'markers_ids[]':[mapSearchMarkerId]}}else if(searchParams){paramString=this.markerSearch.searchParameters(true);}else{params={'search_marker[current_view]':1};Object.extend(params,this.map.mapBoundsForQueryAsHash('marker'));}
paramString=paramString||Object.toQueryString(params);if(selected){var errorCallback=HMUtils.errorMessage("while requesting layers.");if(!this.hideMapLinesChecked()){Layers.index({parameters:{'maps_ids[]':selected},onSuccess:this.onLayersIndexSuccessDelegate,onError:errorCallback,onFailure:errorCallback});}}
this.onRequestMarkersSuccessDelegate.delegate.args=[selected,showModalbox];this.markerSearch.lastSearch=this.markerSearch.lastFullSearch=paramString;this.markerSearch.request({onSuccess:this.onRequestMarkersSuccessDelegate,onFailure:this._onMarkerSearchFailure,counter:(selected||mapSearchMarkerId)?'leave':null,paramString:paramString});},_onLayersIndexSuccess:function(source,layers){this.map.addLayers(layers);if(!(startingPoint&&startingPoint.force)){this.map.autoZoom();}},_onRequestMarkersSuccess:function(source,selected,showModalbox,xhr){var json=xhr.responseJSON;if(xhr.responseText.empty()){$info('No markers yet. You can create first marker!');}else{if(json.markers){var markers=this._addMarkers(json.markers,selected);if(showModalbox){MarkerModalbox.showMarkerModalbox(markers[0]);}}
if(json.location&&json.location.lat&&json.location.lng){this.map.addCenterPoint(json.location);}
if(json.tag_cloud){this.updateTagCloud(json.tag_cloud);}}
if(mapsIds||selected||markersIds||markerId||mapSearchMarkerId){this.map.show();if(!(startingPoint&&startingPoint.force)){this.map.autoZoom();}}},_initFeaturedMaps:function(){this.featuredMaps.select('a').each(this.initFeaturedMapDelegate);},_initFeaturedMap:function(source,i){i.onclick=this.onFeaturedMapDelegate;},_onFeaturedMap:function(source){this.featuredMapsClassToggler.toggle(source.up(),true);this.showMapSearch();this.showFeaturedMap(source.href);return false;},showFeaturedMap:function(permalink){var params=permalink.split('?')[1].toQueryParams();var maps=params.maps;var colors=params.colors;var grouping=!Boolean(params.nogrp);mapsIds=maps&&maps.split('_');mapColors=colors&&colors.split('_');startingPoint=null;this.map.clear();this.map.getOptions().mapType=HMMap.getMapTypeByName(params.t);this.map.setMapType();this.map.setGroupMarkers(grouping);this.noMarkerGrouping.checked=!grouping;var parameters={'ids[]':mapsIds,lat:params.lat,lng:params.lng,z:params.z};this.mapSearch.request({parameters:parameters,initialLoad:true});},_initMapsUI:function(){$('create_map').observe('click',MapCreateForm.showForm.curry(null));$('share_map').observe('click',this._shareMap.bind(this));$('create_widget').observe('click',this._createWidget.bind(this));$('save_map').observe('click',function(){MapCreateForm.showForm(Markers.map.getMarkers());});if(mapSearchMarkerId){this.showMapSearch();this.mapSearch.request({parameters:$H({'search_map[marker_id]':mapSearchMarkerId}).toQueryString()});}else if(mapsIds){this.showMapSearch();this.mapSearch.request({parameters:{'ids[]':mapsIds},initialLoad:true});return true;}
return false;},_initMarkersUI:function(){this.map.getMapIndex().displayTheHabitatMap();$('add_marker').observe('click',this._showNewMarker);},_addMarkers:function(markersJson,selected){this.map.getMarkerIndex().reinitialize(selected||mapsIds);var markers=HMUtils.collect(markersJson,this.map.buildMarkerFromJSONDelegate);this.map.addMarkers(markers);return markers;},_onMarkerSearchFailure:function(xhr){$error('Oops! Something went wrong. Please try again later');},_shareMap:function(){if(this.mapPanelSelected()){var index=this.map.getMapIndex();var ids=index.getSelectedMaps();if(ids.length>0){var colorIds=index.getColorList();ShareDialog.showDialogForMaps(ids,colorIds);}else{$warning("You have to select at least one map first.");}}else{if(this.map.getMarkers().length>0){var attributes=this.map.getAttributesForPermalink();Object.extend(attributes,this._parametersForShareMarkersDialog(this.markerSearch.lastFullSearch));ShareDialog.showDialogForMarkers(attributes);}else{$warning("Why don't you find some markers first?");}}},_parametersForShareMarkersDialog:function(lastSearch){var params=(lastSearch||"").toQueryParams();var markerIds=params['markers_ids[]'];var hash={k:params['search_marker[keywords]']||"",a:params['search_marker[address]']||"",r:params['search_marker[radius]']||"",tag:params['search_marker[tag]']||"",cv:params['search_marker[current_view]']||"",markers_ids:markerIds&&(markerIds instanceof Array?markerIds.join('_'):markerIds)||'',nopol:Markers.hideMapLinesChecked()};['n','s','w','e'].each(function(dir){if(params['search_marker['+dir+']']!==undefined){hash[dir]=params['search_marker['+dir+']'];}});return hash;},_createWidget:function(){if(this.mapPanelSelected()){var index=this.map.getMapIndex();var ids=index.getSelectedMaps();if(ids.length>0){var colorIds=index.getColorList();ShareDialog.showDialogForWidget(ids,colorIds);}else{$warning("You have to select at least one map first.");}}else{$warning("Select map(s) first. Hint: click the green \"maps\" tab on the left and search for the map(s) "+"you want to add to your site.")}},_showNewMarker:function(){if(HMUtils.loggedIn()){MarkerModalbox.load('/markers/new',"New marker",MarkerEditForm.initialize,{afterHide:HMUtils.unloadTinyMCE});}else{$warning("You must log in first to add markers.");}},showMarkersSearch:function(){this.searchTabs.setTabAt(0);},showMapSearch:function(){this.searchTabs.setTabAt(1);},mapPanelSelected:function(){return(this.searchTabs.currentIndex()==1);},currentSearch:function(){return this.mapPanelSelected()?this.mapSearch:this.markerSearch;},clearTagCloud:function(){this.tagCloudContent.update('');},updateTagCloud:function(tagCloud){var max=tagCloud.max(this.tagValueDelegate);this.tagCloudCoefficient=(this.TAG_CLOUD_FONTSIZE_RANGE[1]-this.TAG_CLOUD_FONTSIZE_RANGE[0])/(max-1);var tags=tagCloud.map(this.createTagCloudElementDelegate);this.tagCloudContent.update(tags.join(', '));this.tagCloudContent.childElements().invoke('observe','click',this.onTagClickDelegate);this.tagCloudClassToggler.toggle($$('.tagCloud .content a.selected').first());if(tags.empty()){this.tagCloud.hide();}else{this.tagCloud.show();}},tagValue:function(source,i){return i[1];},createTagCloudElement:function(source,i){var fontSize=this.TAG_CLOUD_FONTSIZE_RANGE[0]+this.tagCloudCoefficient*(i[1]-1);var cssClass=(this.currentSearch().tag.value==i[0])?'selected':'';return this.TAG_CLOUD_ELEMENT_TEMPLATE.evaluate({fontSize:fontSize,cssClass:cssClass,name:i[0]});},onTagClick:function(source,event){event.stop();this.tagCloudClassToggler.toggle(source);this.currentSearch().runWithTag(source.innerHTML);},onMapSearchSuccess:function(html,tagCloud,initialLoad){var index=this.map.getMapIndex();index.reloadContents(html);index.show();if(tagCloud){this.updateTagCloud(tagCloud);}
if(initialLoad){index.selectMapsWithColors(mapsIds,mapColors);this.getMarkers({selected:true});}}};HMUtils.bindMethods(Markers,'init');Event.observe(window,'load',Markers.init);var Reports={BUTTON_ID_PREFIX:'report_inappropriate_',init:function(){$$('a[id^='+this.BUTTON_ID_PREFIX+']').invoke('observe','click',this._showReportForm);},_showReportForm:function(e){e.stop();var objectId=e.element().readAttribute('id').gsub(this.BUTTON_ID_PREFIX,'').split('_');var type=objectId[0];var id=objectId[1];Modalbox.show('/messages/report?'+type+'_id='+id,{title:"Inappropriate content report",afterLoad:this._initModalboxUI});},_initModalboxUI:function(){$('submit_button').observe('click',this._submitForm);},_submitForm:function(e){e.stop();if($F('comment').blank()){$warning("Comment can't be blank");return;}
Requester.post($('report_form').readAttribute('action'),{link:e.element(),parameters:$('report_form').serialize(),onSuccess:function(){Modalbox.hide()},onFailure:function(xhr){$error(xhr.responseText)}});}};HMUtils.bindMethods(Reports,'init','_initModalboxUI','_showReportForm');