var metric = true;
var radiusCenterOptions = null;
var radiusResizeOptions = null;
var radiusDeleteOptions = null;
var radiusSearchOptions = null;
var myObject = null;

function createCircle(point, radius) {
	if (radiusCenterOptions == null) initRadiusIcons();
	radiusQuery = new RadiusSearch();
	radiusQuery.initializeCircle(radius, point, map);
	myQueryControl.addRadiusSearch(radiusQuery);
	radiusQuery.render();
	radiusQuery.zoomToCircle();
	removeClickListener();
}

function redrawCircle(radiusdata) {
	createQueryControl();
	point = new GLatLng(radiusdata.lat,radiusdata.lon);
	createCircle(point, radiusdata.dist);
}

function initRadiusIcons() {
	radiusCenterOptions = new Object();
	radiusResizeOptions = new Object();
	radiusDeleteOptions = new Object();
	radiusSearchOptions = new Object();
	
	radiusCenterOptions.icon = new GIcon();
	radiusCenterOptions.icon.image = "/img/googlemaps/arrcenter2.png";
	radiusCenterOptions.icon.iconSize = new GSize(28,28);
	radiusCenterOptions.icon.iconAnchor = new GPoint(14, 14);
	radiusCenterOptions.draggable = true;
	radiusCenterOptions.bouncy = false;
	radiusCenterOptions.zIndexProcess = mapsOrderOfCreation;
	
	radiusResizeOptions.icon = new GIcon();
	radiusResizeOptions.icon.image = "/img/googlemaps/cirkel/cirkel_size3_"+taal+".png";
	radiusResizeOptions.icon.iconSize = new GSize(172,30);
	radiusResizeOptions.icon.iconAnchor = new GPoint(20, 0);
	radiusResizeOptions.draggable = true;
	radiusCenterOptions.bouncy = false;
	radiusResizeOptions.zIndexProcess = mapsOrderOfCreation;
	
	radiusSearchOptions.icon = new GIcon();
	radiusSearchOptions.icon.image = "/img/googlemaps/cirkel/cirkel_search3_"+taal+".png";
	radiusSearchOptions.icon.iconSize = new GSize(172,30);
	radiusSearchOptions.icon.iconAnchor = new GPoint(20, -28);
	radiusSearchOptions.zIndexProcess = mapsOrderOfCreation;
	
	radiusDeleteOptions.icon = new GIcon();
	radiusDeleteOptions.icon.image = "/img/googlemaps/cirkel/cirkel_delete3_"+taal+".png";
	radiusDeleteOptions.icon.iconSize = new GSize(172,30);
	radiusDeleteOptions.icon.iconAnchor = new GPoint(20, -56);
	radiusDeleteOptions.zIndexProcess = mapsOrderOfCreation;
	
}

function destination(orig, hdng, dist) {
	var R = 6371; // earth's mean radius in km
	var oX, oY;
	var x, y;
	var d = dist/R;  // d = angular distance covered on earth's surface
	hdng = hdng * Math.PI / 180; // degrees to radians
	oX = orig.x * Math.PI / 180;
	oY = orig.y * Math.PI / 180;
	
	y = Math.asin( Math.sin(oY)*Math.cos(d) + Math.cos(oY)*Math.sin(d)*Math.cos(hdng) );
	x = oX + Math.atan2(Math.sin(hdng)*Math.sin(d)*Math.cos(oY), Math.cos(d)-Math.sin(oY)*Math.sin(y));
	
	y = y * 180 / Math.PI;
	x = x * 180 / Math.PI;
	return new GLatLng(y, x);
}

function distance(point1, point2) {
	var R = 6371; // earth's mean radius in km
	var lon1 = point1.lng()* Math.PI / 180;
	var lat1 = point1.lat() * Math.PI / 180;
	var lon2 = point2.lng() * Math.PI / 180;
	var lat2 = point2.lat() * Math.PI / 180;
	
	var deltaLat = lat1 - lat2
	var deltaLon = lon1 - lon2
	
	var step1 = Math.pow(Math.sin(deltaLat/2), 2) + Math.cos(lat2) * Math.cos(lat1) * Math.pow(Math.sin(deltaLon/2), 2);
	var step2 = 2 * Math.atan2(Math.sqrt(step1), Math.sqrt(1 - step1));
	return step2 * R;
}

function checkRadiusInput(e) {
	var keynum;
	var keychar;
	var numcheck;
	if(window.event) { keynum = e.keyCode; }
	else if(e.which) { keynum = e.which; }
	
	keychar = String.fromCharCode(keynum);
	numcheck = /\d/;
	if (numcheck.test(keychar)) {
		radiusQuery.updateCircle(3);
	}
}

function RadiusSearch() {

}

RadiusSearch.prototype.CIRCLE='circle';

