/*
 * Copyright (c) 2011, Chris Hill
 * l2.js is a GPL-licensed JavaScript library for map display and interaction.
 * version 0.4
*/

// the AJaX URI head. Change this if the AJaX server moves. It gets the rest of the URI added later
var ajxuri="/maps/ajxgetpolys.php";

// a place to store many maps
var maps = [];

//var map;
//var hull = new L.LatLng(53.775, -0.356);
var xhpoly;
//var polyLayer;

function initajx() {
	// ajax stuff
	xhpoly=GetXmlHttpObject();
	if (xhpoly==null) {
		alert ("This browser does not support HHTP request that the map needs");
		return;
	}
}
	
function initmap(lat,lng,zoom,id) {
	// set up the map
	var map = new L.Map(id);
	
	var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
	var osmAttrib='Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors';
	var osm = new L.TileLayer(osmUrl, {minZoom: 8, maxZoom: 18, attribution: osmAttrib});		
	
	cen = new L.LatLng(lat,lng);
	map.scrollWheelZoom.disable();
	map.setView(cen,zoom);
	map.addLayer(osm);
	map.polyLayer = new L.GeoJSON();
	map.addLayer(map.polyLayer);
	map.on('moveend', onMapMove);
	maps.push(map);
	askForPolys(map);
}

function onMapMove(e) {
	askForPolys(e.target);
}

function GetXmlHttpObject() {
	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		return new XMLHttpRequest();
	}
	if (window.ActiveXObject) {
		// code for IE6, IE5
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	return null;
}

function askForPolys(map) {
	// request the polygons for the map bounds
	var bounds=map.getBounds();
	var minll=bounds.getSouthWest();
	var maxll=bounds.getNorthEast();
	var URI=ajxuri+'?bbox=' + minll.lng + ',' + minll.lat + ',' + maxll.lng + ',' + maxll.lat + '&mapno=0';
	//use ajax in synchronous mode, to be sure the correct map gets updated
	xhpoly.open('GET', URI, false);
	xhpoly.send(null);
	
	var ret=eval("(" + xhpoly.responseText + ")");
	var mappno=ret.mappno;
	var geojsonFeature=ret.featlist;
			
	// clear the old layer
	map.polyLayer.clearLayers();
			
	// add the new features, using the embedded style
	map.polyLayer.on("featureparse", function (e) {
		// make the popup work
		if (e.properties && e.properties.popupContent) {
			e.layer.bindPopup(e.properties.popupContent);
		}
		// apply the style
		if (e.properties && e.properties.style && e.layer.setStyle) {
			e.layer.setStyle(e.properties.style);
		}
	});
	map.polyLayer.addGeoJSON(geojsonFeature);
}

