// adding prototyte
// adding distance fron function to api v3
initMap = function () {
	if(typeof(google.maps.LatLng.distanceFrom) == 'undefined') {
		google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
			//var R = 6371; // km (change this constant to get miles)
			var R = 6371000; // meters
			var lat1 = this.lat();
			var lon1 = this.lng();
			var lat2 = newLatLng.lat();
			var lon2 = newLatLng.lng();
			var dLat = (lat2-lat1) * Math.PI / 180;
			var dLon = (lon2-lon1) * Math.PI / 180;
			var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * 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;
		}
	}
	
	window.getMap = function (mapId,address,zoomLevel,radius,quality) {
		// finding address using Geocoder
		var geocoder = new google.maps.Geocoder();
		
		geocoder.geocode( { 'address': address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var myOptions = {
					zoom: zoomLevel,
					center: results[0].geometry.location,
					mapTypeId: google.maps.MapTypeId.ROADMAP
				}
				
				var map = new google.maps.Map(document.getElementById(mapId), myOptions);
			
				var marker = new google.maps.Marker({
					map: map, 
					position: results[0].geometry.location
				});
	
				drawCircle(map,results[0].geometry.location,radius,quality);
		
			} else {
				alert("Geocode was not successful for the following reason: " + status);
			}
		});
	}
			
	window.drawCircle = function (map,center, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa) {
			
		//calculating km/degree
		var latConv = center.distanceFrom(new google.maps.LatLng(center.lat()+0.1, center.lng()))/100;
		var lngConv = center.distanceFrom(new google.maps.LatLng(center.lat(), center.lng()+0.1))/100;
	
		//Loop all degrees in a circle
		var points = [];
		var step = parseInt(360/nodes)||10;
		for(var i=0; i<=360; i+=step) {
			var pint = new google.maps.LatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + (radius/lngConv * Math.sin(i * Math.PI/180)));
	
			points.push(pint);
		}
	
		points.push(points[0]); 
		fillColor = fillColor||liColor||"#0055ff";
		liWidth = liWidth||2;
	
		var poly = new google.maps.Polygon({
			paths: points,
			strokeColor: "#FF0000",
			strokeOpacity: 0.8,
			strokeWeight: 2,
			fillColor: fillColor,
			fillOpacity: fillOpa
		});
	
		poly.setMap(map);
	
	}
	
	window.getMaps();
}



addMap = function (mapId,address,zoomLevel,radius,quality) {
	
	if(!window.mapInstances) {
		window.mapInstances = [];
	
	}
	
	window.mapInstances.push([mapId,address,zoomLevel,radius,quality]);
	
}

getMaps = function () {

	for(var x = 0;x < window.mapInstances.length; x++) {
		getMap(window.mapInstances[x][0],window.mapInstances[x][1],window.mapInstances[x][2],window.mapInstances[x][3],window.mapInstances[x][4]);
	
	}

}