RadiusSearch.prototype = new RadiusSearch();
RadiusSearch.prototype._map;
RadiusSearch.prototype._type;
RadiusSearch.prototype._radius;
RadiusSearch.prototype._dragHandle;
RadiusSearch.prototype._centerHandle;
RadiusSearch.prototype._searchHandle;
RadiusSearch.prototype._removeHandle;
RadiusSearch.prototype._polyline;
RadiusSearch.prototype._color;
RadiusSearch.prototype._control;
RadiusSearch.prototype._points;
RadiusSearch.prototype._dragHandlePosition;
RadiusSearch.prototype._centerHandlePosition;
RadiusSearch.prototype._removeHandlePosition;
RadiusSearch.prototype._searchHandlePosition;

RadiusSearch.prototype.initializeCircle = function(radius, point, map) {
	this._type = this.CIRCLE;
	this._radius = radius;
	this._map = map;
	this._color = "#F55424";
	this._dragHandlePosition = destination(point, 90, this._radius);
	this._dragHandle = new GMarker(this._dragHandlePosition, radiusResizeOptions);
	this._removeHandlePosition = this._dragHandlePosition;
	this._removeHandle = new GMarker(this._removeHandlePosition, radiusDeleteOptions);
	this._searchHandlePosition = this._dragHandlePosition;
	this._searchHandle = new GMarker(this._searchHandlePosition, radiusSearchOptions);
	this._centerHandlePosition = point;
	this._centerHandle = new GMarker(this._centerHandlePosition, radiusCenterOptions);
	map.addOverlay(this._dragHandle);
	map.addOverlay(this._centerHandle);
	map.addOverlay(this._searchHandle);
	map.addOverlay(this._removeHandle);
	myObject = this;
	GEvent.addListener (this._dragHandle, "dragend", function() {myObject.updateCircle(1); myObject.zoomToCircle(); });
	GEvent.addListener (this._dragHandle, "drag", function() {myObject.updateCircle(1);});
	GEvent.addListener(this._centerHandle, "dragend", function() {myObject.updateCircle(2); myObject.zoomToCircle(); });
	GEvent.addListener(this._centerHandle, "drag", function() {myObject.updateCircle(2);});
	GEvent.addListener(this._removeHandle, "click", function() { setMapsPoint(); });
	GEvent.addListener(this._searchHandle, "click", function() { myObject.getHousesInRadius() });
}

RadiusSearch.prototype.updateCircle = function (type) {
	this._map.removeOverlay(this._polyline);
	switch (type) {
		case 1:
			distn = distance(this._centerHandlePosition, this._dragHandlePosition);
			distn = distn.toFixed(1);
			this._dragHandlePosition = this._dragHandle.getPoint();
			this._radius = distn;
			searchradius = distn;
			this._removeHandle.setPoint(this._dragHandlePosition);
			this._searchHandle.setPoint(this._dragHandlePosition);
			break;
	 
		case 2:
			this._centerHandlePosition = this._centerHandle.getPoint();
			this._dragHandle.setPoint(this.getEast());
			this._removeHandle.setPoint(this.getEast());
			this._searchHandle.setPoint(this.getEast());
			break;
		case 3:
			dist = $('txtradius').value;
			this._dragHandlePosition = this._dragHandle.getPoint();
			this._removeHandlePosition = this._dragHandlePosition;
			this._searchHandlePosition = this._dragHandlePosition;
			this._radius = dist.toFixed(1);
			searchradius = this._radius;
	}
	this.render();
}

RadiusSearch.prototype.zoomToCircle = function () {
	bounds = this._polyline.getBounds();
	zoomlevel = map.getBoundsZoomLevel(bounds);
	zoomlevel--;
	map.setCenter(bounds.getCenter(), zoomlevel);
	map.setZoom(map.getBoundsZoomLevel(bounds));
}

RadiusSearch.prototype.render = function() {
	if (this._type == this.CIRCLE) {
		this._points = [];
		var distance = this._radius;
		for (i = 0; i < 72; i++) {
			this._points.push(destination(this._centerHandlePosition, i * 360/72, distance));
		}
		this._points.push(destination(this._centerHandlePosition, 0, distance) );
		//this._polyline = new GPolyline(this._points, this._color, 6);
		this._polyline = new GPolygon(this._points, this._color, 1, 1, this._color, 0.2);
		this._map.addOverlay(this._polyline);
		this._control.render();
	}
}

RadiusSearch.prototype.remove = function() {
	this._map.removeOverlay(this._polyline);
	this._map.removeOverlay(this._dragHandle);
	this._map.removeOverlay(this._centerHandle);
	this._map.removeOverlay(this._removeHandle);
	this._map.removeOverlay(this._searchHandle);
}

RadiusSearch.prototype.getRadius = function() {
    return this._radius;
}

RadiusSearch.prototype.getHTML = function() {
	// return "<span><font color='"+ this._color + "''>" + this.getDistHtml() + "</font></span>";
	return this.getDistHtml();
}

