if (typeof HSP == "undefined") HSP = new Object();
if (typeof HSP.map == "undefined") HSP.map = new Object();

HSP.map.the_map = null;
HSP.map.the_mgr = null;

HSP.map.paddingX = 20;
HSP.map.paddingY = 20;

HSP.map.init = function (json, which_maps, zoom)
{
	console.log("HSP.map.init()", GBrowserIsCompatible());
	
	if (!GBrowserIsCompatible()) return;
	
	HSP.map.json = json;

	HSP.map.the_map = new GMap2(document.getElementById("map"));
	
	// city hall
	var latitude = 39.954293352120565;
	var longitude = -75.16439348459244;
	
	HSP.map.the_map.setCenter(new GLatLng(latitude, longitude), zoom);
	
	HSP.map.the_map.enableDragging();
	HSP.map.the_map.enableContinuousZoom();
	HSP.map.the_map.enableDoubleClickZoom();
	HSP.map.the_map.disableScrollWheelZoom();
		
	HSP.map.the_map.addControl(new GLargeMapControl3D(false), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,10)));
	// HSP.map.the_map.addControl(new GOverviewMapControl());

	HSP.map.the_mgr = new MarkerManager(HSP.map.the_map);
	
	HSP.map.addMarkers();

	HSP.map.showMarkers();
	HSP.map.updateCookie();

	HSP.map.build_layers();

	HSP.map.show_layers(which_maps);

	$(window).unload(GUnload);
}

HSP.map.addMarkers = function ()
{
	var url;
	
	console.log("HSP.map.addMarkers()", HSP.map.places.length);

	HSP.map.queue = [];

	HSP.map.markers = new Object();
	
	HSP.map.markers.all = [];
	HSP.map.markers.center = null;
	HSP.map.markers.visible = null;

	GEvent.addListener(HSP.map.the_map, "extinfowindowopen",        HSP.map.extinfowindowopen);
	GEvent.addListener(HSP.map.the_map, "extinfowindowbeforeclose", HSP.map.extinfowindowbeforeclose);
	GEvent.addListener(HSP.map.the_map, "extinfowindowclose",       HSP.map.extinfowindowclose);
	GEvent.addListener(HSP.map.the_map, "extinfowindowupdate",      HSP.map.extinfowindowupdate);

	for (var i = 0; i < HSP.map.places.length; i++) {
		if (HSP.map.places[i].latitude && HSP.map.places[i].longitude) {
			HSP.map.addMarker(HSP.map.places[i]);
		}
	}
}

/*
**
*/

HSP.map.display = new Object();

HSP.map.display.neighborhood = 0;
HSP.map.display.topics = [];
HSP.map.display.sources = [];
HSP.map.display.tour = 0;

HSP.map.updateCookie = function () {
	$.cookie("hsp_map_neighborhood_cookie", HSP.map.display.neighborhood, { path: '/' });
	$.cookie("hsp_map_topics_cookie", HSP.map.display.topics.join(","), { path: '/' });
	$.cookie("hsp_map_sources_cookie", HSP.map.display.sources.join(","), { path: '/' });
	$.cookie("hsp_map_display_cookie", HSP.map.display.tour, { path: '/' });
}

HSP.map.hasACommon = function (a1, a2) {
	var i;
	var j;
	var l1 = a1.length;
	var l2 = a2.length;
	
	for (i = 0; i < l1; i++) {
		for (j = 0; j < l2; j++) {
			if (a1[i] == a2[j]) return true;
		}
	}
	
	return false;
}

