var markersArray = {};
var icons = {};
var markersIdent = [];

dojo.declare("GMap", [], {
	
	geocoder: null,
	map: null,
	node_id: null,
	opts: {},
	styles: [],
	clusterByIcon: false,
	afterParsed: function() {},
	
	constructor: function(node_id) {
		this.node_id = node_id;
		this.geocoder = new GClientGeocoder();
		var myOptions = {
			      zoom: 14,
			      mapTypes: [G_NORMAL_MAP, G_SATELLITE_MAP]
			    };
		G_PHYSICAL_MAP.getMinimumResolution = function () { return 7 };
        G_NORMAL_MAP.getMinimumResolution = function () { return 7 };
        G_SATELLITE_MAP.getMinimumResolution = function () { return 7 };
        G_HYBRID_MAP.getMinimumResolution = function () { return 7 }; 
		window.exml = {};
		this.map = new GMap2(document.getElementById(node_id), myOptions);
		this.centerByAddress('Česká republika, Vlašim', 7);
//		this.map.enableScrollWheelZoom();
//		this.clusterer = new ClusterMarker(this.map);
		this.map.addControl(new GLargeMapControl());
	    this.map.addControl(new GMapTypeControl());
//	    this.map.setUIToDefault();
	    
	    return this;
	},
	
	centerByAddress: function(address, zoom) {
		var instance = this;
//		console.log('nastavuji adresu: '+address+' zoom: '+zoom);
		if (this.geocoder) {
	        this.geocoder.getLocations(address, function (result)
	                { 
	                  // If that was successful
	                  if (result.Status.code == G_GEO_SUCCESS) {
	                    // Loop through the results, placing markers
	                    // centre the map on the first result
	                    var p = result.Placemark[0].Point.coordinates;
	                    instance.map.setCenter(new GLatLng(p[1],p[0]),zoom);
	                  }
	                  // ====== Decode the error status ======
	                  else {
	                    var reason="Code "+result.Status.code;
	                    if (reasons[result.Status.code]) {
	                      reason = reasons[result.Status.code]
	                    } 
	                    alert('Could not find "'+search+ '" ' + reason);
	                  }
	                }
	              );
		    }
	},
	
	clusterIcons: function(instance) {
		var cluster=new ClusterMarker(instance.map, { markers: markersArray } );
		cluster.fitMapToMarkers();
	},
	
	loadKML: function(kml_path) {
		
		var _this = this;
		
		var array_ident = _this.node_id+'_'+kml_path;
		
		exml[array_ident] = new EGeoXml("exml", _this.map, kml_path, {
				iwwidth: 500,
				iwoptions: {icontype: "style"},
				printgif: "true",
//				baseicon: icon
				createmarker: function(point, name, desc, style) {
					_this.createmarker(point, name, desc, style, _this.map, array_ident, _this);
				}
			});
				
		GEvent.addListener(exml[array_ident], "parsed", function() {
			var clusters = [];
			if(_this.clusterByIcon) {
				for(var i=0; i<markersIdent.length;i++) {
					var group = markersIdent[i];
					
						var icon = icons[group];
						clusters[i] = new ClusterMarker(_this.map, {markers: markersArray[group], clusterMarkerIcon: icon});
						clusters[i].fitMapToMarkers();
						console.debug(clusters[i]);
					
				}
			} else {
				var cluster_icon = new GIcon();
				cluster_icon.image = CMS_HOMEPAGE_URL+'public/GoogleMaps/icons/hb-area/gmap-ico-green3.png';
				cluster_icon.iconSize = new GSize(43, 53);
				cluster_icon.shadow = CMS_HOMEPAGE_URL+'public/GoogleMaps/icons/hb-area/gmap-ico-green-shade3.png';
				cluster_icon.shadowSize = new GSize(43, 53);
				cluster_icon.iconAnchor = new GPoint(22, 53);
				cluster_icon.infoWindowAnchor = new GPoint(22, 25);
				
				clusters = new ClusterMarker(_this.map, {markers: markersArray['together'], clusterMarkerIcon: cluster_icon});
				clusters.fitMapToMarkers();
			}
//			console.log('cluster');
//			console.debug(clusters);
				_this.afterParsed();
		    });
		
		try {
			exml[array_ident].parse();
//			exml[array_ident].show();
			exml[array_ident].hide();
		} catch(e) { }
		
	},
	
	createmarker: function(point, name, desc, style, map, kml, instance) {
		var _this = instance;
		var ob_style = exml[kml]["styles"][style];
		
		var icon = new GIcon();
		icon.image = ob_style["image"];
		icon.iconSize = new GSize(parseInt(ob_style["iconSize"]["width"]), parseInt(ob_style["iconSize"]["height"]));
		icon.shadow = ob_style["shadow"];
		icon.shadowSize = new GSize(parseInt(ob_style["shadowSize"]["width"]), parseInt(ob_style["shadowSize"]["height"]));
		icon.iconAnchor = new GPoint(ob_style["iconAnchor"]["x"], ob_style["iconAnchor"]["y"]);
		icon.infoWindowAnchor = new GPoint(parseInt(ob_style["infoWindowAnchor"]["x"]), parseInt(ob_style["infoWindowAnchor"]["y"]));

		if(icons[icon.image] == undefined)
			icons[icon.image] = icon;
		var markeroptions = {};

		if (!markeroptions.icon) {
			markeroptions.icon = icon;
		}

		var marker = new GMarker(point, markeroptions);
	    
		if(marker) {

			if(_this.clusterByIcon) {
				if(markersArray[icon.image] !== undefined)
					markersArray[icon.image].push(marker);
				else {
					markersArray[icon.image] = [];
					markersArray[icon.image].push(marker);
					markersIdent.push(icon.image);
				}
			} else {
				if(!markersArray['together'])
					markersArray['together'] = [];
				markersArray['together'].push(marker);
				markersIdent.push(icon.image);
			}
			
		    GEvent.addListener(marker, 'click', function() {
				marker.openInfoWindowHtml(desc, {maxWidth:500});
			});
		}
	    
	}
	
})
