var map;
var blockarray = new Array();
var cover=null;

function initialiseMaps()
{
	$(".blocklist").hide();									//Hide all right-hand lists of venues
	$(".categoryheader").click(togglemapblocks);			//Click to show venue list for each category
	$(".categoryheader").data("open", false);				//State of each of venue list: initially open=false
	$(".mapblockbox").mouseover(highlightmapblocks);		//Highlight venue on map when mouseovered
	$(".mapblockbox").mouseout(unhighlightmapblocks);		//Unhighlight on mouseout
	$(document).bind('mousemove', function(e) {$(this).data("pagex", e.pageX);$(this).data("pagey", e.pageY); } );	//Track mouse location to position polygon info div
	
	//Map options - Switch of business labels, bus/rail stations and 3D buildings
	var styleArray = [	{ featureType: "poi.business", elementType: "labels", stylers: [ { visibility: "off" } ] },
						{ featureType: "transit", element: "all",	stylers: [ { visibility: "off" } ] },
						{ featureType: "landscape.man_made", element: "all", stylers: [ { visibility: "off" } ] } ];
	
	//Initialise map centred and zoomed on Chinatown in div#mapcanvas
	var mapCentre = new google.maps.LatLng(51.511761,-0.130807);
	var mapOptions = { zoom: 17, minZoom: 17, maxZoom: 19, center: mapCentre, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, styles: styleArray};
	map = new google.maps.Map(document.getElementById("mapcanvas"), mapOptions);
	//google.maps.event.addListener(map, 'click', function(event) { console.log(map.getCenter()); });
	
	//Restrict map panning boundaries (different vals for each zoom level)
	map.set("validcenter", mapCentre);	//Default return point if a series of invalid pans occur
	var panBounds = new Array();
	var nePanBound = new google.maps.LatLng(51.511335, -0.130737);			//Pan boundaries for
	var swPanBound = new google.maps.LatLng(51.512196, -0.131660);  		//zoom level 17 (min zoom)
	panBounds.push(new google.maps.LatLngBounds(swPanBound, nePanBound));
	nePanBound = new google.maps.LatLng(51.512428, -0.129632);				//Pan boundaries for
	swPanBound = new google.maps.LatLng(51.511099, -0.132727);				//zoom level 18
	panBounds.push(new google.maps.LatLngBounds(swPanBound, nePanBound));	
	nePanBound = new google.maps.LatLng(51.512799, -0.128857);				//Pan boundaries for
	swPanBound = new google.maps.LatLng(51.510731, -0.133507);				//zoom level 19 (max zoom)
	panBounds.push(new google.maps.LatLngBounds(swPanBound, nePanBound));
	//Listen for mao events to make sure view is within bounds
	google.maps.event.addListener(map, 'center_changed', function(event) { mapPanHandler(event, this, panBounds, mapCentre); });
	google.maps.event.addListener(map, 'zoom_changed', function(event) { mapPanHandler(event, this, panBounds, mapCentre); });
	
	
	//Create the chinatown map overlay from a png file
	var swOverlayBound = new google.maps.LatLng(51.510362, -0.134287);
	var neOverlayBound = new google.maps.LatLng(51.513163, -0.128087);
	var overlayBounds = new google.maps.LatLngBounds(swOverlayBound, neOverlayBound);
	var srcImage = '/images/chinatown-transp-small.png';
	//var srcImage = '/images/chinatownplain.png';
	overlay = new google.maps.GroundOverlay(srcImage, overlayBounds, {clickable: false});
	overlay.setMap(map);
	
	if(venueid == null)
	{
		var swCoverBound = new google.maps.LatLng(51.510178, -0.134002);
		var neCoverBound = new google.maps.LatLng(51.513229, -0.127703);
		var coverBounds = new google.maps.LatLngBounds(swCoverBound, neCoverBound);	
		var coverImage = '/images/mapcover.png';	
		cover = new google.maps.GroundOverlay(coverImage, coverBounds);
		cover.setMap(map);
		google.maps.event.addListener(cover, 'click', function() { hideCover(this); } );
	}
	else
	{
		addPolygons();
		selectVenue(venueid);

	        newoverlay = new google.maps.GroundOverlay("/images/chinatown-transp-names-bold.png", overlayBounds, {clickable: false});
	        newoverlay.setMap(map);

	
	}

}

function selectVenue(venueid)
{
	$(".mapblockid").each(function(){
										if(venueid == $(this).val())
										{
											$(this).parent().parent().parent().children(".categoryheader").first().click();
											var container = $(this).parent();
											setTimeout(function() { $("#mapcontrols").scrollTop(container.offset().top-300); }, 2000);


											$(this).mouseover();
										}
									});
}