HSP.map.showMarkers = function (recenter)
{
	if (recenter == undefined) recenter = true;
	
	console.log("HSP.map.showMarkers()", HSP.map.display.neighborhood, HSP.map.display.topics);
	
	var latitude = 0;
	var longitude = 0;
	var i;

	var hier_left;
	var hier_right;

	HSP.map.the_mgr.clearMarkers();
	
	HSP.map.markers.center = [];
	HSP.map.markers.visible = [];
	
	for (var i = 0; i < HSP.map.places.length; i++) {
		var ok1 = false;
		var ok2 = false;
		
		if (HSP.map.display.neighborhood == 0) {
			ok1 = true;
		} else {
			hier_left  = HSP.map.neighborhoods[HSP.map.display.neighborhood]["hier_left"];
			hier_right = HSP.map.neighborhoods[HSP.map.display.neighborhood]["hier_right"];
		
			if (HSP.map.places[i].hier_left > hier_left && HSP.map.places[i].hier_right < hier_right) {
				ok1 = true;
			}
		}

		// if (!ok1) continue;
		
		if (HSP.map.display.topics.length == 0) {
			ok2 = true;
		} else {
			ok2 = HSP.map.hasACommon(HSP.map.display.topics, HSP.map.places[i].topics);
		}
		
		if (!ok2) continue;
		
		if (HSP.map.display.sources.length == 0) {
			ok3 = true;
		} else {
			ok3 = HSP.map.hasACommon(HSP.map.display.sources, HSP.map.places[i].occurrence_source_ids);
		}

		if (!ok3) continue;

		if (ok1) {
			HSP.map.markers.center.push(HSP.map.markers.all[i]);
		}
		
		if (ok2 && ok3) {
			HSP.map.markers.visible.push(HSP.map.markers.all[i]);
		}
	}

	if (!HSP.map.markers.visible || HSP.map.markers.visible.length == 0) return;

	HSP.map.the_mgr.addMarkers(HSP.map.markers.visible, 0);

	if (false && recenter) {
		for (i = 0; i < HSP.map.markers.center.length; i++) {
			var latlng = HSP.map.markers.center[i].getLatLng();
			
			latitude += latlng.lat();
			longitude += latlng.lng();
		}
		
		latitude /= HSP.map.markers.center.length;
		longitude /= HSP.map.markers.center.length;
		
		HSP.map.the_map.setCenter(new GLatLng(latitude, longitude));
	}
	
	HSP.map.the_mgr.refresh();

	HSP.map.closeMarkers();
}

HSP.map.closeMarkers = function ()
{
	HSP.map.the_map.closeExtInfoWindow();
}

/*
**
*/

HSP.map.addMarker = function (place)
{
	var marker = HSP.map.createClickableMarker(place);

	HSP.map.markers.all.push(marker);
	
	// console.log("HSP.map.addMarker()", place.name, place.latitude, place.longitude, HSP.map.markers.all.length-1, marker);
}

HSP.map.createMarker = function (place)
{
	var nstories = place.occurrence_ids.length;
	
	if (nstories == 0) return null;

//	console.log("HSP.map.createMarker()", place.latitude, place.longitude, place.name);
	
	var icon = new GIcon();

	icon.image = "/_images/theme/map/" + place.source + "_pin.png";

	switch (place.source) {
		case "hsp": case "partner": case "vcc":
			icon.iconSize = new GSize(16,22);
			icon.iconAnchor = new GPoint(8,20);
			icon.infoWindowAnchor = new GPoint(7,14);
			break;
		case "hsp_partner": case "hsp_vcc": case "partner_vcc":
			icon.iconSize = new GSize(18,24);
			icon.iconAnchor = new GPoint(9,22);
			icon.infoWindowAnchor = new GPoint(9,14);
			break;
		case "hsp_partner_vcc":
			icon.iconSize = new GSize(22,30);
			icon.iconAnchor = new GPoint(11,28);
			icon.infoWindowAnchor = new GPoint(11,14);
			break;
	}

	var opts = new Object();
	
	opts.title = place.name;
	
	// if (nstories > 1) opts.title +=" (" + place.occurrence_ids.length + " stories)";
	
	opts.icon = icon;
	
	var marker = new GMarker(new GLatLng(place.latitude, place.longitude), opts);
	
	return marker;
}

HSP.map.createClickableMarker = function (place)
{
	var marker = HSP.map.createMarker(place);

	GEvent.addListener(marker, 'click', function() { 
		var ajaxURL = null;

		HSP.map.place_id = place.place_id;

		if (HSP.map.display.tour > 0) {
			ajaxURL = HSP.url + "/html/tour_place_marker/" + HSP.map.place_id + "/";
		} else {
			ajaxURL = HSP.url + "/html/" + HSP.map.json + "/" + HSP.map.place_id + "/";
		}
		
		marker.openExtInfoWindow (
			HSP.map.the_map,
			"hsp-marker-popup",
			null,
			{ ajaxUrl: ajaxURL, paddingX: HSP.map.paddingX, paddingY: HSP.map.paddingY, beakOffset: 0 }
		);
	});

	return marker;
}

