var MapBlock = new Class({
	
	initialize : function(id)
	{
		enable_map_extras();
		
		window.sparks = window.sparks || {};
		window.sparks[id] = this;
	
		
		this.markers = [];
		
		var var_name = 'data_MapBlock_'+id;
		this.data = window[var_name];
		this.el = $(id);
		if (!this.el) return;
		
		this.map = new GMap2(this.el);
		window.onunload = GUnload;
	
		this.tooltip = new MapTooltip(this.map);
		this.map.addOverlay(this.tooltip);
		
		//var marker = new GMarker(latlng);
		//this.map.addOverlay(marker);
		this.addMarkers(this.data['markers']);
		if (this.data['polylines'] && this.data['polylines'].length>0) this.addPolylines(this.data['polylines']);
		
		this.map.addMapType(G_PHYSICAL_MAP);
		this.map.addControl(new GSmallZoomControl3D());
		this.map.addControl(new GMenuMapTypeControl());
		
		if (this.data.map_type) this.map.setMapType(window[this.data.map_type]);
		
		GEvent.addListener(this.map, 'click', this.mapClicked.bind(this));
				
		if (this.data.latlng)
		{
			var latlng = new GLatLng(parseFloat(this.data['latlng'][0]),parseFloat(this.data['latlng'][1]));
			var zoom = this.data['zoom'];
			this.map.setCenter(latlng, zoom);
			
		} else {
		
			if (this.data.zoom_to_markers && this.markers.length>0) 
			{
				this.zoomToFitMarkers();
			} else {
				this.zoomToWorld();
			}
		}
	},
	
	triggerResize : function(recenter)
	{
		this.map.checkResize();
		
		if (recenter)
		{
			if (this.data.latlng)
			{
				var latlng = new GLatLng(parseFloat(this.data['latlng'][0]),parseFloat(this.data['latlng'][1]));
				var zoom = this.data['zoom'];
				this.map.setCenter(latlng, zoom);

			} else {

				if (this.data.zoom_to_markers && this.markers.length>0) 
				{
					this.zoomToFitMarkers();
				} else {
					this.zoomToWorld();
				}
			}
		}
	},
	
	zoomToFitMarkers : function()
	{
		var bounds = new GLatLngBounds();
		for (var i=0; i< this.markers.length; i++) 
		{
		   bounds.extend(this.markers[i].getLatLng());
	   	}
	  	var z = this.map.getBoundsZoomLevel(bounds);//-1;
		if (z<0) z=0;
		
		var world_zoom = this.getWorldZoomLevelForSize();
		if (world_zoom > z) z = world_zoom;
		
		if (z > 15) z = 15;
		
	   	this.map.setCenter(bounds.getCenter(), z);
	},
	
	zoomToWorld : function()
	{
		var zoom = this.getWorldZoomLevelForSize();
		var c = new GLatLng(20,0);
		
		this.map.setCenter(c, zoom);
	},
	
	getWorldZoomLevelForSize : function()
	{
		var size = this.map.getSize();
		var zoom = 0;
		if (size.width > 400) zoom ++;
		if (size.width > 800) zoom ++;
		return zoom;
	},
	
	addMarkers : function(markers)
	{
		for(var i=0;i<markers.length;i++)
		{
			this.addMarker(markers[i]);
		}
	},
	
	addPolylines : function(polylines)
	{
		for(var i=0;i<polylines.length;i++)
		{
			var info = polylines[i];
			var latlngs = [];
			
			for(var j=0;j<info[0].length;j++) latlngs.push(new GLatLng(parseFloat(info[0][j][0]),parseFloat(info[0][j][1])));
			
			var polyline = new GPolyline(latlngs, info[1], parseInt(info[2]));
			this.map.addOverlay(polyline);
		}
	},
	
	addMarker : function(marker)
	{
		var title = marker['title'] || 'Marker';
		var icon  = marker['icon'] || 'default';
		var scale  = marker['icon-scale'] || 1;
		
		var latlng = new GLatLng(parseFloat(marker['latlng'][0]),parseFloat(marker['latlng'][1]));
		marker.latlng = latlng;
		
		var icon = this.getIcon(icon,scale);
		var overlay = new GMarker(latlng, {'title': title, 'icon':icon});
		overlay._marker_info = marker;
				
		this.map.addOverlay(overlay);
		this.markers.push(overlay);
		
		overlay._mb = this;
		
		GEvent.addListener(overlay, 'mouseover', this.markerHover);
		GEvent.addListener(overlay, 'mouseout', this.markerDeHover);
	},
	
	mapClicked : function(overlay, latlng)
	{
		if (overlay)
		{
			this.markerClicked(overlay);
		}
	},
	
	markerClicked : function(overlay)
	{
		if (!overlay._marker_info) return;
		
		var marker = overlay._marker_info || {};
		
		if (this.data.is_direct_click && marker.url) return window.location.href = marker.url;
		
		var html = this.generatePopupHtml(marker);
		
		if (html) overlay.openInfoWindowHtml(html, {'maxWidth':this.data.popup.width});
	},
	
	markerHover : function(latlng)
	{
		this._mb.tooltip.show(this, this.getTitle());
	},
	
	markerDeHover : function()
	{
		this._mb.tooltip.hide();
	},
	
	popup_callbacks : null,
	generatePopupHtml : function(marker_info)
	{
		var cls = marker_info.cls || 'default';
	
		if (this.popup_callbacks && this.popup_callbacks.has(cls)) return this.popup_callbacks.get(cls)(marker_info);
	
		if (cls == 'default')
			return this.generatePopupHtml_default(marker_info);
	},
	
	addPopupRenderer : function(cls, cb)
	{
		if (!this.popup_callbacks) this.popup_callbacks = new Hash();
		
		this.popup_callbacks.set(cls, cb);
	},
	
	generatePopupHtml_default : function(marker_info)
	{
		var title = marker_info.title || '';
		var snippet = marker_info.snippet || '';
		var image_url = marker_info.image || '';
		var url = marker_info.url || '';
		var read_more = marker_info.read_more || this.data['default_read_more'];
		
		
		var popup = this.data.popup;
		var style = '';
		if (popup.width) style += 'width:'+popup.width+'px;';
		if (popup.height) style += 'height:'+popup.height+'px;';
		
		var css_class='';
		if (popup.css_class) css_class = ' '+popup.css_class;
		
		var img = '';
		if (image_url) img = '<td width="1%" style="padding-right:5px"><img src="'+image_url+'" class="tmb" /></td>';
		
		var title_html = title;
		if (url) title_html = '<a href="'+url+'">'+title_html+'</a>';
		
		var read_more_html = '';
		if (url) read_more_html = '<a href="'+url+'">'+read_more+'</a>';
		
		return 	'<table class="map-popup'+css_class+'" style="'+style+'"><tr>'+
				img+
				'<td>'+
				'<h4>'+title_html+'</h4>'+
				'<p>'+snippet+'</p>'+read_more_html+
				'</td>'+
				'</tr></table>';
	},
	
	icon_cache: {},
	getIcon : function(type, scale)
	{
		scale = scale || 1;
		
		if (this.icon_cache[type] && scale==1) return this.icon_cache[type];
		var icon = new GIcon(G_DEFAULT_ICON);
		
		var parts = type.split(':');
		if (parts[2]) scale = parseFloat(parts[2]);
		
		if (parts[0] == 'small')
		{
			icon.image = "http://labs.google.com/ridefinder/images/mm_20_"+parts[1]+".png";
			icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
			icon.iconSize = new GSize(12, 20);
			icon.shadowSize = new GSize(22, 20);
			icon.iconAnchor = new GPoint(6, 20);
			icon.infoWindowAnchor = new GPoint(6, 8);
		
		} else if (parts[0] == 'gmaps') {
			
			icon.image = "/_files/map-icons/google-map-icons/"+parts[1]+".png";
			icon.shadow = null;
			icon.iconSize = new GSize(32, 37);
			icon.shadowSize = new GSize(32, 37);
			icon.iconAnchor = new GPoint(16, 37);
			icon.infoWindowAnchor = new GPoint(16, 8);
		} else if (parts[0] == 'dots') {
			icon.image = "http://maps.google.com/mapfiles/kml/pal3/icon49.png";
			icon.shadow = null;
			icon.iconSize = new GSize(9*scale, 9*scale);
			icon.shadowSize = null;//new GSize(32, 37);
			icon.iconAnchor = new GPoint(5*scale, 5*scale);
			icon.infoWindowAnchor = new GPoint(5*scale,5*scale);
		} else if (parts[0] == 'special') {
			icon.image = "/_resources/Wr.Ski/ski-resort-dot.png";//http://maps.google.com/mapfiles/kml/pal4/icon35.png";
			icon.shadow = null;//"/_resources/Wr.Ski/ski-resort-shadow.png";
			icon.iconSize = new GSize(17*scale, 17*scale);
			icon.shadowSize = null;//new GSize(21*scale, 21*scale);
			icon.iconAnchor = new GPoint(8*scale, 8*scale);
			icon.infoWindowAnchor = new GPoint(8*scale,8*scale);
		} else if(parts[0] == 'hg') {
			
			scale = scale / 1.2;
			
			icon.image = "/files/markers/"+parts[1]+".png";//http://maps.google.com/mapfiles/kml/pal4/icon35.png";
			icon.shadow = '/files/markers/shadow.png';
			icon.iconSize = new GSize(27*scale, 34*scale);
			icon.shadowSize = new GSize(37*scale, 35*scale);
			icon.iconAnchor = new GPoint(14*scale, 34*scale);
			icon.infoWindowAnchor = new GPoint(12*scale,34*scale);
		}

		this.icon_cache[type] = icon;
		return icon;
	}	
});


