WP = {};

function T$(id){return document.getElementById(id)}
function T$$(e,p){return p.getElementsByTagName(e)}
function T$$$(){return document.all?1:0}

WP.ajax=function(){
	return{
		call:function(u,m){
			if(tooltip){tooltip.setMap(null)}
			tooltip = new InfoBox({latlng: m.getPosition(), map: map, content: ''});
			var x=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
			x.onreadystatechange=function(){
				if(x.readyState==4&&x.status==200){
					var content=T$('ttcontent');
					content.style.backgroundImage='none';
					content.innerHTML=x.responseText;
				}
			};
			x.open('GET',u,true);
			x.send(null)
		}
	};
}();

WP.properties=function(){
	return{
		sort:function(elem){
			var current = self.document.location.toString(), pos = current.indexOf("sort");
			if(pos != -1){
				current = current.substring(0,pos-1)
			}
			window.location = current + "/sort" + elem.value
		}
	};
}();

WP.search=function(){
	return{
		popcounties:function(id){
			var sf=T$('searchform'); sf.className="loadingcounties";
			var x=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP'),
			url='/hunting-land/counties/' + id;
			x.onreadystatechange=function(){
				if(x.readyState==4&&x.status==200){
					var counties=T$('selectcountywrapper');
					counties.innerHTML=x.responseText;
					counties.disabled=false;
					sf.className="";
				}
			};
			x.open('GET',url,true);
			x.send(null)
		},
		go:function(){
			var url="/hunting-land/results/";
			url+=T$('selectstate').value+"/";
			url+=T$('selectcounty').value+"/";
			url+=T$('minacreage').value+"/";
			url+=T$('minprice').value+"/";
			url+=T$('maxprice').value;
			window.location = url;
		}
	};
}();

WP.container=function(){
	function tabs(n,p){this.n=n; this.init(p)}
	tabs.prototype.init=function(p){
		var s=T$(p.id), u=this.u=T$$('ul',s)[0], c=T$$('li',u), l=c.length, i=this.l=0; this.e=[];
		if(p.navid&&p.activeclass){this.g=T$$('li',T$(p.navid)); this.s=p.activeclass}
		for(i;i<l;i++){if(c[i].parentNode.id=='tabs'){this.e[this.l]=c[i]; this.g[this.l].onclick=new Function(this.n+'.pos('+this.l+')'); this.l++}}
		var hash=self.document.location.hash.substring(1); p.position=hash==''?0:hash=='video'?3:this.l-1;
		this.pos(p.position||0,this.a?1:0)
	},
	tabs.prototype.pos=function(p,a){
		for(var i=0;i<this.l;i++){
			this.e[i].style.display=i==p?'':'none';
			if(this.g){
				var n=this.g[i]; n.className=i==p?this.s:'';
				if(i==p&&n.id=='maplink'){
					map.initialZoom = true;
					map.fitBounds(bounds);
					google.maps.event.trigger(map, 'resize');
				}
			}
		}
	}
	return{tabs:tabs}
}();

WP.tooltips=function(){
	return{
		build:function(){
			var counties=[], areas=[], list=T$('countylistings'), items=T$$('li',list), length=items.length, map=T$('propertiesleft'), i=0;
			for(i; i<length; i++){
				var item=items[i], link=T$$('a',item)[0].href, path=link.split("/"), county=path[5], count=T$$('span',item)[0].innerHTML;
				counties[county]=[count,i]
			}
			this.items=items; this.length=length;
			mlist=T$('mapareadefinitions'), mitems=T$$('area',mlist), mlength=mitems.length, mleft=0, mtop=0;
    		while (map){
        		mleft+=map.offsetLeft;
       			mtop+=map.offsetTop;
        		map=map.offsetParent
    		}
			for(i=0; i<mlength; i++){
				var item=mitems[i], link=item.href, path=link.split("/"), county=path[5], name=item.alt, index=-1,
				count=(counties[county]) ? ((counties[county][0] > 1) ? (counties[county][0] + " listings") : (counties[county][0] + " listing")) : "no listings";
				if(counties[county]){
					var coords=item.coords.split(','), clength=coords.length, x=xcount=ycount=0, xcoords=[], ycoords=[];
					for(x; x<clength; x++){
						if(x%2==0){
							xcoords[xcount]=coords[x];
							xcount++
						}else{
							ycoords[ycount]=coords[x];
							ycount++
						} 
					}
					var xlarge=Math.max.apply(Math,xcoords), xsmall=Math.min.apply(Math,xcoords), xcenter=(xlarge+xsmall)/2,
					ylarge=Math.max.apply(Math,ycoords), ysmall=Math.min.apply(Math,ycoords), ycenter=(ylarge+ysmall)/2;
					top=mtop+ycenter, left=mleft+xcenter;
					index=counties[county][1];
					areas[county]=[name,count,top,left]
				}
				item.onmouseover=new Function("WP.tooltips.show(" + index + ",'<strong>" + addslashes(name) + "</strong><br /><em>" + count + "</em>')");
				item.onmouseout=new Function("WP.tooltips.hide(" + index + ")")
			}
			for(i=0; i<length; i++){
				var item=items[i], link=T$$('a',item)[0].href, path=link.split("/"), county=path[5];
				if(areas[county]){
					var name=areas[county][0], count=areas[county][1], top=areas[county][2], left=areas[county][3]; 
					item.onmouseover=new Function("WP.tooltips.show(-1,'<strong>" + addslashes(name) + "</strong><br /><em>" + count + "</em>', " + top + ", " + left + ")");
					item.onmouseout=function(){WP.tooltips.hide(-1)}
				}
			}
		},
		show:function(index,string,top,left){
			if(index>-1){
				this.items[index].id='hlcounty'
			}
			WP.tooltip.show(string,top,left)
		},
		hide:function(index){
			if(index>-1){
				this.items[index].id=''
			}
			WP.tooltip.hide()
		}
	};
}();