/*
**
*/

HSP.map.extinfowindowopen = function ()
{
//	console.log("HSP.map.extinfowindowopen()", HSP.map.place_id, HSP.map.occurrence_id);

	HSP.map.display.tour_flag = false;
}

HSP.map.extinfowindowupdate = function (foo)
{
	console.log("HSP.map.extinfowindowupdate()", HSP.map.place_id, HSP.map.occurrence_id);
	
	if (HSP.map.occurrence_id) {
		for (var i = 0; i < HSP.map.places.length; i++) {
			if (HSP.map.places[i].place_id ==  HSP.map.place_id) {
				break;
			}
		}
		
		for (var j = 0; j < HSP.map.places[i].occurrence_ids.length; j++) {
			if (HSP.map.places[i].occurrence_ids[j] ==  HSP.map.occurrence_id) {
				break;
			}
		}
		
		HSP.mappage.story_set(j+1);
	}
		
	if (HSP.id == "mappage") {
		HSP.util.trackEvent("Map Popup", "Open", "Place-" + HSP.map.place_id + " " + HSP.map.occurrence_id, 0);
	}
	
	$("#hsp-marker-popup_contents").parent().addClass("noprint");
}

HSP.map.extinfowindowbeforeclose = function ()
{
//	console.log("HSP.map.extinfowindowbeforeclose()", HSP.map.place_id, HSP.map.occurrence_id);

	if (HSP.map.display.tour_flag == false) {
		$("select#tours option").attr("selected", "");
		$("select#tours option#tours-0").attr("selected", "selected");
		$("body").removeClass("tour-mode");
		HSP.map.display.tour = 0;
	}
}

HSP.map.extinfowindowclose = function ()
{
//	console.log("HSP.map.extinfowindowclose()", HSP.map.place_id, HSP.map.occurrence_id);
	
	HSP.map.place_id = 0;
	HSP.map.occurrence_id = 0;
}


/*
**
*/

HSP.map.NORMAL = 1;
HSP.map.SATELLITE = 2;
HSP.map.HYBRID = 4;
HSP.map.PHYSICAL = 8;

HSP.map.MAP_1962 = 16;
HSP.map.MAP_1942 = 32;
HSP.map.MAP_1875 = 64;
HSP.map.MAP_1895 = 128;
HSP.map.MAP_1934 = 256;

HSP.map.STREETS = 131072;

