var GoogleMap = Class.create();
GoogleMap.prototype =
{
	initialize: function(config)
	{
		this.map_container = $(config['map_container_id']);
		this.static_map_container = $(config['static_map_container_id']);
		this.lat = config['lat'];
		this.longitude = config['long'];
		this.zoom = config['zoom'];
		this.markers = config['markers'];
		this.never_hide_info_window = false;
		this.large = false
		this.start_counter = 0;
		if(config['large'] != undefined)
		{
		    this.large = config['large']
		}
		if(config['never_hide_info_window'] != undefined)
		{
			this.never_hide_info_window = config['never_hide_info_window']

		}
		if(config['baseurl'] != undefined)
		{
			this.baseurl = config['baseurl'];
		}
		if (config['start'] != undefined)
		{
			this.start_counter = config['start'];
		}
	},
	display_map : function()
	{
		var that = this;

		setTimeout(//Have to show map after time delay to avoid breaking page layout
			function()
			{
				try
				{
					if (!window.GMap2) {throw 'no gmap2';}
					if (!GBrowserIsCompatible()) throw 'incompatible';
		            if (!window.opera) window.onunload = GUnload;
		            var map = new GMap2(that.map_container);
		            map.enableContinuousZoom();
		            map.setCenter(new GLatLng(that.lat, that.longitude), that.zoom);
		            
		            if (that.large) {
		                map.addControl(new GLargeMapControl3D());
    		            map.addControl(new GMapTypeControl());
    		            map.addControl(new GOverviewMapControl()); 
    		            map.addControl(new GScaleControl());
		            }
		            else {
    		            map.addControl(new GSmallZoomControl3D());
    		            //map.addControl(new GHierarchicalMapTypeControl());
		            }
		            
		            var SearchIcon = new GIcon();
		            SearchIcon.image = "/include/images/map/marker.png";
		            SearchIcon.shadow = "/include/images/map/marker_shadow.png";
		            SearchIcon.transparent = "/include/images/map/marker_transparent.png";
		            SearchIcon.iconSize = new GSize(25, 25);
		            SearchIcon.shadowSize = new GSize(42, 25);
		            SearchIcon.iconAnchor = new GPoint(0, 23);
		            SearchIcon.infoWindowAnchor = new GPoint(5, 1);

		            var search_near_centre = $('search_near_centre');
		            if(search_near_centre)
		            {
			            var moveend = GEvent.bind(map,"moveend",map,function(){
			                GEvent.removeListener(moveend);


			                search_near_centre.hide();
			                search_near_centre.innerHTML = 'Search again near current centre of the map';

			                var showing_only_xxx_results = search_near_centre.previous();
			                if (showing_only_xxx_results)
			                    Effect.Fade(showing_only_xxx_results,{duration:0.2, afterFinish:function(){
			                        Effect.Appear(search_near_centre,{duration:0.2});
			                    }});
			                else
			                    Effect.Appear(search_near_centre,{duration:0.2});

			                search_near_centre.onclick = function()
			                {
			                    var mapcenter = map.getCenter();
			                    that.baseurl = that.baseurl.replace(/([&?])radius=[^&#]*&?/,'$1').replace(/([&?])(postcode|landmark)=[^&#]*&?/,'$1').replace(/([&?])long_lat=[^&#]*&?/,'$1');
			                    window.location = that.baseurl.replace(/&?(#.*|$)/, '&long_lat=' + mapcenter.lng() + ',' + mapcenter.lat() + '$1');
			                    return false;
			                };
			            });
		            }
					var infoWindow = new function()
					{
						var self = this;
						var element = $(document.createElement('div'));
						element.className = 'map-info-window';
						element.style.position = 'absolute';
						element.style.zIndex = '100';
						element.style.bottom = '50%';
						element.style.left = '50%';
						element.hide();

//						map_container.parentNode.insertBefore(element,map_container.nextSibling);
						map.getPane(G_MAP_FLOAT_PANE).appendChild(element);

						var hideTimer;
						var showTimer;

						this.hide = function()
						{
							if(that.never_hide_info_window)
							{
								return;
							}
							if (showTimer)
							{
								clearTimeout(showTimer); showTimer = null;
								Effect.Fade(element,{duration:0.2});
							}
							else
							{
								if (hideTimer) clearTimeout(hideTimer);
								hideTimer = setTimeout(function()
								{
									hideTimer = null;
									Effect.Fade(element,{duration:0.2});//.hide();
								},500);
							}
						};

						var lastPoint;

						this.show = function(point, markerinfo)
						{
							lastPoint = point;

							if (hideTimer) {clearTimeout(hideTimer); hideTimer = null; element.hide();}
							if (showTimer) clearTimeout(showTimer);

							showTimer = setTimeout(function(){
								Effect.Appear(element,{duration:0.1});
//								element.show();
								showTimer = null;
							},250);

//							element.hide();
							while(element.firstChild) element.removeChild(element.firstChild);
							//If tab is always expaded, don't show link
							if(markerinfo['is_expanded'])
							{
								var title_tag = document.createElement('span');
							}
							else
							{
								var title_tag = document.createElement('a');
								title_tag.setAttribute('href',markerinfo['url']);
							}
							title_tag.appendChild(document.createTextNode(markerinfo['name']));
							element.appendChild(title_tag);
							if (markerinfo['description']) element.appendChild(document.createTextNode(markerinfo['description']));

							var img = document.createElement('img');
							img.setAttribute('src','/include/images/map/marker_corner.png');
							img.setAttribute('alt','');
							element.appendChild(img);

					        var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(point,map.getZoom());
							var zeropoint= map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());

					        var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, offset);

							element.style.bottom = element.parentNode.offsetHeight - (offset.y - zeropoint.y) + 4 + 'px';
							element.style.left = offset.x - zeropoint.x + 6 + 'px';
						};

						element.onmouseover = function()
						{
							if (showTimer) return;
							if (hideTimer) clearTimeout(hideTimer); hideTimer = null;
						};

						element.onmouseout = function()
						{
							if (hideTimer) return;
							if (showTimer) clearTimeout(showTimer); showTimer = null;
							self.hide();
						};

						element.onclick = function()
						{
							if (showTimer) clearTimeout(showTimer); showTimer = null;
							if (hideTimer) clearTimeout(hideTimer); hideTimer = null;
							Effect.Fade(element,{duration:0.2});

							if (lastPoint)
							{
								map.panTo(lastPoint);
			                    if (map.getZoom() < 14) setTimeout(function(){
			                            map.zoomIn();
			                            map.panTo(lastPoint);
			                    },150);
							}
						};
					};

		            var newMarker = function(point,markerinfo,count)
		            {
						var obj = markerinfo['type'] && $(markerinfo['type']);
						if (obj)
						{
							obj.onmouseover = function()
							{
								infoWindow.show(point,markerinfo);
							};
						}
						
						
						if (count > 0) {
							var width = 40;
							if (count < 10) {
								width = 25;
							}
							else if (count < 100) {
								width = 27
							}
							else if (count < 1000) {
								width = 35;
							}
							
				            var icon = new GIcon();
							icon.image = "/include/images/map/marker_" + count + ".png";
							icon.shadow = "/include/images/map/marker_shadow.png";
							icon.transparent = "/include/images/map/marker_transparent.png";
							icon.iconSize = new GSize(width, 25);
							icon.shadowSize = new GSize(42, 25);
							icon.iconAnchor = new GPoint(0, 23);
							icon.infoWindowAnchor = new GPoint(5, 1);
				            
							var marker = new GMarker(point, {icon:icon});
						    var type_specific_image = "/include/images/map/marker_" + count + ".png";
						}
						else {
							var marker = new GMarker(point, {icon:SearchIcon});
							var type_specific_image = "/include/images/map/marker.png";	
						}
                        
						GEvent.bind(marker,"dblclick", null, function() {
							location = markerinfo['url'];
						});

		                GEvent.bind(marker,"click", null, function() {
							infoWindow.show(point,markerinfo);
		                    map.panTo(point);
		                    if (map.getZoom() < 14) setTimeout(function(){
		                            map.zoomIn();
		                            map.panTo(point);
		                    },150);
		                });
		                GEvent.bind(marker,"mouseover", null, function() {
							marker.setImage("/include/images/map/marker_inert.png");
		    				infoWindow.show(point,markerinfo);
		            	});
		                GEvent.bind(marker,"mouseout", null, function() {
							marker.setImage(type_specific_image);
							infoWindow.hide();
		                });
		                map.addOverlay(marker);

						if (markerinfo['type'] && count < 1)
						{
							switch(markerinfo['type'].charAt(0))
							{
								case 'r': type_specific_image = "/include/images/map/marker_r.png"; break;
								case 'f': case 'd': type_specific_image = "/include/images/map/marker_f.png"; break;
								case 'v': case 'g': case 'e': type_specific_image = "/include/images/map/marker_v.png"; break;
							}
						}
						
						if (type_specific_image != "/include/images/map/marker.png") {
						    marker.setImage(type_specific_image);
						}
						
		            	if(markerinfo['is_expanded'])
		            	{
		            		infoWindow.show(point,markerinfo);
		            	}
		            };

		            for(m=0; m < that.markers.length; m++)
		            {
		                var index = m+1
		                if (that.markers.length > 60 || that.never_hide_info_window) {
		                    index = 0;
		                }

		                newMarker(new GLatLng(that.markers[m]['lat'],that.markers[m]['long']), that.markers[m], index + that.start_counter);
		            }
				}
				catch(e)
				{
					//alert(e.message || e);
					//Falied to show map, use static map instead
					if (that.static_map_container && that.static_map_container.style)
					{
						that.static_map_container.display='';
					}
				}
			},
			100);
	},
	on_map_move : null

};
