google.maps.Polygon.prototype.addPoint = addPoint;
function addPoint(LatLng) {
	var coords = this.getPath();
	coords.push(LatLng);
}

google.maps.Polygon.prototype.del = del;
function del() {
	this.setMap(null);
	try {
		this.window.close();
	} catch(err) {}
	
	try {
		for (var i = 0; i < this.tempMarkers.getLength();i++){
			var marker = this.tempMarkers.getAt(i);
			marker.setMap(null);
		}	
		} catch(err) {}
}

google.maps.Polygon.prototype.ClickAction = ClickAction;
function ClickAction(objNr) {
	if (this.markers && this.addmarkers) {
		var erasemarker;
		for (var i=0; i < this.markers.getLength();i++) {
			erasemarker = this.markers.getAt(i);
			erasemarker.setMap(null);
		}
		for (var i=0; i < this.addmarkers.getLength();i++) {
			erasemarker = this.addmarkers.getAt(i);
			erasemarker.setMap(null);
		}	
	}
	var str = "<div id='inputFieldBOX' class='inputFieldBOX'>";
	str += '<div id="open" onclick="minimize(&#34;inputFieldBOX&#34;,this)" class="minimize"></div>';
	str += "<h2>Polygon, "+this.Area()+", "+ this.Circumference() + " m";
	if (this.Info) {
		str += ",";
		for (var i in this.Info) {
			if (i%3 == 0) str +=	"<br/>";
			str += this.Info[i]["title"] + " : " + this.Info[i]["selected"];
			if (i < this.Info.length-1) str += ", ";
		}
	}
	str += "</h2>";
	str +=  "<div class='infoWindowTool'>";
	str += '<img width="60" height="60" src="ICONS/FILL.png" title="Change polygon style" alt="Change polygon style" onclick="recreatePolygon(mapObjekts['+objNr+'],null,map);" />';
	if (mapObjekts[objNr].getPaths().length == 1) { // do some work with the edit button so that also multible polygons can be editet !!!
		str += '<img width="60" height="60" src="ICONS/EditPolygon.png" title="Edit polygon" alt="Edit polygon" onclick="editPoly(mapObjekts['+objNr+'],'+objNr+',0);" />';
	}
	str += '<img width="60" height="60" src="ICONS/DELETE.png" title="Delete polygon" alt="Delete polygon" onclick="deletObjekt(mapObjekts['+objNr+']);" />';
	str += "</div><h2 onclick='document.getElementById(&#34;inputField&#34;).innerHTML=&#34;&#34;'>[close]</h2>";
	str += "</div>";
	document.getElementById("inputField").innerHTML = str;
}

google.maps.Polygon.prototype.ClickActionMarker = ClickActionMarker;
function ClickActionMarker(objNr) {
	// multi select ?? ...
	var str = "<div id='inputFieldBOX' class='inputFieldBOX'>";
	str += '<div id="open" onclick="minimize(&#34;inputFieldBOX&#34;,this)" class="minimize"></div>';
	str += "<h2>"+this.address + "<p/>";
	for (var i in this.Info) {	
		if (this.Info[i]["type"] == "select") {
			str += this.Info[i]["title"] + " : ";
			str += "<select onchange='mapObjekts["+objNr+"].Info["+i+"][&#34;selected&#34;]=this.value'>";
			for (var j in this.Info[i]["options"]) {					
				str += "<option value='"+this.Info[i]["options"][j]+"'";
				if (this.Info[i]["options"][j] == this.Info[i]["selected"]) {
					str += "selected='selected'";	
				}
				str+= ">"+this.Info[i]["options"][j]+"</option>";
			}
			str += "</select><br/>";
		} else if (this.Info[i]["type"] == "text"){
			str += this.Info[i]["title"] + " : ";
			str += "<input type='text' size='20' onchange='mapObjekts["+objNr+"].Info["+i+"][&#34;selected&#34;]=this.value' value='"+this.Info[i]["selected"]+"' ></input><p/>";
		} else if (this.Info[i]["type"] == "fixed" ){
			str += this.Info[i]["title"] + " : ";
			str += this.Info[i]["selected"];
			if (i < this.Info.length-1) str += "<br/>";;
		} else if (this.Info[i]["type"] == "url" ){
			str += "<a href='"+ this.Info[i]["selected"] + "' target='_blank'>" +this.Info[i]["title"] + "</a>";
			if (i < this.Info.length-1) str += "<br/>";;
		}
	}
	str +=  "</h2><div class='infoWindowTool'>";
	str += '<img width="60" height="60" src="ICONS/FILL.png" title="Change marker Style" alt="Change Marker Style" onclick="recreateMarker(mapObjekts['+objNr+'],null,map)" />';
	str += '<img width="60" height="60" src="ICONS/editMarker.png" title="Change marker position" alt="Change marker position" onclick="editMarker(mapObjekts['+objNr+'],'+objNr+',map);" />';
	str += '<img width="60" height="60" src="ICONS/DELETE.png" title="Delete marker" alt="Delete marker" onclick="deletObjekt(mapObjekts['+objNr+']);" />';
	str += "</div><h2 onclick='document.getElementById(&#34;inputField&#34;).innerHTML=&#34;&#34;'>[close]</h2>";
	str += "</div>";
	document.getElementById("inputField").innerHTML = str;
}