function hideCover(target)
{
	if(target != null)
		target.setMap(null);
	$("#instructions").hide();
	addPolygons();

	 //Create the chinatown map overlay from a png file
        var swOverlayBound = new google.maps.LatLng(51.510362, -0.134287);
        var neOverlayBound = new google.maps.LatLng(51.513163, -0.128087);
        var overlayBounds = new google.maps.LatLngBounds(swOverlayBound, neOverlayBound);


	newoverlay = new google.maps.GroundOverlay("/images/chinatown-transp-names-bold.png", overlayBounds, {clickable: false});
        newoverlay.setMap(map);

}

function addPolygons()
{
	for(var i=0; i<mapblocks.length; i++)
	{
		var polycoords = new Array();
		for(var j=0; j<mapblocks[i].polygon.length; j++)
		{
			polycoords.push(new google.maps.LatLng(mapblocks[i].polygon[j][0], mapblocks[i].polygon[j][1]));
		}
		var blockcolour = mapblocks[i].data.colour;
		var blockpolygon = new google.maps.Polygon({paths: polycoords, strokeColor: "#000000", strokeOpacity: 1.0, strokeWeight: 1, fillColor: blockcolour, fillOpacity: 0.6});
		blockpolygon.set("pageid", mapblocks[i].data.page_id);
		blockpolygon.set("title", mapblocks[i].data.page_title);
		blockpolygon.set("image", mapblocks[i].data.thumbnail);
		blockpolygon.set("url", mapblocks[i].data.url);
		blockpolygon.set("type", mapblocks[i].data.category_name);
		blockpolygon.set("typeid", mapblocks[i].data.category_id);
		blockpolygon.set("colour", blockcolour);
		blockpolygon.set("stroke", mapblocks[i].data.stroke);
		blockarray.push(blockpolygon);
		blockpolygon.setMap(map);
		google.maps.event.addListener(blockpolygon, 'mouseover', function(event){ showinfo(event, this) });
		google.maps.event.addListener(blockpolygon, 'mouseout' , function(event){ hideinfo(event); });
		if(mapblocks[i].data.clickable == 1)
			google.maps.event.addListener(blockpolygon, 'click', function (event) { navigate(this); });
	}
}

function mapPanHandler(event, target, bounds, defaultpan)
{
	if(bounds[target.getZoom() - 17].contains(target.getCenter()))
	{
		target.set("validcenter",  target.getCenter());
	}
	else
	{
		if(bounds[target.getZoom() -17].contains(target.get("validcenter")))			
			target.panTo(target.get("validcenter"));
		else
			target.panTo(defaultpan);
	}
}

function showinfo(event, target)
{
	$("#infotitle").text(target.get("title"));
	$("#infoimage").attr("src", "/images/files/thumbnail/" + target.get("image"));
	$("#infotype").text(target.get("type"));
	$("#infotype").css("background", target.get("colour"));
	$("#infotype").css("color", target.get("stroke"));
	$("#info").css("top", $(document).data("pagey") -170);				
	$("#info").css("left", $(document).data("pagex") - 435);
	$("#info").css("visibility", "visible");
	$("#info").css("display", "inherit");
	
}

function hideinfo()
{
	$("#info").css("visibility", "hidden");
	$("#info").css("display", "none");
}

function togglemapblocks(event)
{
	hideCover(cover);
	$(this).data("open", !($(this).data("open")));
	if($(this).data("open"))
	{	 
		$(".catselected").click();
		$(this).addClass("catselected");
		$(this).css("background-image", "url('/images/arrowopen.png')");
		$(this).parent().children(".blocklist").first().show("slide", { direction: "up" }, 1000);
		for(var i=0; i<blockarray.length; i++)
		{
			if(blockarray[i].get("typeid") == $(this).children(".categoryid").first().val())
			{
				blockarray[i].setMap(map);
			}
			else
			{
				blockarray[i].setMap();
			}
		}
	}
	else
	{	
		$(this).removeClass("catselected");	
		$(this).css("background-image", "url('/images/arrowclosed.png')");
		$(this).parent().children(".blocklist").first().hide("slide", { direction: "up" }, 1000);
		for(var i=0; i<blockarray.length; i++)
			blockarray[i].setMap(map);
	}
}

function highlightmapblocks(event)
{
	$(this).css("background", "#EEEEEE");
	for(var i=0;i<blockarray.length; i++)
		if(blockarray[i].get("pageid") == $(this).children(".mapblockid").first().val())
		{
			blockarray[i].setOptions({strokeColor: "#00F2FF", fillColor: "#00F2FF"});
			x = blockarray[i].getPath();
			map.panTo(x.getAt(0));
		}
		else
		{
			blockarray[i].setOptions({strokeColor: "black", fillColor: blockarray[i].get("colour")});
		}
		
}

function unhighlightmapblocks(event)
{
	$(this).css("background", "");
	for(var i=0;i<blockarray.length; i++)
		if(blockarray[i].get("pageid") == $(this).children(".mapblockid").first().val())
			blockarray[i].setOptions({strokeColor: "black", fillColor: blockarray[i].get("colour")});
}

function navigate(target)
{
	window.location = target.get("url");
}

