
var synbio = {

	map: null,
	markers: null,
	geocoder: null,

	gotoAddress: function(address) {
		synbio.geocoder.getLatLng(address, function(point) {
			if(!point) alert("Unable to locate address"); 
				else synbio.map.setCenter(point, 10); 
		});
	},

	addItem: function(item) {

		var icon = new GIcon();
		icon.image = "http://www.synbioproject.org" + item.cat.icon; 
		icon.iconSize = new GSize(32, 34);
		icon.iconAnchor = new GPoint(16, 17); 
		icon.infoWindowAnchor = new GPoint(16,17); 
		icon.shadow = "http://www.synbioproject.org/process/templates/styles/images/map_icon_shadow.png";
		icon.shadowSize = new GSize(50, 34); 

		var marker = new GMarker(new GLatLng(item.lat, item.lng), icon); 
		var html = "<strong><a target='_blank' href='" + item.url + "'>" + item.name + "</a></strong><br />Category: " + item.cat.name;

		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowHtml(html); 
		}); 

		synbio.map.addOverlay(marker); 
		synbio.markers[item.cat.id][item.id] = marker;
	},


	loadMap: function() {

		synbio.geocoder = new GClientGeocoder();
		synbio.geocoder.setCache = null;

		synbio.map = new GMap2(document.getElementById("map"));
		synbio.map.addControl(new GLargeMapControl());
		synbio.map.addControl(new GMapTypeControl());
		//synbio.map.setMapType(G_HYBRID_MAP); 

		synbio.markers = new Array(); 
			
		var zl = 3;
		synbio.map.setCenter(new GLatLng(38.896809,-50.00),zl);

		$.getJSON("http://www.synbioproject.org/library/inventories/map/json/", {'r': 'y'}, function(data, textStatus) {
			$.each(data.categories, function(c, cat) {
				synbio.markers[cat.id] = new Array(); 
			}); 
			$.each(data.items, function(i, item) {
				$.each(data.categories, function(c, cat) {
					if(cat.id == item.cat_id) item.cat = cat;	
				}); 
				synbio.addItem(item); 
			}); 
		}); 
	}, 

	init: function() {

		synbio.loadMap();
		
		$("#submit_address").click(function() {
			var address = $("#address").val();
			if(address.length) synbio.gotoAddress(address);
			return false; 
		}); 

		$("#category_checkboxes input").click(function() {
			for(cat_id in synbio.markers) {
				if(cat_id == $(this).val()) {
					for(m in synbio.markers[cat_id]) {
						marker = synbio.markers[cat_id][m];
						if($(this).is(":checked")) marker.show();
							else marker.hide();
					}
				}
			}
		}); 
		
	}
}

$(document).ready(function() {
	synbio.init();
}); 