TINY={};

TINY.box=function(){
	var j,m,b,g,v,p=0;
	return{
		show:function(o){
			v={opacity:70,close:1,animate:1,fixed:1,mask:1,maskid:'',boxid:'',topsplit:2,url:0,post:0,height:0,width:0,html:0,iframe:0,fade:1};
			for(s in o){v[s]=o[s]}
			if(!p){
				j=document.createElement('div'); j.className='tbox';
				p=document.createElement('div'); p.className='tinner';
				b=document.createElement('div'); b.className='tcontent';
				m=document.createElement('div'); m.className='tmask';
				g=document.createElement('div'); g.className='tclose'; g.v=0;
				document.body.appendChild(m); document.body.appendChild(j); j.appendChild(p); p.appendChild(b);
				m.onclick=g.onclick=TINY.box.hide; window.onresize=TINY.box.resize
			}else{
				j.style.display='none'; clearTimeout(p.ah); if(g.v){p.removeChild(g); g.v=0}
			}
			p.id=v.boxid; m.id=v.maskid; j.style.position=v.fixed?'fixed':'absolute';
			if(v.html&&!v.animate){
				p.style.backgroundImage='none'; b.innerHTML=v.html; b.style.display='';
				p.style.width=v.width?v.width+'px':'auto'; p.style.height=v.height?v.height+'px':'auto'
			}else{
				b.style.display='none'; 
				if(!v.animate&&v.width&&v.height){
					p.style.width=v.width+'px'; p.style.height=v.height+'px'
				}else{
					p.style.width=p.style.height='100px'
				}
			}
			if(v.mask){this.mask(); this.alpha(m,1,v.opacity)}else{this.alpha(j,1,100)}
			if(v.autohide){p.ah=setTimeout(TINY.box.hide,1000*v.autohide)}else{document.onkeypress=TINY.box.esc}
		},
		fill:function(c,u,k,a,w,h){
			if(u){
				if(v.image){
					var i=new Image(); i.onload=function(){w=w||i.width; h=h||i.height; TINY.box.psh(i,a,w,h)}; i.src=v.image
				}else if(v.iframe){
					this.psh('<iframe src="'+v.iframe+'" width="'+v.width+'" frameborder="0" height="'+v.height+'"></iframe>',a,w,h)
				}else{
					var x=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
					x.onreadystatechange=function(){
						if(x.readyState==4&&x.status==200){p.style.backgroundImage=''; TINY.box.psh(x.responseText,a,w,h)}
					};
					if(k){
    	            	x.open('POST',c,true); x.setRequestHeader('Content-type','application/x-www-form-urlencoded'); x.send(k)
					}else{
       	         		x.open('GET',c,true); x.send(null)
					}
				}
			}else{
				this.psh(c,a,w,h)
			}
		},
		psh:function(c,a,w,h){
			if(typeof c=='object'){b.appendChild(c)}else{b.innerHTML=c}
			var x=p.style.width, y=p.style.height;
			if(!w||!h){
				p.style.width=w?w+'px':''; p.style.height=h?h+'px':''; b.style.display='';
				if(!h){h=parseInt(b.offsetHeight)}
				if(!w){w=parseInt(b.offsetWidth)}
				b.style.display='none'
			}
			p.style.width=x; p.style.height=y;
			this.size(w,h,a)
		},
		esc:function(e){e=e||window.event; if(e.keyCode==27){TINY.box.hide()}},
		hide:function(){TINY.box.alpha(j,-1,0,3); document.onkeypress=null; if(v.closejs){v.closejs()}},
		resize:function(){TINY.box.pos(); TINY.box.mask()},
		mask:function(){m.style.height=this.total(1)+'px'; m.style.width=this.total(0)+'px'},
		pos:function(){
			var t;
			if(typeof v.top!='undefined'){t=v.top}else{t=(this.height()/v.topsplit)-(j.offsetHeight/2); t=t<20?20:t}
			if(!v.fixed&&!v.top){t+=this.top()}
			j.style.top=t+'px'; 
			j.style.left=typeof v.left!='undefined'?v.left+'px':(this.width()/2)-(j.offsetWidth/2)+'px'
		},
		alpha:function(e,d,a){
			clearInterval(e.ai);
			if(d){e.style.opacity=0; e.style.filter='alpha(opacity=0)'; e.style.display='block'; TINY.box.pos()}
			e.ai=setInterval(function(){TINY.box.ta(e,a,d)},20)
		},
		ta:function(e,a,d){
			var o=Math.round(e.style.opacity*100);
			if(o==a){
				clearInterval(e.ai);
				if(d==-1){
					e.style.display='none';
					e==j?TINY.box.alpha(m,-1,0,2):b.innerHTML=p.style.backgroundImage=''
				}else{
					if(e==m){
						this.alpha(j,1,100)
					}else{
						j.style.filter='';
						TINY.box.fill(v.html||v.url,v.url||v.iframe||v.image,v.post,v.animate,v.width,v.height)
					}
				}
			}else{
				var n=a-Math.floor(Math.abs(a-o)*.5)*d;
				e.style.opacity=n/100; e.style.filter='alpha(opacity='+n+')'
			}
		},
		size:function(w,h,a){
			if(a){
				clearInterval(p.si); var wd=parseInt(p.style.width)>w?-1:1, hd=parseInt(p.style.height)>h?-1:1;
				p.si=setInterval(function(){TINY.box.ts(w,wd,h,hd)},20)
			}else{
				p.style.backgroundImage='none'; if(v.close){p.appendChild(g); g.v=1}
				p.style.width=w+'px'; p.style.height=h+'px'; b.style.display=''; this.pos();
				if(v.openjs){v.openjs()}
			}
		},
		ts:function(w,wd,h,hd){
			var cw=parseInt(p.style.width), ch=parseInt(p.style.height);
			if(cw==w&&ch==h){
				clearInterval(p.si); p.style.backgroundImage='none'; b.style.display='block'; if(v.close){p.appendChild(g); g.v=1}
				if(v.openjs){v.openjs()}
			}else{
				if(cw!=w){p.style.width=(w-Math.floor(Math.abs(w-cw)*.6)*wd)+'px'}
				if(ch!=h){p.style.height=(h-Math.floor(Math.abs(h-ch)*.6)*hd)+'px'}
				this.pos()
			}
		},
		top:function(){return document.documentElement.scrollTop||document.body.scrollTop},
		width:function(){return self.innerWidth||document.documentElement.clientWidth||document.body.clientWidth},
		height:function(){return self.innerHeight||document.documentElement.clientHeight||document.body.clientHeight},
		total:function(d){
			var b=document.body, e=document.documentElement;
			return d?Math.max(Math.max(b.scrollHeight,e.scrollHeight),Math.max(b.clientHeight,e.clientHeight)):
			Math.max(Math.max(b.scrollWidth,e.scrollWidth),Math.max(b.clientWidth,e.clientWidth))
		}
	}
}();