google.maps.Polygon.prototype.Area = Area;
function Area() { //not finsihed jet.... area is worng....
	var allCoords = this.getPaths();
	var totalArea = 0;
	for (var c = 0; c < allCoords.getLength();c++) {
		var coords = allCoords.getAt(c);
		var Remaped = new Array();
		var latlng, temp;
		latlng = coords.getAt(0);
		for (var i = 1; i < coords.getLength();i++){
			temp = coords.getAt(i);
			latlng = new google.maps.LatLng(Math.min(latlng.lat(),temp.lat()),latlng.lng());
			latlng =  new google.maps.LatLng(latlng.lat(),Math.min(latlng.lng(),temp.lng()) );
		}
		
		var area = 0;
		var c1,c2,d1,d2;
		for (var i = 0; i < coords.getLength() ;i++){
			c1 = coords.getAt(i);
			c1 = new google.maps.LatLng(c1.lat(), latlng.lng());
			c2 = coords.getAt(i);
			c2 = new google.maps.LatLng(latlng.lat() , c2.lng());
			d1 = new google.maps.Point(distance(latlng,c1),distance(latlng,c2));
			Remaped.push(d1);
		}
		
		for (var i = 0; i < Remaped.length;i++){
			d1 = Remaped[i];
			d2 = Remaped[(i+1)%Remaped.length];
			area += d1.x * d2.y - d2.x * d1.y;
		}
		
		area = Math.abs(area * .5);
		
		
		
		totalArea += area;
	}
	
	if (totalArea > 1000000) {
		totalArea /= 1000000;
		totalArea *= 1000;
		totalArea = Math.round(totalArea);
		totalArea/=1000;	
		return totalArea + " km<sup>2</sup>";
	}
	totalArea = Math.round(totalArea);
	return totalArea + " m<sup>2</sup>";
}


google.maps.Polygon.prototype.Circumference = Circumference;
function Circumference() {
	var totalCircum = 0
	var allCoords = this.getPaths();
	for (var c = 0; c < allCoords.getLength();c++) {
		var coords = allCoords.getAt(c);
		var Circum = 0;
		for (var i = 0; i < coords.getLength();i++){
			Circum += this.distance(coords.getAt(i),coords.getAt((i+1)%coords.getLength()) );
		}
		totalCircum += Circum;
	}
	return Math.round(totalCircum);
}