HSP.map.build_layers = function ()
{
	// mostly borrowed from http://www.philageohistory.org/tiles/viewer/
	// which relies heavilly on http://johndeck.blogspot.com/
	
	HSP.map.layer = new Object();
	
	var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0,
                    				"<span class='geohistory-credit'>Historical maps supplied by <a href='http://www.philageohistory.org/geohistory/philaplace.cfm' target='_blank'>Greater Philadelphia GeoHistory Network</a></span>");
	var copyrightCollection = new GCopyrightCollection("");
	
	copyrightCollection.addCopyright(copyright);

	HSP.map.layer.map1875 = new GTileLayer(copyrightCollection, 1, 19);
	HSP.map.layer.map1875.getTileUrl = CustomGetTileUrl;
	HSP.map.layer.map1875.myLayers = 'GMH1875v6';
	HSP.map.layer.map1875.myFormat = 'image/png';
	HSP.map.layer.map1875.myBaseURL = 'http://tiles.philaplace.org/ecwcache2.php?';
	HSP.map.layer.map1875.mySRS = 'none';
	HSP.map.layer.map1875.myBaseMax = 6;
	HSP.map.layer.map1875.myBaseReplace = 'replace';
	HSP.map.layer.map1875.myBaseSubRoot = 'w';
	HSP.map.layer.map1875.getOpacity = customOpacity;
	
	HSP.map.layer.map1895 = new GTileLayer(copyrightCollection, 1, 19);
	HSP.map.layer.map1895.getTileUrl = CustomGetTileUrl;
	HSP.map.layer.map1895.myLayers = 'bromley1895';
	HSP.map.layer.map1895.myFormat = 'image/png';
	HSP.map.layer.map1895.myBaseURL = 'http://tiles.philaplace.org/ecwcache2.php?';
	HSP.map.layer.map1895.mySRS = 'none';
	HSP.map.layer.map1895.myBaseMax = 6;
	HSP.map.layer.map1895.myBaseReplace = 'replace';
	HSP.map.layer.map1895.myBaseSubRoot = 'w';
	HSP.map.layer.map1895.getOpacity = customOpacity;

	HSP.map.layer.map1934 = new GTileLayer(copyrightCollection, 1, 19);
	HSP.map.layer.map1934.getTileUrl = CustomGetTileUrl;
	HSP.map.layer.map1934.myLayers = 'JMB1934.Phila';
	HSP.map.layer.map1934.myFormat = 'image/png';
	HSP.map.layer.map1934.myBaseURL = 'http://tiles.philaplace.org/ecwcache2.php?';
	HSP.map.layer.map1934.mySRS = 'none';
	HSP.map.layer.map1934.myBaseMax = 6;
	HSP.map.layer.map1934.myBaseReplace = 'replace';
	HSP.map.layer.map1934.myBaseSubRoot = 'w';
	HSP.map.layer.map1934.getOpacity = customOpacity;

	HSP.map.layer.map1942 = new GTileLayer(copyrightCollection, 1, 19);
	HSP.map.layer.map1942.getTileUrl = CustomGetTileUrl;
	HSP.map.layer.map1942.myLayers = 'LUM1942';
	HSP.map.layer.map1942.myFormat = 'image/png';
	HSP.map.layer.map1942.myBaseURL = 'http://tiles.philaplace.org/ecwcache2.php?';
	HSP.map.layer.map1942.mySRS = 'none';
	HSP.map.layer.map1942.myBaseMax = 6;
	HSP.map.layer.map1942.myBaseReplace = 'replace';
	HSP.map.layer.map1942.myBaseSubRoot = 'w';
	HSP.map.layer.map1942.getOpacity = customOpacity;

	HSP.map.layer.map1962 = new GTileLayer(copyrightCollection, 1, 19);
	HSP.map.layer.map1962.getTileUrl = CustomGetTileUrl;
	HSP.map.layer.map1962.myLayers = 'LUM1962';
	HSP.map.layer.map1962.myFormat = 'image/png';
	HSP.map.layer.map1962.myBaseURL = 'http://tiles.philaplace.org/ecwcache2.php?';
	HSP.map.layer.map1962.mySRS = 'none';
	HSP.map.layer.map1962.myBaseMax = 6;
	HSP.map.layer.map1962.myBaseReplace = 'replace';
	HSP.map.layer.map1962.myBaseSubRoot = 'w';
	HSP.map.layer.map1962.getOpacity = customOpacity;
		
	HSP.map.layer.mapNormal = G_NORMAL_MAP.getTileLayers()[0];
	HSP.map.layer.mapSatellite = G_SATELLITE_MAP.getTileLayers()[0];
	HSP.map.layer.mapPhysical = G_PHYSICAL_MAP.getTileLayers()[0];
	HSP.map.layer.mapStreets = G_HYBRID_MAP.getTileLayers()[1];
}