function addslashes(str) {
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\0/g,'\\0');
	return str;
}

WP.tooltip=function(){
	var id='tooltip', z=80, o=3, t,m,a,x,h,p;
	return{
		show:function(c,top,left){
		  if(t==null){
			  t=document.createElement('div'); t.id=id;
			  m=document.createElement('div'); m.id=id+'content';
			  a=document.createElement('div'); a.id=id+'arrow';
			  t.style.opacity=z/100; t.style.filter='alpha(opacity='+z+')';
			  t.appendChild(m); t.appendChild(a); document.body.appendChild(t);
			  t.p=new Function('event','WP.tooltip.pos(event)')
		  }
		  m.innerHTML=c; t.style.display='block'; t.style.width='';
		  x=t.offsetWidth+20; t.style.width=x+'px';
		  h=parseInt(t.offsetHeight)+o; p=WP.page.width();
		  if(top){
          	t.style.left=(left-(x/2))+'px'; t.style.top=(top-(h/2)-21)+'px'
		  }else{
		  	T$$$()?document.attachEvent('onmousemove',t.p):document.addEventListener('mousemove',t.p,1)
		  }
		},
		pos:function(e){
		  var u=WP.cursor.top(e), l=WP.cursor.left(e), d=x/2;
		  if(p-l+10<d){l=p-d-10}
			t.style.top=(u-h)+'px'; t.style.left=(l-d)+'px'
		},
		hide:function(){
		  t.style.display='none'; t.style.top=t.style.left='-100px';
		  T$$$()?document.detachEvent('onmousemove',t.p):document.removeEventListener('mousemove',t.p,1)
		}
	};
}();

WP.scroller=function(){
	return{
		init:function(a,c,b,s,d){
			a=T$(a); a.c=c; a.s=s; c=T$(c); b=T$(b); s=T$(s); a.n=d||0;
			b.style.display='block'; a.style.overflow='hidden';
			var h=a.offsetHeight, t=c.offsetHeight-7;
			if(t<h){
				b.style.display='none'
			}else{
				a.m=h-t; a.d=t/h; s.style.height=(h*(h/t))+'px'; s.style.top=b.style.top=0;
				s.onmousedown=function(event){WP.scroller.st(event,a.id); return false};
				s.onselectstart=function(){return false}
			}
			a.l=b.offsetHeight-s.offsetHeight
		},
		st:function(e,f){
			var a=T$(f), s=T$(a.s); a.bcs=WP.cursor.top(e); a.bct=parseInt(s.style.top);
			if(a.mv){this.sp(f)}
			a.mv=function(event){WP.scroller.mv(event,f)};
			a.sp=function(){WP.scroller.sp(f)};
			if(T$$$()){
				document.attachEvent('onmousemove',a.mv); document.attachEvent('onmouseup',a.sp)
			}else{
				document.addEventListener('mousemove',a.mv,1); document.addEventListener('mouseup',a.sp,1)
			}
			if(a.d){s.className+=' '+a.n}
		},
		mv:function(e,f){
			var a=T$(f), m=WP.cursor.top(e)-a.bcs+a.bct, s=T$(a.s), c=T$(a.c);
			if(m>=0&&m<a.l){
				s.style.top=m+'px'; c.style.top=(m*-1*a.d)+'px'
			}else if(m<0){
				s.style.top=0; c.style.top=0
			}else if(m>a.l){
				s.style.top=a.l+'px'; c.style.top=a.m+'px'
			}
		},
		sp:function(f){
			var a=T$(f), s=T$(a.s); if(a.d){s.className=s.className.replace(' '+a.n,'')}
			if(T$$$()){
				document.detachEvent('onmousemove',a.mv); document.detachEvent('onmouseup',a.sp)
			}else{
				document.removeEventListener('mousemove',a.mv,1); document.removeEventListener('mouseup',a.sp,1)
			}
			a.mv=0;
		}
	}
}();

