function addIcon(icon) { // Add icon attributes
 icon.shadow= "/img/googlemaps/cirkel/20_shadow.png";
 icon.iconSize = new GSize(12, 20);
 icon.shadowSize = new GSize(22, 20);
 icon.iconAnchor = new GPoint(6, 20);
 icon.infoWindowAnchor = new GPoint(5, 1);
}


function redrawPolygon(polypoints) {
	polypoints.each(function(polypoint) {
		var latlng = new GLatLng(polypoint.lat,polypoint.lon);
		addPolyMarker(latlng,false);
	});
	drawOverlay(true,false);
	zoomToPolygon();
}

function addPolyMarker(point,manualclick) {
	count++;
	// Purple marker icons
	var icon = new GIcon();
	icon.image = "/img/googlemaps/cirkel/20_orange2.png";
	addIcon(icon);
	
	// Make markers draggable
	var marker = new GMarker(point, {icon:icon, draggable:true, zIndexProcess: mapsOrderOfCreation});
	map.addOverlay(marker);
	marker.content = count;
	markers.push(marker);
	// Drag listener
	GEvent.addListener(marker, "drag", function() {
		mgr.clearMarkers();
		drawOverlay(false,false);
	});
	
	GEvent.addListener(marker, "dragend", function () {
		mgr.clearMarkers();
		drawOverlay(true,true);
	});
	
	
	
	// Second click listener
	GEvent.addListener(marker, "click", function() {
		// Find out which marker to remove
		for(var n = 0; n < markers.length; n++) {
			if(markers[n] == marker) {
				map.removeOverlay(markers[n]);
				break;
			}
		}
		
		// Shorten array of markers and adjust counter
		markers.splice(n, 1);
		if(markers.length == 0) {
			count = 0;
		}
		else {
			count = markers[markers.length-1].content;
			drawOverlay(true,true);
		}
	});
}

function leftClick(overlay, point) {
	if(point) {
		addPolyMarker(point,true);
		drawOverlay(true,true);
	}
	//if (polyarea > 0) zoomToPolygon();
}

function drawOverlay(message,showsearchlbl){
	if(poly) {
		map.removeOverlay(poly); 
	}
	points = Array();
	for(i = 0; i < markers.length; i++) {
		points.push(markers[i].getLatLng());
	}

	points.push(markers[0].getLatLng());
	poly = new GPolygon(points, "#f55424", 3, 0.8, "#f55424", 0.2);
	polyarea = poly.getArea()/(1000*1000);
	if (polyarea > 0) {
		if (message == true) {
			var areafixed = polyarea.toFixed(3);
			mapsmessage = gentrans["poly_info"]+"<br /><a href=\"javascript:;\" class=\"button\" onclick=\"doPolyButtonClick()\">"+gentrans["zkvkh"]+"</a> | <a href=\"javascript:;\" class=\"closelink\" onclick=\"clearMap(); $(\'maps_info\').hide();\">"+gentrans["wd_ann"]+"</a>";
			showMapsMessage(mapsmessage,"info",false);
		}
		if (showsearchlbl == true) {
			setSearchLabel();
		}
	}
	map.addOverlay(poly);
}


function clearMap() {
	map.clearOverlays();
	points.length = 0;
	markers.length = 0;
	count = 0;
	
}
function getHousesInPolygon() {
	mgr.clearMarkers();
	if (markers.length > 2) {
		polyg = {pointspoly:[]};
		for(i = 0; i < markers.length; i++) {
			mrk = markers[i].getLatLng();
			polyg.pointspoly.push({lat:mrk.lat(), lon:mrk.lng(), indx:i});
		 }
		 jso = Object.toJSON(polyg);
		 new Ajax.Request("/ajax/aj_setpoly_v2", { onSuccess: returnGetHousesInPolygon, method: "post", parameters: "polyg="+jso });
	}
}

function returnGetHousesInPolygon(data) {
	var obj = data.responseJSON;
	if (!Object.isUndefined(obj.error)) {
		alert(obj.error);
	}
	else {
		zoomToPolygon();
		doCorsSearch(obj.cors);
	}
}
function pausecomp(millis)  {
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); } 
	while(curDate-date < millis);
} 
function getSecondsBetween(d1,d2) {
	d = (d2.getTime() - d1.getTime()) / 1000;
	return d;
}
function pointsdist(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;
}
polysearcher = null;
function importanceOrder (marker,b) { 
        return marker.importance; 
} 
function setSearchLabel() {
	bounds = poly.getBounds();
	labelpos = bounds.getNorthEast();
	labelpos = bounds.getCenter();
	if (polysearcher != null && !Object.isUndefined(polysearcher)) {
		map.removeOverlay(polysearcher);
		polysearcher = null;
	}
	if (polysearcher == null || Object.isUndefined(polysearcher)) {
		polysearchericon = new GIcon();
		polysearchericon.image = "/img/googlemaps/area_search_"+taal+".png";
		if (taal == "fr") {
			polysearchericon.iconSize = new GSize(200,30);
			polysearchericon.iconAnchor = new GPoint(100, 15);
		}
		else {
			polysearchericon.iconSize = new GSize(174,30);
			polysearchericon.iconAnchor = new GPoint(87, 15);
		}
		polysearcher = new GMarker(labelpos, {draggable: true, icon:polysearchericon, zIndexProcess: mapsOrderOfCreation});
		polysearcher.autoposition = true;
		map.addOverlay(polysearcher);
		GEvent.addListener (polysearcher, "click", doPolyButtonClick);
		GEvent.addListener (polysearcher, "dragend", setAutoPositionButton);
	}
	/* else {
		map.addOverlay(polysearcher);
		if (polysearcher.autoposition) {
			polysearcher.setLatLng(labelpos);
		}
	} */
}

function doPolyButtonClick() {
	//polysearcher.hide();
	getHousesInPolygon();
}

function setAutoPositionButton() {
	polysearcher.autoposition = false;
}

function zoomToPolygon() {
	currzoom = map.getZoom();
	bounds = poly.getBounds();
	if (polysearcher != null) bounds.extend(polysearcher.getLatLng());
	zoomlevel = map.getBoundsZoomLevel(bounds);
	if (currzoom != zoomlevel) {
		map.setCenter(bounds.getCenter(), zoomlevel);
		map.setZoom(map.getBoundsZoomLevel(bounds));
	}
}
