var map = null;
var walkIcon = null;

window.onresize=resizeMap;

function loadMap(lat, lng, zoom, view)
{
	if (GBrowserIsCompatible()) 				// Do Map if Compatible Browser only
	{
		map = new GMap2(document.getElementById("map"),{draggableCursor: 'crosshair'});
		resizeMap();
		
		map.addControl(new GLargeMapControl());
		map.addControl(new GScaleControl()) ;    	
		map.addMapType(G_PHYSICAL_MAP);
		map.addControl(new GMapTypeControl());

		setView(view);
		var latlng = new GLatLng(lat,lng) ;
		map.setCenter(latlng,zoom);
		
		loadIcons();
		loadRoutes();
	}else	{
		document.getElementById("map").innerHTML = "<h1>Browser not compatible with Google Maps. Sorry...</h1>" ;
	}
}

function setView(view)
{
	switch(view){
		case 'Satellite':
			mapType = G_SATELLITE_MAP;
			break;
		case 'Terrain':
			mapType = G_PHYSICAL_MAP;
			break;
		case 'Hybrid':
			mapType = G_HYBRID_MAP;
			break;
		default:
			mapType = G_NORMAL_MAP;
	}
	map.setMapType(mapType);
}


function resizeMap()
{
	var mapElement = document.getElementById("map");
	if( window.innerHeight )
	{
		var width = window.innerWidth - 530;
		var height = window.innerHeight - 210;
	} 
	else
	{
		var width = document.documentElement.offsetWidth - 530; 
		var height = document.documentElement.offsetHeight - 210;
	}
	mapElement.style.width = width  + 'px';
	mapElement.style.height = height + 'px';
}

function loadIcons()
{
	walkIcon = new GIcon();
	walkIcon.image = "http://www.walkscene.co.uk/images/start_flag.png";
	walkIcon.shadow = "http://www.walkscene.co.uk/images/flag_shadow.png";
	walkIcon.shadowSize = new GSize(34,20);
	walkIcon.iconSize = new GSize(20,20);
	walkIcon.iconAnchor = new GPoint(2,20);
	walkIcon.infoWindowAnchor = new GPoint(10,15);
}

function loadRoutes()
{
	var request = GXmlHttp.create();
	request.open('GET', '/main/ajax_routeSearch', true);

	//tell the request what to do when the state changes.
	request.onreadystatechange = function() 
	{
		if (request.readyState == 4 && request.status == 200) 
		{
//alert (request.responseText);

// handle JSON route data
			var routes = eval(request.responseText);
			for(var i=0; i<routes.length; i++)
			{

				var lat = parseFloat(routes[i].lat);
				var lng = parseFloat(routes[i].lng);
				if(lat && lng){
					var marker = new GMarker(new GLatLng(lat, lng), {icon: walkIcon, clickable:true});
					marker.infoHtml = routes[i].infoHtml;
					map.addOverlay(marker);
					
					GEvent.addListener(marker, 'click', function(){						
						this.openInfoWindowHtml(this.infoHtml, {maxWidth:300});						
					});
				}
			}			
		}	
	} //function	
	request.send(null);	
}