WP.page=function(){
	return{
		width:function(){return self.innerWidth||document.documentElement.clientWidth||document.body.clientWidth}
	}
}();

WP.cursor=function(){
	return{
		top:function(e){
		  return T$$$()?window.event.clientY+document.documentElement.scrollTop+document.body.scrollTop:e.clientY+window.scrollY
		},
		left:function(e){
		  return T$$$()?window.event.clientX+document.documentElement.scrollLeft+document.body.scrollLeft:e.clientX+window.scrollX
		}
	}
}();

WP.email=function(){
	return{
		send:function(){
			var yourname=escape(T$('yourname').value), recipientname=escape(T$('recipientname').value), recipientemail=escape(T$('recipientemail').value);
			if(yourname==''||yourname=='Your Name'){
				alert('You must enter your name.');
			}else if(recipientname==''||recipientname=='Recipient Name'){
				alert('You must enter the recipient name.');
			}else if(recipientemail==''||recipientemail=='Recipient Email'){
				alert('You must enter the recipient email.');
			}else{
				var message=escape(T$('personalizedmessage').value), agentemail=T$('agentemail').value, post='yourname='+yourname+'&recipientname='+recipientname+'&recipientemail='+recipientemail+'&message='+message+'&agentemail='+agentemail;
				var url='/hunting-land/send-email/' + T$('entryid').value;
				TINY.box.fill(url,1,post,1,300,16);
			}
		}
	};
}();

WP.map=function(){
	return{
		resize:function(d){
			var c=T$("mapwrapper");
			if(d){
				c.style.position="absolute"; c.style.width="100%"; c.style.height="100%"; c.style.top="0px"; c.style.left="0px";
				var close=document.createElement("div"); close.id="resizemap"; close.title="Return to Listings"; close.onclick=function(){WP.map.resize(0)}; document.body.appendChild(close)
			}else{
				c.style.position=""; c.style.width=""; c.style.height=""; c.style.top=""; c.style.left="";
				var close=T$('resizemap'); document.body.removeChild(close);
			}
			var center = map.getCenter(); 
			google.maps.event.trigger(map, 'resize');
			map.panTo(center); 
		}
	};
}();

var map, marker, tooltip, mc;

function initMap(zoomLevel, clusterZoom){
var markers = [], i = 0, total = properties.length, image = 'http://static.whitetailpropertiessouth.com/images/marker.png', mc;
var bounds = new google.maps.LatLngBounds();

map = new google.maps.Map(T$("map"), {
	zoom: 4,
	center: new google.maps.LatLng(37, -88),
	mapTypeId: google.maps.MapTypeId.ROADMAP
});

for (i; i < total; i++) {
	var pos = new google.maps.LatLng(properties[i].lat, properties[i].lng);
	marker = new google.maps.Marker({
		position: pos,
		map: map
	});

	bounds.extend(pos);
	markers.push(marker);

	google.maps.event.addListener(marker, 'click', (function(marker, i) {
		return function() {
			var url = '/properties/tooltip/' + properties[i].id;
			WP.ajax.call(url,marker);
		}
	})(marker, i));
}

google.maps.event.addListener(map, 'zoom_changed', function() {
    zoomChangeBoundsListener = 
        google.maps.event.addListener(map, 'bounds_changed', function(event) {
            if (this.getZoom() > zoomLevel && this.initialZoom == true) {
                this.setZoom(zoomLevel);
                this.initialZoom = false;
            }
        google.maps.event.removeListener(zoomChangeBoundsListener);
    });
});

map.initialZoom = true;
map.fitBounds(bounds);

var options = {gridSize: 30, maxZoom: clusterZoom};

mc = new MarkerClusterer(map, markers, options);
}

function InfoBox(opts){
	google.maps.OverlayView.call(this);
	this.latlng_ = opts.latlng;
	this.map_ = opts.map;
	this.content_ = opts.content;
	var box = this;
	this.boundsChangedListener_ = google.maps.event.addListener(this.map_, "bounds_changed", function(){return box.panMap.apply(box)});
	this.setMap(this.map_);
}

InfoBox.prototype = new google.maps.OverlayView();

InfoBox.prototype.remove = function(){
	if (this.div_){
		this.div_.parentNode.removeChild(this.div_);
		this.div_ = null
	}
};

InfoBox.prototype.draw = function(){
	this.createElement();
	if (!this.div_){return}
	var pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
	if (!pixPosition){return}
	this.div_.style.left = (pixPosition.x - 152) + "px";
	this.div_.style.top = (pixPosition.y - 152) + "px";
	this.div_.style.display = 'block';
};


