if (!GBrowserIsCompatible()) 
	throw ("This page only works in a browser that supports google maps");

Event.observe(document.body, 'unload', function () {GUnload();});

if (typeof LS == 'undefined') LS = {};

LS.Maps = {}
LS.Maps.CopyrightCoverage = new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180));
LS.Maps.Copyright = new GCopyright('cm', LS._CMCopyrightCoverage, 0,	'<a href="http://niusileadscape.org/contactus.php">NIUSI</a>');
LS.Maps.CopyrightCollection = new GCopyrightCollection('Education data:');
LS.Maps.CopyrightCollection.addCopyright(LS.Maps.Copyright);
LS.Maps.Map = Class.create({
	initialize: function(el, options) {
    //init map
		this.div = $(el);
		this.year = options.year;
		this.lea_id = options.lea_id;
    this._legend = this.div.down('.cm_legend');
    this._form = this.div.down('form');
    this._map = new GMap2(this.div.down('.cm_map'));
    this._slider_years = this.div.down('.cm_yearslider');
    this._map.enableContinuousZoom();
    this._map.enableScrollWheelZoom();
		this._map.addControl(new GSmallMapControl());
    this._map.addControl(new GHierarchicalMapTypeControl());
    this._map.addControl(new GScaleControl());
    this._map.setCenter(new GLatLng(0, 0), 1);
		this.layers = [];		
		this._cache = {}; //cache for data by year
		GEvent.addListener(this._map, "click", this._map_onclick.bind(this));
		var min = 2002;
		var max = 2007;
		var map = this;
		jq('#cm_yearslider').slider({
			min: min,
			max: max,
			startValue: this.year, 
			stepping:1,
			slide: function(e,ui) {
				jq('#cm_curyear').text(ui.value+'-'+(ui.value+1)); 
				var new_year = ui.value;
				if (new_year != map.year) {
					map._map.clearOverlays();
					map.year = new_year;
					var layer = map.schools[map.year];
					if (!layer) {
						//jq.jGrowl('No school data loaded for '+map.year, {header:'Error', lifetime:1000});
					} else {
						//jq.jGrowl('Loading '+layer.markers.length+' schools(s) for '+map.year, {header:'Notice', lifetime:1000});
					}
					map.setLayer.bind(map).defer(0, layer);

					jq("#cm_map_form input[name='year']").val(new_year);
					jq.get('/raw/mp/City/'+map.lea_id, {year:new_year, legend:'1', l0:map.l0, l1:map.l1}, function(data, textStatus) {
					try{
						var legend;
						eval('legend = '+data);
						jq('#cm_layer_l0').html(legend['cm_layer_l0']);
						jq('#cm_layer_l1').html(legend['cm_layer_l1']);
						var l1=jq("#cm_map_form select[name='l1']").val();
						map.l1=l1?l1:map.l1;
						map.setLayer.bind(map).defer(1, new LS.Maps.RRLayer(map.lea_id, map.year, map.l1));
					} catch(e) { if (console) console.warn('couldnt load data '+data)};
					}, 'text');
				}
			}
		});
	},
	_map_onclick: function(overlay, point) {
		if (overlay && overlay.school_id) { 
			if (typeof console != 'undefined') console.info(overlay);
			GDownloadUrl('/raw/mp/SchoolStats?d='+this.lea_id+'&y='+this.year+'&s='+overlay.school_id
			, function(d,r){
			  overlay.openInfoWindowHtml(d);
			});
		}
	},
	//pos:= array position, opts.use_bounds:= use the layer's bounding box to update the map viewport
	setLayer: function(pos, layer, opts) {
		if (typeof opts != 'object') opts = {};
		if (typeof pos == 'undefined') pos = this.layers.length; 
		this.removeLayer(pos);	
		if (typeof layer != 'object') return;
		var bounds = new GLatLngBounds();
		var overlays = layer.overlays();
		for(i=0; i < overlays.length; ++i) {
			var o = overlays[i];
			if (opts.use_bounds) {
				bounds.extend(o.getLatLng());
			}	
			this._map.addOverlay(o);
		}
		if (opts.use_bounds) {
			var z = this._map.getBoundsZoomLevel(bounds);	
			this._map.setCenter(bounds.getCenter(), z);
		}
		
		this.layers[pos] = layer;
	},
	// layer:= a layer object that is in the map or its index
	removeLayer: function(layer) {
		if (typeof layer != 'object') 
			layer = this.layers[layer];
		if (typeof layer != 'object') 
			return; 
		var overlays = layer.overlays();
		for(i=0; i < overlays.length; ++i) {
			var o = overlays[i];
			try { this._map.removeOverlay(o); } catch (e) { if (console) console.warn(e); };
		}
		this.layers = this.layers.without(layer);
	}
});

(function(){
		var baseIcon = new GIcon();
		baseIcon.iconSize = new GSize(10, 10);
		baseIcon.iconAnchor = new GPoint(5, 5);
		baseIcon.infoWindowAnchor = new GPoint(5, 5);				
		LS.Maps.Icons = {};
		var ids = ['b','g','w'];
		for (i=0; i < ids.length; ++i) {
			LS.Maps.Icons[ids[i]] = new GIcon(baseIcon); LS.Maps.Icons[ids[i]].image = "/images/maps/"+ids[i]+"10.gif";
		}
})()

LS.Maps.SchoolLayer = Class.create({
	initialize: function(leaid, year, points) {
		this.leaid = leaid;
		this.year = year;
		this.markers = [];
		for (i=0, len=points.length; i < len; ++i) {
			this._addpoint(points[i]);
		}
	},
	_addpoint: function(p) {
				// p = [id,lat,lng,icon]
				var layer = this;
				var m = new GMarker(new GLatLng(p[1],p[2]),{draggable:false,icon:LS.Maps.Icons[p[3]]});
				m.school_id = p[0];
			  this.markers.push(m);
	},
	overlays: function() { return this.markers;}
});

LS.Maps.RRLayer = Class.create({
	initialize: function(leaid, year, col) {
		this.leaid = leaid;
		this.year = year;
		this.col = col;
		this._tlos = [new GTileLayerOverlay(
			new GTileLayer(LS.Maps.CopyrightCollection, 0, 17, {
				isPng: false,
				opacity: 0.6,
				tileUrlTemplate:'/raw/mp/Tile/Image.png?x={X}&y={Y}&zoom={Z}&'+Object.toQueryString({
					d: this.leaid,
					yr: this.year,
					c: this.col,
					s: 'rr'
				})
			})
		)];
	},
	overlays: function() { return this._tlos;}
});