RadiusSearch.prototype.getDistHtml = function() {
	if (this._radius < 1) {
		dist = this._radius;
	} else {
		dist = this._radius;
	}
	params = "dist="+dist+"&index="+this._control.getIndex(this);
	mapsmssg = gentrans["radius_km"]+" "+dist+" <a href=\"javascript:;\" class=\"button\" onclick=\"myObject.getHousesInRadius()\">"+gentrans["zkvkh"]+"</a> | <a href=\"javascript:;\" onclick=\"setMapsPoint();\">"+gentrans["wd_ann"]+"</a>";
	showMapsMessage(mapsmssg,"info",false);
	result = "";
	return result;
}

RadiusSearch.prototype.getNorth = function() {
  return this._points[0];
}

RadiusSearch.prototype.getSouth = function() {
  return this._points[(72/2)];
}

RadiusSearch.prototype.getEast = function() {
  return this._points[(72/4)];
}

RadiusSearch.prototype.getWest = function() {
  return this._points[(72/4*3)];
}

RadiusSearch.prototype.getHousesInRadius = function() {
	corsparam = getMapsRadiusParam(this._centerHandlePosition, this._radius, "");
	doCorsSearch(corsparam);
}

function QueryControl (localSearch) {
	this._localSearch = localSearch;
}

QueryControl.prototype = new GControl();
QueryControl.prototype._radiusQueries;
QueryControl.prototype._mainDiv;
QueryControl.prototype._queriesDiv;
QueryControl.prototype._timeout;
QueryControl.prototype._localSearch;

QueryControl.prototype.initialize = function(map) {
	this._mainDiv = document.createElement("div");
	this._mainDiv.id = "GQueryControl";
	this._queriesDiv = document.createElement("div");
	this._queriesDiv.id = "queriesDiv";
	this._mainDiv.appendChild(this._queriesDiv);
	
	map.getContainer().appendChild(this._mainDiv);
	this._radiusQueries = new Array();
	return this._mainDiv;
}

QueryControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(80, 40));
}

QueryControl.prototype.addRadiusSearch = function(radiusQuery) {
	this._radiusQueries.push(radiusQuery);
	radiusQuery._control = this;
	ghtml = radiusQuery.getHTML();	
}

QueryControl.prototype.render = function() {
	for (i = 0; i < this._radiusQueries.length; i++) {
		radiusQuery = this._radiusQueries[i];
		radiusQuery.getHTML();
		//$('maps_info').update(radiusQuery.getHTML()).show();
		//this._queriesDiv.childNodes[i].innerHTML = radiusQuery.getHTML();
	}
}

QueryControl.prototype.remove = function(index) {
	this._radiusQueries[index].remove();
	this._queriesDiv.removeChild(this._queriesDiv.childNodes[index]);
	delete this._radiusQueries[index];
	this._radiusQueries.splice(index,1);
	this.render();
}


QueryControl.prototype.getIndex = function(radiusQuery) {
	for (i = 0; i < this._radiusQueries.length; i++) {
		if (radiusQuery == this._radiusQueries[i]) {
		  return i;
		}
	}
	return -1;
}


function showRadiusAddress() {
	if (geocoder == null) {
		geocoder = new GClientGeocoder();
		geocoder.setBaseCountryCode("nl");
	}
	address = $("mapkeyword").value;
	geocoder.getLocations(address, pointListCallBack);
}

function pointListCallBack(result) {
	if (result.Status.code == G_GEO_SUCCESS) {
		if (result.Placemark.length > 1) { 
			// Loop through the results
			var multimssg = gentrans['bedoelde_u'];
			for (var i=0; i<result.Placemark.length; i++) {
				var p = result.Placemark[i].Point.coordinates;
				multimssg += "<br />"+(i+1)+": <a href=\"javascript:;\" onclick=\"selectMultiAdr("+p[1]+","+p[0]+",'"+result.Placemark[i].address+"');\">"+result.Placemark[i].address+"</a>";
			}
			$('multimapkeyword').update(multimssg);
			$('multimapkeyword').show();
		}
		else {
			$('multimapkeyword').update();
			$('multimapkeyword').hide();
			var p = result.Placemark[0].Point.coordinates;
			pointn = new GLatLng(p[1], p[0]);
			corsval = getMapsRadiusParam(pointn, searchradius, address);
			pointCallBack(pointn,corsval);
		}
	}
	else {
		$('multimapkeyword').update("<strong style='color:red;'>"+address+" "+gentrans['niet_gevonden']+"</strong>");
		$('multimapkeyword').show();
	}
}

function getMapsRadiusParam(point, dist, address) {
	corsval = point.lat()+"c"+point.lng()+"c"+dist;
	if (address != "") corsval += "c"+address;
	return corsval;
}

function pointCallBack(point,corsval) {
	if (!point) {
		$('multimapkeyword').update("<strong style='color:red;'>"+address+" "+gentrans['niet_gevonden']+"</strong>");
	}
	else {
		doCorsSearch(corsval);
	}
}
function selectMultiAdr(lat,lon,adr) {
	pointn = new GLatLng(lat, lon);
	$('mapkeyword').value = adr;
	$('multimapkeyword').update("");
	$('multimapkeyword').hide();
	corsval = getMapsRadiusParam(pointn, searchradius, adr);
	doCorsSearch(corsval);
}