InfoBox.prototype.createElement = function(){
	var panes = this.getPanes();
	var div = this.div_;

	if (!div) {
		var div = this.div_ = document.createElement("div");
		div.id = "tt";
		var close = document.createElement("div");
		close.id = "ttclose";
		var content = document.createElement("div");
		content.id = "ttcontent";
    	content.innerHTML = this.content_;
		content.style.backgroundImage='url(/static/images/spinner.gif)';
		div.style.display = "none";

		div.appendChild(close);
		div.appendChild(content);

		function removeInfoBox(ib) {
			return function(){ib.setMap(null)}
		}

		google.maps.event.addDomListener(close, 'click', removeInfoBox(this));

		panes.floatPane.appendChild(div);
		this.panMap();
	}else if(div.parentNode != panes.floatPane){
		div.parentNode.removeChild(div);
		panes.floatPane.appendChild(div);
	}
}

InfoBox.prototype.panMap = function() {
	var map = this.map_;
	var bounds = map.getBounds();
	if(!bounds){return}
	
	var position = this.latlng_;
	var iwWidth = 304;
	var iwHeight = 152;
	var iwOffsetX = -152;
	var iwOffsetY = -173;
	var padX = 60;
	var padY = 60;
	var mapDiv = map.getDiv();
	var mapWidth = mapDiv.offsetWidth;
	var mapHeight = mapDiv.offsetHeight;
	var boundsSpan = bounds.toSpan();
	var longSpan = boundsSpan.lng();
	var latSpan = boundsSpan.lat();
	var degPixelX = longSpan / mapWidth;
	var degPixelY = latSpan / mapHeight;
	var mapWestLng = bounds.getSouthWest().lng();
	var mapEastLng = bounds.getNorthEast().lng();
	var mapNorthLat = bounds.getNorthEast().lat();
	var mapSouthLat = bounds.getSouthWest().lat();
	var iwWestLng = position.lng() + (iwOffsetX - padX) * degPixelX;
	var iwEastLng = position.lng() + (iwOffsetX + iwWidth + padX) * degPixelX;
	var iwNorthLat = position.lat() - (iwOffsetY - padY) * degPixelY;
	var iwSouthLat = position.lat() - (iwOffsetY + iwHeight + padY) * degPixelY;
	var shiftLng = (iwWestLng < mapWestLng ? mapWestLng - iwWestLng : 0) + (iwEastLng > mapEastLng ? mapEastLng - iwEastLng : 0);
	var shiftLat = (iwNorthLat > mapNorthLat ? mapNorthLat - iwNorthLat : 0) + (iwSouthLat < mapSouthLat ? mapSouthLat - iwSouthLat : 0);
	var center = map.getCenter();
	var centerX = center.lng() - shiftLng;
	var centerY = center.lat() - shiftLat;
	
	map.setCenter(new google.maps.LatLng(centerY, centerX));
	
	google.maps.event.removeListener(this.boundsChangedListener_);
	this.boundsChangedListener_ = null;
};

