var osmOptions = {
	getTileUrl: function(coord, zoom) {
		return "http://tile.openstreetmap.org/"+zoom+"/"+coord.x+"/"+coord.y+".png"
	}
	,tileSize: new google.maps.Size(256, 256)
	,maxZoom:18
	,name:"Drew"
	,alt:"Drew University Campus Map"
};
var map;
var infoWindow = new google.maps.InfoWindow();
var locations;
var maplocations = [];
var currentbld = "";
var walkingpath;
var maplegend;

function makePOI(type, poidata, options){
	options.content = 
	'<div style="width:580px;min-height:100px;">'+
		'<h2 style="margin:0 0 .5em 0;padding:0 0 0 0;">'+poidata.name+'</h2>';
			if (poidata.img)options.content+= '<img src="images/buildings/'+poidata.img+'" width="200" height="150" style="margin-left:1em;padding:0;border:0;" />';
			if (poidata.description) options.content+=  poidata.description;
	options.content+=  '<h3 style="margin:0;padding:.5em 0 0 0;display:block;clear:both;">Directions</h3>';
	options.content+=  "<div>Get walking directions between here and <select onchange=\"SetPaths('" + poidata.id + "',this.options[this.selectedIndex].value)\"><option></option>";
	
	$(locations).each(function(x, bld){
		options.content+= "<option value='"+bld.id+"'>"+bld.name+"</option>";
	});
	
	options.content+=  "</select></div>";	
	options.content+=  '</div>';
	
	//define and draw the POI
	if (type == 'marker'){
		var poi = new google.maps.Marker({map:map});
		poi.setOptions(options);
	} else if (type == 'poly'){
		var outline = [];
		var geooutline = poidata.geooutline.split(",")
		for (i=0;i<geooutline.length;i++){
			outline.push(
				new google.maps.LatLng(geooutline[i+1], geooutline[i])
			)
			i++;
		}
		var poi = new google.maps.Polygon({map:map});
		poi.setOptions({
			paths: outline
			,strokeColor: "#6FFFFC"
			,strokeOpacity: 0.7
			,strokeWeight: 2
			,fillColor: "#000000"
			,fillOpacity: 0.0
		});
	}
	// infoWindow for the POI
	google.maps.event.addListener(poi, 'click', function(){
		infoWindow.setOptions(options);
		if (type ='poly') infoWindow.setPosition( new google.maps.LatLng(poidata.lat,poidata.lon) );
		infoWindow.open(map);
		currentbld = poidata.id;
		$.historyLoad("building="+poidata.id);
	});
	if (type == 'poly') poi.setMap(map);
	maplocations[poidata.id] = poi;
	return poi;
}

function openMarker(i){
	google.maps.event.trigger(maplocations[i],'click');
};

function SetPaths(startpoint, endpoint){
	$.historyLoad("start="+startpoint+"&end="+endpoint);
}
function GetPaths(startpoint, endpoint){
	if (walkingpath) walkingpath.polyline.setMap();
	$.getJSON("getpath.php", {start:startpoint.vertexid ,end:endpoint.vertexid}, function(data){
		if (data.status == 207){
			alert("Unable to find directions at this time.");
		}else{
			pathlist = [];
			$(data.route_geometry).each(function(a,b){
				pathlist[a] = new google.maps.LatLng(b[0], b[1]);
			});
			//set up the walking directions line 
			walkingpath = {
				polyline : new google.maps.Polyline({
					path: pathlist
					,strokeColor: "#FF0000"
					,strokeOpacity: 1.0
					,strokeWeight: 2
				})
				/*
				,start : new google.maps.Marker({
					position: new google.maps.LatLng(40.760651,-74.426429), 
					map: map, 
					title:"Hello World!"
				})
				,end : new google.maps.Marker({
					position: new google.maps.LatLng(40.760651,-74.426429), 
					map: map, 
					title:"Hello World!"
				})
				*/
			};
			walkingpath.polyline.setMap(map);
			infoWindow.close();
			var bounds = new google.maps.LatLngBounds();
			//var bounds = new google.maps.LatLngBounds(pathlist[0], pathlist[(pathlist.length)-1]); 
			$(pathlist).each(function(a, p){
				bounds.extend(p);
			});
			map.setCenter(bounds.getCenter());
			map.fitBounds(bounds); 

		}
	});
}

