var distanceFilter;
function DistanceFilter(){
	distanceFilter = this;
	$svGM = jQuery.fn.svGoogleMaps;
	this.filterByZero = false;
	this.circle = null;
	this.center = null;
	this.placemark = null;
	
	this.run = function() {
		var value = this.getValue();
		this.placemark = this.getPlacemark();
		this.center = null;
		
		var selecty = document.getElementById($svGM.args.mapName+'_distance');
		if (selecty) selecty.onchange = distanceFilter.redrawCircle;
		
		//$svGM.updatedFilters(this.applyFilter($svGM.args.placemarks[$svGM.args.mapName], value, placemark));
		
		if (this.placemark && this.placemark.marker) {
			this.center = this.placemark.marker.getPoint();
		}
		else if (this.placemark)
			this.center = new GLatLng(parseFloat(this.placemark.latitude), parseFloat(this.placemark.longitude));
		if (this.circle != null){
			$svGM.args.m.removeOverlay(this.circle);
			this.circle = null;
		}

		if (this.center != null && value && parseFloat(value) > 0) {
			this.drawCircle(this.center,value);
		}
		
		unfiltered = this.applyFilter($svGM.args.placemarks[$svGM.args.mapName], value, this.placemark);
		
		$svGM.updatedFilters(unfiltered);
		
		jQuery('#gPlacemarkContainer .gTop').get(0).style.display = (unfiltered.length) ? 'block' : 'none';
		jQuery('#gPlacemarkContainer .gBottom').get(0).style.display = (unfiltered.length) ? 'block' : 'none';
		
		if (this.placemark) this.addHead(this.placemark,value,unfiltered.length);
		jQuery('#'+$svGM.args.mapName+'_DistanceFilter').show();
	}

	//Expects an array of placemarks, returns array of all unfiltered placemarks				
	this.applyFilter = function(arr, distance, distanceFrom){
		this.filterByZero = false;
		var unfiltered = new Array();
		//First reset any existing filter
		this.resetFilter(arr);
		//Now apply the new value
		if(distanceFrom != null){
			jQuery('#'+$svGM.args.mapName+'_distanceOrigin').html(distanceFrom.name);
		}
//					unfiltered.minmax = {minLat: 1000,maxLat: -1000,minLng: 1000,maxLng: -1000};
		for(var i = 0; i < arr.length; i++){
			if((this.filterByZero || parseFloat(distance) != 0) && distanceFrom != null){
				arr[i].distance = placemarkDistance(arr[i],distanceFrom);
				arr[i].filteredBy['distance'] = (arr[i].distance >= distance);
			}
			arr[i].filtered = arr[i].filtered || arr[i].filteredBy['distance'] || !arr[i].active;						
			if(!arr[i].filtered)
				unfiltered.push(arr[i]);
		}
		
		return unfiltered;
	}

	//Expects an array of placemarks
	this.resetFilter = function(arr){
		/*if(this.circle){
			$svGM.args.m.removeOverlay(this.circle);
		}*/
		for(var i = 0; i < arr.length; i++){
			//Reset this filter
			arr[i].filteredBy['distance'] = false;
			arr[i].filtered = false;
			//Reapply Filter if there are any additional filters
		}
		this.checkFilters(arr);
		jQuery('#'+$svGM.args.mapName+'_distanceFilter').hide();
	}

	//Expects an array of placemarks - will check all filters and reset filter status based on that
	this.checkFilters = function(arr){
		for(var i = 0; i < arr.length; i++){
			arr[i].filtered = false;
			for(var j in arr[i].filteredBy){
				arr[i].filtered = arr[i].filtered || arr[i].filteredBy[j] || !arr[i].active;
			}
		}
	}

	this.getValue = function(){
		var distance = jQuery('#'+$svGM.args.mapName+'_distance').val();
		distance = parseFloat(distance);
		if (isNaN(distance))
			distance = 0;
		return distance;
	}
	
	this.getPlacemark = function(){
		var prikey = jQuery('#distanceFromID').val();
		var placemark = null;
		if(prikey.length > 0){
			placemark = $svGM.findPlacemark(prikey, $svGM.args.mapName);
		} 
		
		if(placemark != null){
			return placemark;
		}
		else
			return null;
	}

	this.findNearBy = function(prikey){
		jQuery('#distanceFromID').val(prikey);
		this.run();
	}

	
	this.clearDistance = function(){
	}
	
	this.drawCircle = function (center, radius){
		logit('Called: distance.drawCircle - ' + radius);
		var circlePoints = Array();
		var measureLat = new google.maps.LatLng(parseFloat(center.lat())+0.1, parseFloat(center.lng()));
		var measureLng = new google.maps.LatLng(center.lat(), parseFloat(center.lng())+0.1);
		var latConv = center.distanceFrom(measureLat)/160.9344;
		var lngConv = center.distanceFrom(measureLng)/160.9344;
		var map = $svGM.args.m;
		with (Math) {
			for (var i = 0 ; i <= 360 ; i++ ) {
				var newlat = parseFloat(center.lat()) + (radius/latConv * cos(i * PI/180));
				var newlng = parseFloat(center.lng()) + (radius/lngConv * sin(i * PI/180));
				var point = new google.maps.LatLng(newlat,newlng);
				circlePoints.push(point);
			}
		}
		var circle = new google.maps.Polygon(circlePoints, '##0000ff', 1, 1, '##0000ff', 0.2);
		this.circle = circle;
		map.circle = this.circle;
		map.cancelCentering = true;
		map.gmap.addOverlay(this.circle);
		logit('map.gmap.setCenter(' + circle.getBounds().getCenter() + ', ' + map.gmap.getBoundsZoomLevel(circle.getBounds()));
		map.gmap.setCenter(circle.getBounds().getCenter(), map.gmap.getBoundsZoomLevel(circle.getBounds()));
		logit('End: distance.drawCircle - ' + radius);
	}
	
	this.redrawCircle = function () {
		var unfiltered;
		var val = distanceFilter.getValue();
		if (distanceFilter.circle) $svGM.args.m.removeOverlay(distanceFilter.circle);
		if (val) distanceFilter.drawCircle(distanceFilter.center,val);
		unfiltered = distanceFilter.applyFilter($svGM.args.placemarks[$svGM.args.mapName],val,distanceFilter.placemark);
		$svGM.updatedFilters(unfiltered);
		if (distanceFilter.placemark) distanceFilter.addHead(distanceFilter.placemark,val,unfiltered.length);
	}
	
	this.addHead = function (placemark,distance,resultsLength) {
		var txt,phead,container,pcontent,span;
		
		if (!distance) {
			jQuery('#gPlacemarkHeader').hide();
			return false;
		}
		
		txt = distance+' mile radius from '+placemark.name+' <img src="'+placemark.icon.image+'" align="absmiddle" alt="'+placemark.name+'" border="0"/>';
		pcontent = '<br/><span>Begin by selecting a category from the left.</span>';
		if (!resultsLength) txt += pcontent;
		
		phead = document.getElementById('gPlacemarkHeader');
		
		if (!phead) {
			container = jQuery('#gPlacemarkContainer .gHeader').get(0);
			if (!container) return false;
			phead = document.createElement('div');
			phead.id = 'gPlacemarkHeader';
			container.appendChild(phead);
		}
		else phead.style.display = 'block';
		
		phead.innerHTML = txt;
		
		
		jQuery('#gPlacemarkContainer').show();
	}
}