function enable_map_extras()
{
	window.MapTooltip = function()
	{

	}	

	MapTooltip.prototype = new GOverlay();

	$extend(MapTooltip.prototype, {

		gmap : null,
		el : null,
		latlng : null, // Position on map
		yoffset : 0,   // Height from ground (pixels)

		//
		//	Function required by API
		//
		initialize : function(map)
		{
			this.map = map;

			this.els = {};
			var outer = new Element('div',{'class' : 'geo_map_tooltip'});
			var inner = new Element('div');
			outer.style.display = 'none';
			
			var is_ie6 = (Browser.Engine.trident && (Browser.Engine.version<5)) || false;
			if (is_ie6) outer.className = 'geo_map_tooltip_ie6';

			outer.style.position = 'absolute';

			outer.appendChild(inner);
		  	this.map.getPane(G_MAP_FLOAT_PANE).appendChild(outer);

			this.latlng = null;

			// Poiner div
			var pdiv = new Element('div',{'class' : 'geo_map_tooltip_pointer'});
			outer.appendChild(pdiv);

			this.els.outer = outer;
			this.els.inner = inner;
		},

	 	remove : function() 
		{
		  this.els.outer.parentNode.removeChild(this.els.outer);
		},

		copy : function()
		{
			return new MapTooltip();
		},

		redraw : function(force) 
		{
			if (!force) return;

			if (!this.latlng) return;

			var p = this.map.fromLatLngToDivPixel(this.latlng);

			var s = this.els.outer.getSize();

			var x = p.x-(s.x/2);
			var y = p.y-this.yoffset-s.y;		

			this.els.outer.style.left = x+'px';
			this.els.outer.style.top = y+'px';
		},

		//
		//	Extra
		//
		show : function(marker, title)
		{
			if (this.els) 
			{
				this.yoffset = marker.getIcon ? (marker.getIcon().iconAnchor.y+3) : 3;


				this.latlng = marker.getLatLng();
				title = title || marker.getTitle() || '';
				this.els.inner.innerHTML = title;
				this.els.outer.style.display = 'block';
				this.redraw(true);
			}
		},

		hide : function()
		{
			if (this.els) this.els.outer.style.display = 'none';
		}

	});
	
}