HSP.map.show_layers = function (which, streets)
{
	console.log("HSP.map.show_layers()", which, streets);
	
	var layers = [ ];
	var i = 0;
	
	if (false || which & HSP.map.NORMAL) { layers[i++] = HSP.map.layer.mapNormal; }
	if (which & HSP.map.PHYSICAL)        { layers[i++] = HSP.map.layer.mapPhysical; }
	if (which & HSP.map.SATELLITE)       { layers[i++] = HSP.map.layer.mapSatellite; }
	if (which & HSP.map.MAP_1962)        { layers[i++] = HSP.map.layer.map1962; }
	if (which & HSP.map.MAP_1942)        { layers[i++] = HSP.map.layer.map1942; }
	if (which & HSP.map.MAP_1875)        { layers[i++] = HSP.map.layer.map1875; }
	if (which & HSP.map.MAP_1895)        { layers[i++] = HSP.map.layer.map1895; }
	if (which & HSP.map.MAP_1934)        { layers[i++] = HSP.map.layer.map1934; }

	if (streets) { layers[i++] = HSP.map.layer.mapStreets; }

	HSP.map.type = new GMapType(layers, G_SATELLITE_MAP.getProjection(), "HSP");
	
	HSP.map.the_map.getMapTypes().length = 0;
	HSP.map.the_map.addMapType(HSP.map.type);
	HSP.map.the_map.setMapType(HSP.map.type);
}

/*
**
*/

HSP.map.polyline = null;

HSP.map.disconnectVisibleMarkers = function ()
{
	if (HSP.map.polyline) {
		HSP.map.the_map.removeOverlay(HSP.map.polyline);
	}
}

HSP.map.connectVisibleMarkers = function ()
{
	var points = [];
	
	for (var i = 0; i <HSP.map.markers.visible.length; i++) {
		points.push(HSP.map.markers.visible[i].getLatLng());
	}
	
	HSP.map.disconnectVisibleMarkers();
	
	HSP.map.polyline = new GPolyline(points, "#ff0000", 5);
	
	HSP.map.the_map.addOverlay(HSP.map.polyline);
}

HSP.map.polygon = null;

HSP.map.unboxVisibleMarkers = function ()
{
	if (HSP.map.polygon) {
		HSP.map.the_map.removeOverlay(HSP.map.polygon);
	}
}

HSP.map.boxVisibleMarkers = function ()
{
	return;

	var points = [];

	var min_lat = 10000;
	var max_lat = -10000;
	var min_lng = 10000;
	var max_lng = -10000;

	for (var i = 0; i <HSP.map.markers.visible.length; i++) {
		var latlng = HSP.map.markers.visible[i].getLatLng();
		var lat = latlng.lat();
		var lng = latlng.lng();
		
		if (lat < min_lat) min_lat = lat;
		if (lat > max_lat) max_lat = lat;
		if (lng < min_lng) min_lng = lng;
		if (lng > max_lng) max_lng = lng;
	}
	
	HSP.map.unboxVisibleMarkers();
	
	var fudge = 0.001;
	
	HSP.map.polygon = new GPolygon([
		new GLatLng(min_lat - fudge, min_lng - fudge),
		new GLatLng(min_lat - fudge, max_lng + fudge),
		new GLatLng(max_lat + fudge, max_lng + fudge),
		new GLatLng(max_lat + fudge, min_lng - fudge),
		new GLatLng(min_lat - fudge, min_lng - fudge)
	], "#ff0000", 2, 1, "#ff0000", 0.25);
	
	HSP.map.the_map.addOverlay(HSP.map.polygon);
}

/*
**
*/

// other option here is to just use GGroundOverlay(), but that scales with zoom because it is bounded by a latlong box

HSP.map.imageOverlay = function (latlong, src)
{
	this.latlong_  = latlong;
	this.src_ = src;
}

HSP.map.imageOverlay.prototype = new GOverlay();

HSP.map.imageOverlay.prototype.initialize = function (map)
{
	var img = document.createElement("img");

	img.src  = this.src_;
	img.style.position = "absolute";
	
	map.getPane(G_MAP_MAP_PANE).appendChild(img);
	
	this.map_ = map;
	this.img_ = img;
	
	this.redraw();
}

HSP.map.imageOverlay.prototype.remove = function ()
{
	this.img_.parentNode.removeChild(this.img_);
}

HSP.map.imageOverlay.prototype.copy = function ()
{
	return new HSP.map.imageOverlay(this.latlong_, this.src_);
}

HSP.map.imageOverlay.prototype.redraw = function (force)
{
	var point = this.map_.fromLatLngToDivPixel(this.latlong_);

	this.img_.style.left = point.x + "px";
	this.img_.style.top = point.y + "px";
}

/*
**
*/