function pageload(hash) {
	if(hash){
		hash = "?"+hash;
		
		building = parseUri(hash).queryKey.building;
		startpoint = parseUri(hash).queryKey.start;
		endpoint = parseUri(hash).queryKey.end;
		
		if (building){
			if (currentbld != building){
				openMarker(building);
			}
		} else if (startpoint && endpoint){
			$(locations).each(function(x, bld){
				if (startpoint == bld.id){
					startpoint = bld;
				}
				if (endpoint == bld.id){
					endpoint = bld;
				}
			});
			GetPaths(startpoint, endpoint);
		}
	}
}
function changesize(){
	mheight = $(window).height() - $("body>section").offset().top;
	if (mheight > 550) {
		$("#map_canvas").height(mheight);
		maplegend.height(mheight);
	}
}
$(function(){
	$("body>section:eq(0)").removeClass('clearfix');
	maplegend = $("#maplegend");
	changesize();
	$(window).resize(function(){changesize()});
	var osmMapType = new google.maps.ImageMapType(osmOptions);
	var drew = new google.maps.LatLng(40.7611,-74.4264);

	var mapOptions = {
		zoom: 17
		,center: drew
		,mapTypeControlOptions: {
			mapTypeIds: ['coordinate', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE]
		}
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
	map.mapTypes.set('coordinate',osmMapType);
	map.setMapTypeId('coordinate');

	//add the buildings
	$.getJSON('buildings.php',function(data){
		locations = data;
		$(locations).each(function(x, bld){
			if (bld.geooutline){
				makePOI('poly', bld, {
					position: new google.maps.LatLng(bld.lat,bld.lon), 
					title: bld.name,
					content: '<div><h1>Lorem ipsum</h1>Lorem ipsum dolor sit amet<div>'
				});
			} else {
				makePOI('marker', bld,{
					position: new google.maps.LatLng(bld.lat,bld.lon), 
					title: bld.name,
					content: '<div><h1>Lorem ipsum</h1>Lorem ipsum dolor sit amet<div>'
				});
			}		
		});
		$.historyInit(pageload);


		//build the legend
		maplegend.append(
			"<div id='parking'><h3>Parking</h3><ul></ul></div>"
			+"<div id='aa'><h3>Academics &amp; Administrative</h3><ul></ul></div>"
			+"<div id='athletics'><h3>Athletics</h3><ul></ul></div>"
			+"<div id='residence'><h3>Residence Halls</h3><ul></ul></div>"
			+"<div id='other'><h3>Other</h3><ul></ul></div>"
		);
		
		$(locations).each(function(x, b){
			switch (b.type){
				case 'P':
					maplegend.find('#parking ul').append("<li><a href='#building="+b.id+"'>"+b.name+"</a></li>");
				break;
				case 'S':
					maplegend.find('#athletics ul').append("<li><a href='#building="+b.id+"'>"+b.name+"</a></li>");
				break;
				case 'R':
					maplegend.find('#residence ul').append("<li><a href='#building="+b.id+"'>"+b.name+"</a></li>");
				break;
				case 'A':
					maplegend.find('#aa ul').append("<li><a href='#building="+b.id+"'>"+b.name+"</a></li>");
				break;
				default:
					maplegend.find('#other ul').append("<li><a href='#building="+b.id+"'>"+b.name+"</a></li>");
			}
		});
		
	});
	google.maps.event.addListener(map, 'click', function(arg) {
		infoWindow.close();
	});
});