function MarkerClusterer(map,opt_markers,opt_options){this.extend(MarkerClusterer,google.maps.OverlayView);this.map_=map;this.markers_=[];this.clusters_=[];this.sizes=[53,56,66,78,90];this.styles_=[];this.ready_=false;var options=opt_options||{};this.gridSize_=options['gridSize']||60;this.maxZoom_=options['maxZoom']||null;this.styles_=options['styles']||[];this.imagePath_=options['imagePath']||this.MARKER_CLUSTER_IMAGE_PATH_;this.imageExtension_=options['imageExtension']||this.MARKER_CLUSTER_IMAGE_EXTENSION_;this.zoomOnClick_=true;if(options['zoomOnClick']!=undefined){this.zoomOnClick_=options['zoomOnClick'];}this.averageCenter_=false;if(options['averageCenter']!=undefined){this.averageCenter_=options['averageCenter'];}this.setupStyles_();this.setMap(map);this.prevZoom_=this.map_.getZoom();var that=this;google.maps.event.addListener(this.map_,'zoom_changed',function(){var maxZoom=that.map_.mapTypes[that.map_.getMapTypeId()].maxZoom;var zoom=that.map_.getZoom();if(zoom<0||zoom>maxZoom){return;}if(that.prevZoom_!=zoom){that.prevZoom_=that.map_.getZoom();that.resetViewport();}});google.maps.event.addListener(this.map_,'idle',function(){that.redraw();});if(opt_markers&&opt_markers.length){this.addMarkers(opt_markers,false);}}MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_PATH_='http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/'+'images/m';MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_EXTENSION_='png';MarkerClusterer.prototype.extend=function(obj1,obj2){return(function(object){for(var property in object.prototype){this.prototype[property]=object.prototype[property];}return this;}).apply(obj1,[obj2]);};MarkerClusterer.prototype.onAdd=function(){this.setReady_(true);};MarkerClusterer.prototype.draw=function(){};MarkerClusterer.prototype.setupStyles_=function(){if(this.styles_.length){return;}for(var i=0,size;size=this.sizes[i];i++){this.styles_.push({url:this.imagePath_+(i+1)+'.'+this.imageExtension_,height:size,width:size});}};MarkerClusterer.prototype.setStyles=function(styles){this.styles_=styles;};MarkerClusterer.prototype.getStyles=function(){return this.styles_;};MarkerClusterer.prototype.isZoomOnClick=function(){return this.zoomOnClick_;};MarkerClusterer.prototype.isAverageCenter=function(){return this.averageCenter_;};MarkerClusterer.prototype.getMarkers=function(){return this.markers_;};MarkerClusterer.prototype.getTotalMarkers=function(){return this.markers_.length;};MarkerClusterer.prototype.setMaxZoom=function(maxZoom){this.maxZoom_=maxZoom;};MarkerClusterer.prototype.getMaxZoom=function(){return this.maxZoom_||this.map_.mapTypes[this.map_.getMapTypeId()].maxZoom;};MarkerClusterer.prototype.calculator_=function(markers,numStyles){var index=0;var count=markers.length;var dv=count;while(dv!==0){dv=parseInt(dv/10,10);index++;}index=Math.min(index,numStyles);return{text:count,index:index};};MarkerClusterer.prototype.setCalculator=function(calculator){this.calculator_=calculator;};MarkerClusterer.prototype.getCalculator=function(){return this.calculator_;};MarkerClusterer.prototype.addMarkers=function(markers,opt_nodraw){for(var i=0,marker;marker=markers[i];i++){this.pushMarkerTo_(marker);}if(!opt_nodraw){this.redraw();}};MarkerClusterer.prototype.pushMarkerTo_=function(marker){marker.setVisible(false);marker.setMap(null);marker.isAdded=false;if(marker['draggable']){var that=this;google.maps.event.addListener(marker,'dragend',function(){marker.isAdded=false;that.resetViewport();that.redraw();});}this.markers_.push(marker);};MarkerClusterer.prototype.addMarker=function(marker,opt_nodraw){this.pushMarkerTo_(marker);if(!opt_nodraw){this.redraw();}};MarkerClusterer.prototype.removeMarker_=function(marker){var index=-1;if(this.markers_.indexOf){index=this.markers_.indexOf(marker);}else{for(var i=0,m;m=this.markers_[i];i++){if(m==marker){index=i;break;}}}if(index==-1){return false;}this.markers_.splice(index,1);marker.setVisible(false);marker.setMap(null);return true;};MarkerClusterer.prototype.removeMarker=function(marker,opt_nodraw){var removed=this.removeMarker_(marker);if(!opt_nodraw&&removed){this.resetViewport();this.redraw();return true;}else{return false;}};MarkerClusterer.prototype.removeMarkers=function(markers,opt_nodraw){var removed=false;for(var i=0,marker;marker=markers[i];i++){var r=this.removeMarker_(marker);removed=removed||r;}if(!opt_nodraw&&removed){this.resetViewport();this.redraw();return true;}};MarkerClusterer.prototype.setReady_=function(ready){if(!this.ready_){this.ready_=ready;this.createClusters_();}};MarkerClusterer.prototype.getTotalClusters=function(){return this.clusters_.length;};MarkerClusterer.prototype.getMap=function(){return this.map_;};MarkerClusterer.prototype.setMap=function(map){this.map_=map;};MarkerClusterer.prototype.getGridSize=function(){return this.gridSize_;};MarkerClusterer.prototype.setGridSize=function(size){this.gridSize_=size;};MarkerClusterer.prototype.getExtendedBounds=function(bounds){var projection=this.getProjection();var tr=new google.maps.LatLng(bounds.getNorthEast().lat(),bounds.getNorthEast().lng());var bl=new google.maps.LatLng(bounds.getSouthWest().lat(),bounds.getSouthWest().lng());var trPix=projection.fromLatLngToDivPixel(tr);trPix.x+=this.gridSize_;trPix.y-=this.gridSize_;var blPix=projection.fromLatLngToDivPixel(bl);blPix.x-=this.gridSize_;blPix.y+=this.gridSize_;var ne=projection.fromDivPixelToLatLng(trPix);var sw=projection.fromDivPixelToLatLng(blPix);bounds.extend(ne);bounds.extend(sw);return bounds;};MarkerClusterer.prototype.isMarkerInBounds_=function(marker,bounds){return bounds.contains(marker.getPosition());};MarkerClusterer.prototype.clearMarkers=function(){this.resetViewport();this.markers_=[];};MarkerClusterer.prototype.resetViewport=function(){for(var i=0,cluster;cluster=this.clusters_[i];i++){cluster.remove();}for(var i=0,marker;marker=this.markers_[i];i++){marker.isAdded=false;marker.setMap(null);marker.setVisible(false);}this.clusters_=[];};MarkerClusterer.prototype.redraw=function(){this.createClusters_();};MarkerClusterer.prototype.distanceBetweenPoints_=function(p1,p2){if(!p1||!p2){return 0;}var R=6371;var dLat=(p2.lat()-p1.lat())*Math.PI/180;var dLon=(p2.lng()-p1.lng())*Math.PI/180;var a=Math.sin(dLat/2)*Math.sin(dLat/2)+Math.cos(p1.lat()*Math.PI/180)*Math.cos(p2.lat()*Math.PI/180)*Math.sin(dLon/2)*Math.sin(dLon/2);var c=2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));var d=R*c;return d;};MarkerClusterer.prototype.addToClosestCluster_=function(marker){var distance=40000;var clusterToAddTo=null;var pos=marker.getPosition();for(var i=0,cluster;cluster=this.clusters_[i];i++){var center=cluster.getCenter();if(center){var d=this.distanceBetweenPoints_(center,marker.getPosition());if(d<distance){distance=d;clusterToAddTo=cluster;}}}if(clusterToAddTo&&clusterToAddTo.isMarkerInClusterBounds(marker)){clusterToAddTo.addMarker(marker);}else{var cluster=new Cluster(this);cluster.addMarker(marker);this.clusters_.push(cluster);}};MarkerClusterer.prototype.createClusters_=function(){if(!this.ready_){return;}var mapBounds=new google.maps.LatLngBounds(this.map_.getBounds().getSouthWest(),this.map_.getBounds().getNorthEast());var bounds=this.getExtendedBounds(mapBounds);for(var i=0,marker;marker=this.markers_[i];i++){if(!marker.isAdded&&this.isMarkerInBounds_(marker,bounds)){this.addToClosestCluster_(marker);}}};function Cluster(markerClusterer){this.markerClusterer_=markerClusterer;this.map_=markerClusterer.getMap();this.gridSize_=markerClusterer.getGridSize();this.averageCenter_=markerClusterer.isAverageCenter();this.center_=null;this.markers_=[];this.bounds_=null;this.clusterIcon_=new ClusterIcon(this,markerClusterer.getStyles(),markerClusterer.getGridSize());}Cluster.prototype.isMarkerAlreadyAdded=function(marker){if(this.markers_.indexOf){return this.markers_.indexOf(marker)!=-1;}else{for(var i=0,m;m=this.markers_[i];i++){if(m==marker){return true;}}}return false;};Cluster.prototype.addMarker=function(marker){if(this.isMarkerAlreadyAdded(marker)){return false;}if(!this.center_){this.center_=marker.getPosition();this.calculateBounds_();}else{if(this.averageCenter_){var l=this.markers_.length+1;var lat=(this.center_.lat()*(l-1)+marker.getPosition().lat())/l;var lng=(this.center_.lng()*(l-1)+marker.getPosition().lng())/l;this.center_=new google.maps.LatLng(lat,lng);this.calculateBounds_();}}if(this.markers_.length==0){marker.setMap(this.map_);marker.setVisible(true);}else if(this.markers_.length==1){this.markers_[0].setMap(null);this.markers_[0].setVisible(false);}marker.isAdded=true;this.markers_.push(marker);this.updateIcon();return true;};Cluster.prototype.getMarkerClusterer=function(){return this.markerClusterer_;};Cluster.prototype.getBounds=function(){var bounds=new google.maps.LatLngBounds(this.center_,this.center_);var markers=this.getMarkers();for(var i=0,marker;marker=markers[i];i++){bounds.extend(marker.getPosition());}return bounds;};Cluster.prototype.remove=function(){this.clusterIcon_.remove();this.markers_.length=0;delete this.markers_;};Cluster.prototype.getSize=function(){return this.markers_.length;};Cluster.prototype.getMarkers=function(){return this.markers_;};Cluster.prototype.getCenter=function(){return this.center_;};Cluster.prototype.calculateBounds_=function(){var bounds=new google.maps.LatLngBounds(this.center_,this.center_);this.bounds_=this.markerClusterer_.getExtendedBounds(bounds);};Cluster.prototype.isMarkerInClusterBounds=function(marker){return this.bounds_.contains(marker.getPosition());};Cluster.prototype.getMap=function(){return this.map_;};Cluster.prototype.updateIcon=function(){var zoom=this.map_.getZoom();var mz=this.markerClusterer_.getMaxZoom();if(zoom>mz){for(var i=0,marker;marker=this.markers_[i];i++){marker.setMap(this.map_);marker.setVisible(true);}return;}if(this.markers_.length<2){this.clusterIcon_.hide();return;}var numStyles=this.markerClusterer_.getStyles().length;var sums=this.markerClusterer_.getCalculator()(this.markers_,numStyles);this.clusterIcon_.setCenter(this.center_);this.clusterIcon_.setSums(sums);this.clusterIcon_.show();};function ClusterIcon(cluster,styles,opt_padding){cluster.getMarkerClusterer().extend(ClusterIcon,google.maps.OverlayView);this.styles_=styles;this.padding_=opt_padding||0;this.cluster_=cluster;this.center_=null;this.map_=cluster.getMap();this.div_=null;this.sums_=null;this.visible_=false;this.setMap(this.map_);}ClusterIcon.prototype.triggerClusterClick=function(){var markerClusterer=this.cluster_.getMarkerClusterer();google.maps.event.trigger(markerClusterer,'clusterclick',this.cluster_);if(markerClusterer.isZoomOnClick()){this.map_.fitBounds(this.cluster_.getBounds());}};ClusterIcon.prototype.onAdd=function(){this.div_=document.createElement('DIV');if(this.visible_){var pos=this.getPosFromLatLng_(this.center_);this.div_.style.cssText=this.createCss(pos);this.div_.innerHTML=this.sums_.text;}var panes=this.getPanes();panes.overlayImage.appendChild(this.div_);var that=this;google.maps.event.addDomListener(this.div_,'click',function(){that.triggerClusterClick();});};ClusterIcon.prototype.getPosFromLatLng_=function(latlng){var pos=this.getProjection().fromLatLngToDivPixel(latlng);pos.x-=parseInt(this.width_/2,10);pos.y-=parseInt(this.height_/2,10);return pos;};ClusterIcon.prototype.draw=function(){if(this.visible_){var pos=this.getPosFromLatLng_(this.center_);this.div_.style.top=pos.y+'px';this.div_.style.left=pos.x+'px';}};ClusterIcon.prototype.hide=function(){if(this.div_){this.div_.style.display='none';}this.visible_=false;};ClusterIcon.prototype.show=function(){if(this.div_){var pos=this.getPosFromLatLng_(this.center_);this.div_.style.cssText=this.createCss(pos);this.div_.style.display='';}this.visible_=true;};ClusterIcon.prototype.remove=function(){this.setMap(null);};ClusterIcon.prototype.onRemove=function(){if(this.div_&&this.div_.parentNode){this.hide();this.div_.parentNode.removeChild(this.div_);this.div_=null;}};ClusterIcon.prototype.setSums=function(sums){this.sums_=sums;this.text_=sums.text;this.index_=sums.index;if(this.div_){this.div_.innerHTML=sums.text;}this.useStyle();};ClusterIcon.prototype.useStyle=function(){var index=Math.max(0,this.sums_.index-1);index=Math.min(this.styles_.length-1,index);var style=this.styles_[index];this.url_=style['url'];this.height_=style['height'];this.width_=style['width'];this.textColor_=style['textColor'];this.anchor_=style['anchor'];this.textSize_=style['textSize'];this.backgroundPosition_=style['backgroundPosition'];};ClusterIcon.prototype.setCenter=function(center){this.center_=center;};ClusterIcon.prototype.createCss=function(pos){var style=[];if(document.all){style.push('filter:progid:DXImageTransform.Microsoft.AlphaImageLoader('+'sizingMethod=scale,src="'+this.url_+'");');}else{style.push('background-image:url('+this.url_+');');var backgroundPosition=this.backgroundPosition_?this.backgroundPosition_:'0 0';style.push('background-position:'+backgroundPosition+';');}if(typeof this.anchor_==='object'){if(typeof this.anchor_[0]==='number'&&this.anchor_[0]>0&&this.anchor_[0]<this.height_){style.push('height:'+(this.height_-this.anchor_[0])+'px; padding-top:'+this.anchor_[0]+'px;');}else{style.push('height:'+this.height_+'px; line-height:'+this.height_+'px;');}if(typeof this.anchor_[1]==='number'&&this.anchor_[1]>0&&this.anchor_[1]<this.width_){style.push('width:'+(this.width_-this.anchor_[1])+'px; padding-left:'+this.anchor_[1]+'px;');}else{style.push('width:'+this.width_+'px; text-align:center;');}}else{style.push('height:'+this.height_+'px; line-height:'+this.height_+'px; width:'+this.width_+'px; text-align:center;');}var txtColor=this.textColor_?this.textColor_:'black';var txtSize=this.textSize_?this.textSize_:11;style.push('cursor:pointer; top:'+pos.y+'px; left:'+pos.x+'px; color:'+txtColor+'; position:absolute; font-size:'+txtSize+'px; font-family:Arial,sans-serif; font-weight:bold');return style.join('');};window['MarkerClusterer']=MarkerClusterer;MarkerClusterer.prototype['addMarker']=MarkerClusterer.prototype.addMarker;MarkerClusterer.prototype['addMarkers']=MarkerClusterer.prototype.addMarkers;MarkerClusterer.prototype['clearMarkers']=MarkerClusterer.prototype.clearMarkers;MarkerClusterer.prototype['getCalculator']=MarkerClusterer.prototype.getCalculator;MarkerClusterer.prototype['getGridSize']=MarkerClusterer.prototype.getGridSize;MarkerClusterer.prototype['getExtendedBounds']=MarkerClusterer.prototype.getExtendedBounds;MarkerClusterer.prototype['getMap']=MarkerClusterer.prototype.getMap;MarkerClusterer.prototype['getMarkers']=MarkerClusterer.prototype.getMarkers;MarkerClusterer.prototype['getMaxZoom']=MarkerClusterer.prototype.getMaxZoom;MarkerClusterer.prototype['getStyles']=MarkerClusterer.prototype.getStyles;MarkerClusterer.prototype['getTotalClusters']=MarkerClusterer.prototype.getTotalClusters;MarkerClusterer.prototype['getTotalMarkers']=MarkerClusterer.prototype.getTotalMarkers;MarkerClusterer.prototype['redraw']=MarkerClusterer.prototype.redraw;MarkerClusterer.prototype['removeMarker']=MarkerClusterer.prototype.removeMarker;MarkerClusterer.prototype['removeMarkers']=MarkerClusterer.prototype.removeMarkers;MarkerClusterer.prototype['resetViewport']=MarkerClusterer.prototype.resetViewport;MarkerClusterer.prototype['setCalculator']=MarkerClusterer.prototype.setCalculator;MarkerClusterer.prototype['setGridSize']=MarkerClusterer.prototype.setGridSize;MarkerClusterer.prototype['onAdd']=MarkerClusterer.prototype.onAdd;MarkerClusterer.prototype['draw']=MarkerClusterer.prototype.draw;Cluster.prototype['getCenter']=Cluster.prototype.getCenter;Cluster.prototype['getSize']=Cluster.prototype.getSize;Cluster.prototype['getMarkers']=Cluster.prototype.getMarkers;ClusterIcon.prototype['onAdd']=ClusterIcon.prototype.onAdd;ClusterIcon.prototype['draw']=ClusterIcon.prototype.draw;ClusterIcon.prototype['onRemove']=ClusterIcon.prototype.onRemove;
