/**
	*
	* Google Maps Class
	*
	*	Binary Objects, 2008
	*	Created by RW
	*
	* var gmp = new GMPage();
	* window.onload = gmp.init;
	* window.unload = GUnload;
	*
	**/
function GMPage()
{
	var self = this;

	// private main objects
	var map = null;
	var mgr = null;

	// private subs
	var _colors = [ ["red", "#ff0000"], ["orange", "#ff8800"], ["green", "#008000"],
        					["blue", "#000080"], ["purple", "#800080"] ];

 	var _options = {};
 	var _colidx = 0;
 	var _lineCounter = 0;
 	var _polyCounter = 0;

	var _map_positionable = 0;
	var _ctxtmenu = null;
	var _overlay = null;
	var _overlays = [];
	var _kmls = [];

	// constructor...
	this.init = function()
		{
			if (GBrowserIsCompatible())
	    	{
	      		// create map
		      map = new GMap2(document.getElementById("gmap"));
		      map.setCenter(new GLatLng(52.481251, 13.392398), 16); // tempelhof
					map.addControl(new GLargeMapControl());
					map.addControl(new GMapTypeControl());
					map.setMapType(G_SATELLITE_MAP);
					//mgr = new MarkerManager(map, { borderPadding: 50, maxZoom: 15, trackMarkers: true });

					// create contextmenu
					//_createContextMenu();

					// define events
					defineGEvents();

					/*selectButton('gmaps_b_hand');*/
		    }
		}

	this.initProjectMap = function()
		{

		while(!map);

		var b = document.getElementById('cbox_buero_stat');
		var s = document.getElementById('cbox_sonder_stat');
		var l = document.getElementById('cbox_lager_stat');
		var h = document.getElementById('cbox_hangar_stat');

		if(b) b.click();
		if(s) s.click();
		if(l) l.click();
		if(h) h.click();

		/*this.selectMapOptById('cbox_buero_stat');
		this.selectMapOptById('cbox_sonder_stat');
		this.selectMapOptById('cbox_lager_stat');
		this.selectMapOptById('cbox_hangar_stat');*/
		}


	/**
		*
		* PRIVATE
		*
		**/

	var defineGEvents = function()
		{
			// right click context menu
			GEvent.addListener(map, "singlerightclick",
				function(overlay, point)
				{
					_overlay = overlay; // save

	        var x = overlay.x;
	        var y = overlay.y;
	        if (overlay.x > map.getSize().width - 120) { x = map.getSize().width - 120; }
	        if (overlay.y > map.getSize().height - 100) { y = map.getSize().height - 100; }

	        var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));
	        pos.apply(ctxtmenu);

	        ctxtmenu.style.visibility = "visible";
      	}
			);

		  // left click create poly
		  GEvent.addListener(map, "click",
		  	function(overlay, point)
				{
					if (!overlay && _map_positionable) { createMarker(point); }
				});

			// addoverlay event, um marker festzuhalten
			GEvent.addListener(map, "addoverlay",
				function(overlay)
				{
        	if (overlay.name)
        	{
          	if (!overlay._known)
          	{
            	// ref of new marker
            	//_overlays.push( [overlay.name, overlay] );
            	//drawGenericPoly(overlay.getLatLng(), 0.5, 8)
            	overlay._known = true;
          	}
        	}
      	});
		}

	var createMarker = function(point)
		{
			mgr.addMarker(new GMarker(point), 13);
			mgr.refresh();
		}

	var createContextMenu = function()
		{
			_ctxtmenu = document.createElement("div");
			_ctxtmenu.style.visibility="hidden";
    	_ctxtmenu.style.background="#ffffff";
    	_ctxtmenu.style.border="1px solid #8888FF";
    	_ctxtmenu.innerHTML =
    		'<a href="javascript:contAddPoly()"><div class="context">&nbsp;&nbsp;Polygon hinzuf&uuml;gen&nbsp;&nbsp;</div></a>'
    		+ '<a href="javascript:contDelPoly()"><div class="context">&nbsp;&nbsp;Polygon entfernen&nbsp;&nbsp;</div></a>';
  		map.getContainer().appendChild(_ctxtmenu);
		}

	var isKmlLoaded = function(path)
		{
			for(i=0, c=_kmls.length; i<c; ++i) { if(_kmls[i][0] == path) return 1; }
			return 0;
		}

	var getKmlId = function(path)
		{
			for(i=0, c=_kmls.length; i<c; ++i) { if(_kmls[i][0] == path) return i; }
			return -1;
		}

	var selectButton = function(id)
		{
			if(_e("gmaps_b_hand")) {	_e("gmaps_b_hand").className = ""; }
		  if(_e("gmaps_b_placemarker")) { _e("gmaps_b_placemarker").className = ""; }
		  if(_e("gmaps_b_line")) { _e("gmaps_b_line").className = ""; }
		  if(_e("gmaps_b_poly")) { _e("gmaps_b_poly").className = ""; }
		  if(_e(id)) { _e(id).className="selected"; }
		}

	var stopEditing = function()
		{
  		selectButton("gmaps_b_hand");
		}

	var getColor = function(color)
		{
  		return _colors[(_colidx++) % _colors.length][color ? 0 : 1];
		}

	var getIcon = function(color)
		{
		  var ic = new GIcon();
		  ic.image = "http://google.com/mapfiles/ms/micons/" + color + ".png";
		  ic.iconSize = new GSize(32, 32);
		  ic.iconAnchor = new GPoint(15, 32);
		  return ic;
		}

	/**
		* pos = new GLatLng
		**/
	var drawGenericPoly = function(pos, radius, nodes, line_col, line_width, line_opac, fill_col, fill_opac)
		{
			fill_col = fill_col||line_col||"#0055ff";
			line_width = line_width||2;

			var points = [];
			var step = parseInt(360/nodes) || 10;
			var latConv = pos.distanceFrom(new GLatLng(pos.lat() + 0.1, pos.lng()))/100;
			var lngConv = pos.distanceFrom(new GLatLng(pos.lat(), pos.lng() + 0.1))/100;

			for(var i = 0; i<360; i+=step)
			{
				var pt = new GLatLng(
					pos.lat() + (radius/latConv * Math.cos(i * Math.PI/180)),
					pos.lng() + (radius/lngConv * Math.sin(i * Math.PI/180))
				);
				points.push(pt);
			}

			var poly = new GPolygon(points, line_col, line_width, line_opac, fill_col, fill_opac);
			map.addOverlay(poly);
		}

	var startDrawing = function(poly, name, onUpdate, color)
		{
		  map.addOverlay(poly);

		  poly.enableDrawing(_options);
		  poly.enableEditing( {onEvent: "mouseover"} );
		  poly.disableEditing( {onEvent: "mouseout"} );

		  GEvent.addListener(poly, "endline",
		  	function()
			  {
			    selectButton("gmaps_b_hand");
			    GEvent.bind(poly, "lineupdated", null, onUpdate);

			    GEvent.addListener(poly, "click",
			    	function(latlng, index)
				    {
				      if(typeof index == "number")
					      {
					        poly.deleteVertex(index);
					      }
				      else
				      	{
					        var newColor = getColor(false);
					        poly.setStrokeStyle( {color: newColor, weight: 4} );
					      }
				    });
			  });
		}


	/**
		*
		* PUBLIC
		*
		**/

	this.placeMarker = function()
		{
	  	var listener = GEvent.addListener(map, "click",
	  		function(overlay, latlng)
	  		{
			    if(latlng)
			    {
			      selectButton("gmaps_b_hand");
			      GEvent.removeListener(listener);

			      var color = getColor(true);
			      var marker = new GMarker(latlng, {icon: getIcon(color), draggable: true});
			      map.addOverlay(marker);
			    }
			  });
			selectButton("gmaps_b_placemarker");
		}

	this.startLine = function()
		{
		  selectButton("gmaps_b_line");

			var color = getColor(false);
		  var line = new GPolyline([], color);
		  startDrawing(line, "Line " + (++_lineCounter), function() {}, color);
		}

	this.startPoly = function()
		{
		  selectButton("gmaps_b_poly");

		  var color = getColor(false);
		  var polygon = new GPolygon([], color, 2, 0.7, color, 0.2);
		  startDrawing(polygon, "Shape " + (++_polyCounter), function() {}, color);
		}

	this.switchKml = function(path, state)
		{
			if(!isKmlLoaded(path))
			{
				var id = _kmls.length;
				_kmls[id] = [ path, new GGeoXml(path) ];
			}
			else
				var id = getKmlId(path);

			if(state)
				map.addOverlay(_kmls[id][1]);
			else
				map.removeOverlay(_kmls[id][1]);
		}

	this.clearCheckboxes = function()
		{
		var els = [ 'cbox_mainbldg', 'cbox_subbldg', 'cbox_piofld', 'cbox_baufld',
								'cbox_buero_stat', 'cbox_hangar_stat', 'cbox_lager_stat', 'cbox_sonder_stat' ];
		var c = els.length;
		for(var i=0; i<c; ++i)
			{
			var el = document.getElementById(els[i]);
			if(el) { el.checked = false; }
			}
		}

	this.selectMapOptById = function(el_id)
		{
		this.selectMapOpt(document.getElementById(el_id));
		}

	this.selectMapOpt = function(el)
		{
			switch(el.id)
				{
				case 'cbox_mainbldg':
					this.switchKml('http://' + window.location.hostname + '/site/gmaps/lager.kml', el.checked); return;
				case 'cbox_subbldg':
					this.switchKml('http://' + window.location.hostname + '/site/gmaps/hangar.kml', el.checked); return;
				case 'cbox_piofld':
					this.switchKml('http://' + window.location.hostname + '/site/gmaps/buero.kml', el.checked);	return;
				case 'cbox_baufld':
					this.switchKml('http://' + window.location.hostname + '/site/gmaps/sonderbauten.kml', el.checked); return;

				case 'cbox_buero_stat':
					this.switchKml('http://' + window.location.hostname + '/site/gmaps/buero_stat.kml', el.checked); return;
				case 'cbox_hangar_stat':
					this.switchKml('http://' + window.location.hostname + '/site/gmaps/hangar_stat.kml', el.checked); return;
				case 'cbox_lager_stat':
					this.switchKml('http://' + window.location.hostname + '/site/gmaps/lager_stat.kml', el.checked); return;
				case 'cbox_sonder_stat':
					this.switchKml('http://' + window.location.hostname + '/site/gmaps/sonderbauten_stat.kml', el.checked); return;

				case 'cbox_labels':
					return;
				case 'reset':
					map.clearOverlays(); this.clearCheckboxes(); return;
				case 'cbox_pos':
					_map_positionable = el.checked; return;
				case 'cbox_dist':
					_map_messurable = el.checked; return;
				}
		}
}