google.maps.Polygon.prototype.distance = distance;
function distance(c1,c2) { // returns distance in meters...
	var dLat = (c2.lat()-c1.lat()) * Math.PI / 180;
	var dLon = (c2.lng()-c1.lng()) * Math.PI / 180;
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
	Math.cos(c1.lat() * Math.PI / 180 ) * Math.cos(c2.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 = 6371 * c;
	return d * 1000;
}

google.maps.Polygon.prototype.toKML = toKML;

function toKML() {
	var allCoords = this.getPaths(); // how to find out what is what...
	var d = new Date();
	var id = (d.getTime() + "" + Math.floor(Math.random() *1000000)).substr(0, 18);
	var opacity = new Array("00","11","22","33","44","55","66","77","88","99","aa","bb","cc","dd","ee","ff");
	
	var KMLString = "<Placemark id='" + id + clearentities(this.getKMLTitle())+"'>\n";
	KMLString += "<name>"+clearentities(this.getKMLTitle())+"</name>";
	// description
	KMLString += "<description>\n<![CDATA[";
	if (this.address) {
		KMLString += "address: " + this.address + " <br/>";
	} else {
		KMLString += "area: " + this.Area() +" <br/>";
		KMLString += "circumference: " + this.Circumference()+" m <br/>";
	}
	for(var i in this.Info) {
		KMLString += this.Info[i]["title"] + " : " + this.Info[i]["selected"] + " <br/>";
	}
	KMLString += "<sub>created with <a href='http://drawamap.org'> DRAWaMAP</a> </sub>"
	KMLString += "]]></description>\n";
	
	// addresse
	if (this.address) {
		KMLString += "<address>" + clearentities(this.address) + "</address>";
	} 
	
	// Extended Data
	KMLString += "<ExtendedData>";
	
	for(var i in this.Info) {
		KMLString += "<Data name='" + clearentities(this.Info[i]["type"]) + "'><value>" + clearentities(this.Info[i]["selected"]) ;
		if (this.Info[i]["type"] == "select") {
			KMLString += ":";
			for (var j =0; j < this.Info[i]["options"].length;j++) {
				KMLString += clearentities(this.Info[i]["options"][j]);
				if (j+1 != this.Info[i]["options"].length) {
					KMLString += ",";
				}
			}
		} else if ( this.Info[i]["type"] == "text") {
			KMLString += ":";
		}
		
		KMLString += "</value>"
		KMLString += "<displayName><![CDATA["+ clearentities(this.Info[i]["title"])  +"]]></displayName></Data>";	
	}
	KMLString += "</ExtendedData>";
	
	KMLString += "<Style id='Style"+id+"'>\n";
	var strokeColor = this.strokeColor.replace("#","");
	KMLString += "<LineStyle>\n";	
   KMLString += "<color>ff"+strokeColor.substr(4,2)+strokeColor.substr(2,2)+strokeColor.substr(0,2)+"</color>\n";   // aarrbbgg     
   KMLString += "<colorMode>normal</colorMode>\n";
   KMLString += "<width>"+this.strokeWeight+"</width>\n"; 
   KMLString += "</LineStyle>\n";
   
   var fillColor = this.fillColor.replace("#","");
	KMLString += "<PolyStyle>\n";
   KMLString += "<color>"+opacity[parseInt(this.fillOpacity*15)]+fillColor.substr(4,2)+fillColor.substr(2,2)+fillColor.substr(0,2)+"</color>\n"; // aarrbbgg
   KMLString += "<colorMode>normal</colorMode>\n";
   KMLString += "<fill>1</fill>\n"; //boolean true - false
   KMLString += "<outline>1</outline>\n"; //true true - false
   KMLString += "</PolyStyle>\n";
   KMLString += "</Style>\n";
   if (allCoords.getLength() > 1){
   	KMLString += "<MultiGeometry id='"+window.document.title+"'>\n";
   } else {
// vielleicht doch was hier ...
   }
   for (var c = 0; c < allCoords.getLength();c++){
   	var coords = allCoords.getAt(c);
   	KMLString += "<Polygon id='"+window.document.title+"'>\n";
   	KMLString += "<extrude>0</extrude>\n"
   	KMLString += "<tessellate>0</tessellate>\n";                
   	KMLString +="<altitudeMode>clampToGround</altitudeMode>\n";
   	KMLString +="<outerBoundaryIs>\n";
   	KMLString +="<LinearRing>\n";
   	KMLString += "<coordinates>\n";
   	for (var j =0; j < coords.length;j++){
   		var latlng = coords.getAt(j);
   		KMLString += +latlng.lng()+","+latlng.lat()+" \n";
   	}
   	KMLString += "</coordinates>\n";
   	KMLString += "</LinearRing>\n";
   	KMLString += "</outerBoundaryIs>\n";
   	   	KMLString += "</Polygon>\n";	
   }
   if (allCoords.getLength() > 1){
   	KMLString += "</MultiGeometry>";
   } else {
   	// vielleicht doch was hier...
   }
   KMLString += "</Placemark>";
   return KMLString;	
}

google.maps.Polygon.prototype.getKMLTitle = getKMLTitle;
function getKMLTitle() {
	return this.title;
}

