﻿/*
jQuery and Google Maps Tutorial
	http://marcgrabanski.com/article/jquery-google-maps-tutorial-basics
	Comment #12. Erik White
		http://www.erikwhite.net/gmapjquery.html
*/
$(document).ready(function(){

	if( $("#propertiesmap").length > 0 ) {
		
		var defaultLat = 55.3888;
		var defaultLon = -3.29205;
		
		var map = new google.maps.Map2($("#propertiesmap").get(0));
		map.setCenter(new GLatLng(defaultLat, defaultLon), 8);
		map.disableDoubleClickZoom();
		map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl());

		//This section works fine but does not animate on load
		var bounds = new GLatLngBounds();

		$(markers).each(function(i,marker){

			map.addOverlay(marker[0]);
            bounds.extend(marker[3]);

		    GEvent.addListener(marker[0], "click", function(){
				displayPoint(marker[0], i);
			    setActive(i);//Show active location
				if ($('#map_message').is(':hidden')) {//Allow toggling of active state
					setActive();
				}
			});

		});

		map.setZoom(map.getBoundsZoomLevel(bounds));
		map.setCenter(bounds.getCenter());



		//$("#map_list").css("opacity","0.2").animate({opacity: 1}, 1100);//Fade in menu
		$("#map_message").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));


		var zoomEnd = GEvent.addListener(map,"zoomend", function(oldLevel, newLevel){ 
			$('#map_message').hide()
		});
						
		function displayPoint(marker, index){

			if ($('#map_message').is(':hidden')) {//Allow toggling of markers
				$('#map_message').fadeIn();
			}
			else{//Remove all .active classes and hide markers
				$('#map_message').hide();
				$(".active").removeClass();
			}
			//$("#map_message").hide();//Default behaviour, doesn't allow toggling

			var moveEnd = GEvent.addListener(map, "moveend", function(){
					var markerOffset = map.fromLatLngToDivPixel(marker.getLatLng());
					$("#map_message")
						.html(markers[index][2])//Use information from array
						.fadeIn()
						.css({ top:markerOffset.y-150, left:markerOffset.x+15 });
					GEvent.removeListener(moveEnd);
				});
				map.panTo(marker.getLatLng());
		}	
		
		function setActive(el){
			$(".active").removeClass();//Remove all .active classes
			$("#map_list").find('li').eq(el).addClass('active');//Find list element equal to index number and set active
			$(el).addClass('active');//Set active if list element clicked directly
		}
	}
});