/**
	*
	* Google Maps Class
	*
	*	(c) Binary Objects, 2008 - 2009
	*	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 = [];

	var markers = [];
    var marker_categories = [];

    var _marker_initialized = false;


	// constructor...
	this.init = function()
		{
        if (GBrowserIsCompatible())
	    	{
	      	map = new GMap2(document.getElementById("gmap"));
		    map.setCenter(new GLatLng(52.535, 13.508), 12);
            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
            map.setMapType(G_NORMAL_MAP);
            mgr = new MarkerManager(map);

            // create contextmenu
            //_createContextMenu();

            // define events
            defineGEvents();

            var files = [
                'rummelsburger_bucht.kml', 'neu_lichtenberg.kml', 'neu_hohenschoenhausen_sued.kml',
                'neu_hohenschoenhausen_nord.kml', 'malcho_wartenberg_falkenberg.kml', 'karlshorst.kml',
                'friedrichsfelde_sued.kml', 'friedrichsfelde_nord.kml', 'fennpfuhl.kml',
                'alt_lichtenberg.kml', 'alt_hohenschoenhausen_sued.kml', 'alt_hohenschoenhausen_nord.kml',
                'frankfurter_allee_sued.kml'
                ];
            var d = new Date();

            for(var i = 0, c = files.length; i < c; ++i)
                {
                var path = 'http://' + window.location.hostname + '/site/gmaps/' + files[i] + '?t=' + d.getTime();
                var id = _kmls.length;
                _kmls[id] = [files[i], new GGeoXml(path)];

                map.addOverlay(_kmls[id][1]);
                }

            window.setTimeout(setupMarkers, 10);
		    }
		}

    /* public */

    this.getZoom = function() {
        return map.getZoom();
        
    }    
    
    
    
    this.zoomIn = function(x, y, zoom) {
        if(zoom === undefined) { zoom = 14; }
        map.setCenter(new GLatLng(x, y), zoom);
        }

	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.switchLibgPointByCategory = function(cat, state) {
        //alert(map.getZoom());
        for(var i = 0, c = marker_categories.length; i < c; ++i)
            {
            if(marker_categories[i] == cat || (cat == 'Sonstiges' && marker_categories[i] == ''))
                {
                if(markers[i])
                    {
                    var el = markers[i];
                    if(el.isHidden() && state != false)
                        {
                        el.show();
                        }
                    else
                        {
                        el.hide();
                        }
                    }
                }
            }
        }

    this.addLibgPoint = function(googlex, googley,
        stadtteilnr, stadtteil, objektname, plz, ort,
        anschrift, telefon, email, homepage, info,
        thema, kategorie, count, iditem, itemarray)
        {
        var innercount = count;
        if (count == '0') {count = '';} 
            
        var latlng = new GLatLng(googlex, googley);
        //var m = new GMarker(latlng);

        var icon = new GIcon();
        icon.iconSize = new GSize(32, 32);
        icon.iconAnchor = new GPoint(16, 16);
        icon.infoWindowAnchor = new GPoint(16, 16);

        stadtteilnr = urldecode(stadtteilnr);
        stadtteil = urldecode(stadtteil);

        objektname = urldecode(objektname);
        //plz = urldecode(plz);
        ort = urldecode(ort);

        anschrift = urldecode(anschrift);
        telefon = urldecode(telefon);
        email = urldecode(email);
        homepage = urldecode(homepage);
        info = urldecode(info);

        thema = urldecode(thema);
        
        var kategorie_urlencoded = kategorie;
        kategorie = urldecode(kategorie);
        
        switch(kategorie)
            {
            case 'Spielplätze': icon.image = 'http://' + window.location.hostname + '/site/pictures/gicons/spielplatz.png'; break;
            case 'Sportplätze': icon.image = 'http://' + window.location.hostname + '/site/pictures/gicons/sportplatz.png'; break;
            case 'Sporthallen': icon.image = 'http://' + window.location.hostname + '/site/pictures/gicons/sporthalle.png'; break;
            case 'Kinder- und Jugendeinrichtungen': icon.image = 'http://' + window.location.hostname + '/site/pictures/gicons/kinder.png'; break;
            case 'Sport': icon.image = 'http://' + window.location.hostname + '/site/pictures/gicons/sportplatz.png'; break;
            case 'Seniorenbegegnungsstätte': icon.image = 'http://' + window.location.hostname + '/site/pictures/gicons/senioren.png'; break;
            case 'Stadtteilzentren': icon.image = 'http://' + window.location.hostname + '/site/pictures/gicons/sozio.png'; break;
            case 'Bürgerämter': icon.image = 'http://' + window.location.hostname + '/site/pictures/gicons/buergeramt.png'; break;
            case 'Bibliotheken': icon.image = 'http://' + window.location.hostname + '/site/pictures/gicons/bibliothek.png'; break;
            case 'Kultureinrichtungen': icon.image = 'http://' + window.location.hostname + '/site/pictures/gicons/kultur.png'; break;
            case 'Volkshochschule': icon.image = 'http://' + window.location.hostname + '/site/pictures/gicons/vhs.png'; break;
            case 'Musikschule': icon.image = 'http://' + window.location.hostname + '/site/pictures/gicons/musikschule.png'; break;

            default: 
                icon.image = 'http://' + window.location.hostname + '/site/pictures/gicons/sonstiges.png';
                kategorie_urlencoded = 'Sonstiges';
            }

        marker_categories.push(kategorie_urlencoded);

        opts = {
          "icon": icon,
          "clickable": true,
          "title": unescape(objektname),
          "labelText": count,
          "labelOffset": new GSize(-12, -32),
          "labelClass": "markerCount"
        };
        var m = new LabeledMarker(latlng, opts);

        var listeVorschlaege = 'Hierzu gibt es noch keine Vorschläge.';
        // anchors to detail pages
        if (itemarray != '') {
            listeVorschlaege = '';
            var itemsarray = itemarray.split(',');
            if (itemsarray.length > 0) {
                for (i=0; i < itemsarray.length; i++) {
                    listeVorschlaege = listeVorschlaege +
                    "<a href='index.php?page=detail_vorschlag&id_item="+itemsarray[i]+"&menucontext=78&submenucontext=224&subsubmenucontext=232'>Vorschlag "+(i+1)+"</a><br>";
                }
            }
        }
        
        GEvent.addListener(m, "click", function() {
            m.openInfoWindow("<span style='font-size: 13px;'><p style='width:400px;'><b>" + objektname + "</b>" +
                "<br><br>" + anschrift + "<br>" + plz + "&nbsp;" + ort +
                "<br><br>Telefon: " + telefon + "<br>E-Mail: " + email + "<br>Webseite: " + homepage +
                "<br>Info: " + info + "<br><br>" +
                "<!-- <a href='index.php?page=submit_item_vorschlag&submititem_id_itemtype=52&menucontext=31&submititem_prefield1_name=Stadtbezirk&submititem_prefield1_value=" +
                escape(stadtteil) + "&submititem_prefield2_name=Thema&submititem_prefield2_value=" + escape(thema) +
                "&submititem_prefield3_name=Kategorie&submititem_prefield3_value=" + escape(kategorie) +
                "&submititem_prefield4_name=Objekt&submititem_prefield4_value=" + escape(objektname) +
                "'>Vorschlag schreiben</a> --></p>" +
                "<p>Anzahl Vorschl&auml;ge zu diesem Objekt: " + innercount +
                "<br>" + listeVorschlaege + 
                "</p></span>"
                );
            });

        markers.push(m);
        }


	/**
		*
		* PRIVATE
		*
		**/

    var setupMarkers = function()
        {
        mgr.addMarkers(markers, 13);
        mgr.refresh();

        self.switchLibgPointByCategory('Spielpl%E4tze', false);
        self.switchLibgPointByCategory('Sporthallen', false);
        self.switchLibgPointByCategory('Kinder-+und+Jugendeinrichtungen', false);
        self.switchLibgPointByCategory('Sportpl%E4tze', false);
        }

    var setupRandomMarkers = function()
        {
        mgr.addMarkers(getRandomMarkers(10), 3);
        mgr.refresh();
        }

    var getRandomMarkers = function(n)
        {
        var markers = [];
        for(var i=0; i < n; ++i)
            {
            markers.push( new GMarker( getRandomPoint() ) );
            }
        return markers;
        }

    var getRandomPoint = function()
        {
        var lat = 52.563 + (Math.random() - 0.5) * 0.05;
        var lng = 13.506 + (Math.random() - 0.5) * 0.05;
        return new GLatLng(lat, lng);
        }

    var getRandomIcon = function()
        {
      var i = Math.floor(IMAGES.length*Math.random());
      if (!ICONS[i]) {
        var icon = new GIcon();
        icon.image = "images/"
            + IMAGES[i] + ".png";
        icon.iconAnchor = new GPoint(16, 16);
        icon.infoWindowAnchor = new GPoint(16, 0);
        icon.iconSize = new GSize(32, 32);
        icon.shadow = "images/"
            + IMAGES[i] + "-shadow.png";
        icon.shadowSize = new GSize(59, 32);
        ICONS[i] = icon;
      }
      return ICONS[i];
    }


	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), 14);
        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(key)
		{
			for(i=0, c=_kmls.length; i<c; ++i) { if(_kmls[i][0] == key) return 1; }
			return 0;
		}

	var getKmlId = function(key)
		{
			for(i=0, c=_kmls.length; i<c; ++i) { if(_kmls[i][0] == key) 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(key, path, state)
		{
        if(!isKmlLoaded(key))
            {
            var id = _kmls.length;
            _kmls[id] = [key, new GGeoXml(path)];
            }
        else
            {
            var id = getKmlId(key);
            }

        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.selectKmlFile = function(el, file)
        {
        var d = new Date();
        this.switchKml(file, 'http://' + window.location.hostname + '/site/gmaps/' + file + '?t=' + d.getTime(), el.checked); // ' + window.location.hostname + '
        }

    /*
	this.selectMapOpt = function(el)
		{
			switch(el.id)
				{
				case 'cbox_mainbldg':
					this.switchKml('http://' + window.location.hostname + '/2011/site/gmaps/lager.kml', el.checked); return;
				case 'cbox_subbldg':
					this.switchKml('http://' + window.location.hostname + '/2011/site/gmaps/hangar.kml', el.checked); return;
				case 'cbox_piofld':
					this.switchKml('http://' + window.location.hostname + '/2011/site/gmaps/buero.kml', el.checked);	return;
				case 'cbox_baufld':
					this.switchKml('http://' + window.location.hostname + '/2011/site/gmaps/sonderbauten.kml', el.checked); return;

				case 'cbox_buero_stat':
					this.switchKml('http://' + window.location.hostname + '/2011/site/gmaps/buero_stat.kml', el.checked); return;
				case 'cbox_hangar_stat':
					this.switchKml('http://' + window.location.hostname + '/2011/site/gmaps/hangar_stat.kml', el.checked); return;
				case 'cbox_lager_stat':
					this.switchKml('http://' + window.location.hostname + '/2011/site/gmaps/lager_stat.kml', el.checked); return;
				case 'cbox_sonder_stat':
					this.switchKml('http://' + window.location.hostname + '/2011/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;
				}
		}
    */

    var urldecode = function(str)
        {
        // http://kevin.vanzonneveld.net
        // +   original by: Philip Peterson
        // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +      input by: AJ
        // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +   improved by: Brett Zamir (http://brett-zamir.me)
        // +      input by: travc
        // +      input by: Brett Zamir (http://brett-zamir.me)
        // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +   improved by: Lars Fischer
        // +      input by: Ratheous
        // %          note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
        // *     example 1: urldecode('Kevin+van+Zonneveld%21');
        // *     returns 1: 'Kevin van Zonneveld!'
        // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
        // *     returns 2: 'http://kevin.vanzonneveld.net/'
        // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
        // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'

        var hash_map = {}, ret = str.toString(), unicodeStr='', hexEscStr='';

        var replacer = function (search, replace, str)
            {
            var tmp_arr = [];
            tmp_arr = str.split(search);
            return tmp_arr.join(replace);
            };

        // The hash_map is identical to the one in urlencode.
        hash_map["'"] = '%27';
        hash_map['('] = '%28';
        hash_map[')'] = '%29';
        hash_map['*'] = '%2A';
        hash_map['~'] = '%7E';
        hash_map['!'] = '%21';
        hash_map['%20'] = '+';
        hash_map['\u00DC'] = '%DC';
        hash_map['\u00FC'] = '%FC';
        hash_map['\u00C4'] = '%D4';
        hash_map['\u00E4'] = '%E4';
        hash_map['\u00D6'] = '%D6';
        hash_map['\u00F6'] = '%F6';
        hash_map['\u00DF'] = '%DF';
        hash_map['\u20AC'] = '%80';
        hash_map['\u0081'] = '%81';
        hash_map['\u201A'] = '%82';
        hash_map['\u0192'] = '%83';
        hash_map['\u201E'] = '%84';
        hash_map['\u2026'] = '%85';
        hash_map['\u2020'] = '%86';
        hash_map['\u2021'] = '%87';
        hash_map['\u02C6'] = '%88';
        hash_map['\u2030'] = '%89';
        hash_map['\u0160'] = '%8A';
        hash_map['\u2039'] = '%8B';
        hash_map['\u0152'] = '%8C';
        hash_map['\u008D'] = '%8D';
        hash_map['\u017D'] = '%8E';
        hash_map['\u008F'] = '%8F';
        hash_map['\u0090'] = '%90';
        hash_map['\u2018'] = '%91';
        hash_map['\u2019'] = '%92';
        hash_map['\u201C'] = '%93';
        hash_map['\u201D'] = '%94';
        hash_map['\u2022'] = '%95';
        hash_map['\u2013'] = '%96';
        hash_map['\u2014'] = '%97';
        hash_map['\u02DC'] = '%98';
        hash_map['\u2122'] = '%99';
        hash_map['\u0161'] = '%9A';
        hash_map['\u203A'] = '%9B';
        hash_map['\u0153'] = '%9C';
        hash_map['\u009D'] = '%9D';
        hash_map['\u017E'] = '%9E';
        hash_map['\u0178'] = '%9F';

        for(unicodeStr in hash_map)
            {
            hexEscStr = hash_map[unicodeStr]; // Switch order when decoding
            ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
            }

        // End with decodeURIComponent, which most resembles PHP's encoding functions
        ret = decodeURIComponent(ret);

        return ret;
        }
}

