// This is Matt's javascript hack using the google maps API
// It basically reads a data file and uses the info to plot points
// and add a descriptive box for each point.
// Each point can have multiple categories which you can filter off.
// 
    var sortedCat;
    var map;
    var qString;

    
// For some reason, I'm using this to clear the categories. That should change
  function sortCat(newCat){
      	//alert("map map is " + map);
      	//alert("category is " + newCat);
      	sortedCat = newCat;
      	initMap();
    }


// Start things off the default map settings. Just nulls out all the relevant variables and objects
  function resetMap(){
    	map = undefined;
    	sortedCat = null;
    	initMap();
    }
/*
  Invoked if someone is coming to a fresh page
  determines if it's a query string based load
  or a fresh load. It also creates the sidebar on the fly
*/
  function load() { 
  	makeSidebar();
  	if(window.location.search.substring(1)){
  		makeQueryMap();
  	}else{
  		initMap();
  	}
    }
/*
  If someone has a permalink they want and are loading things, this 
  will be invoked by load(), parse the query string, get the relevent 
  parameters and treat it like a newLoc()
  Once I have the filters in the URL, I'll need to deal with those too
*/
  function makeQueryMap(){
  	qString = window.location.search.substring(1);
  	var qsArray = new Array();
  	var params = qString.split('&');
	for (var i=0; i<params.length; i++) {
		var pos = params[i].indexOf('=');
		if (pos > 0) {
			var key = params[i].substring(0,pos);
			var val = params[i].substring(pos+1);
			qsArray[key] = val;
//			alert("key is " + key + " and val is " + val);
		}
	}
	//alert("lat " + qsArray['lat'] + " lng " + qsArray['lng'] + " zoom " + qsArray['zoom'] + " type " + qsArray['mtype']);
	if(parseFloat(qsArray['lat'])){
		newLoc(parseFloat(qsArray['lat']),parseFloat(qsArray['lng']),parseFloat(qsArray['zoom']),parseFloat(qsArray['mType']));
	}else if(qsArray['city']){
		loadPreDefinedLoc(qsArray['city']);
	}else{
		initMap();
	}
	
  }

   function loadPreDefinedLoc(c){
	city = c;
//	alert("City is " + city);
	var titleTxt;
	var locLng = null;
	var locLat = null;
	var locName = null;
	var locZoom = null;
	var locType = null;

	GDownloadUrl("locationData.xml", function(data) {
		var xml = GXml.parse(data);
		var locations = xml.documentElement.getElementsByTagName("location");
		var layer = document.getElementById('pageTitle');
		for (var i = 0; i < locations.length; i++) {
			if(locations[i].getAttribute("name") == city){
				alert ("found " + city + " and assigning " + locations[i].getAttribute("name"));
				locName = parseFloat(locations[i].getAttribute("name"));
				locLng = parseFloat(locations[i].getAttribute("lng"));
				locLat = parseFloat(locations[i].getAttribute("lat"));
				locZoom = parseFloat(locations[i].getAttribute("zoom"));
				locType = parseFloat(locations[i].getAttribute("mType"));
			}	
		}
//		alert("In gdu: " + locType + "-" + locZoom + "-" + locLat + "-" + locLng + "-" + locName);
		titleTxt = locName + " in Map Form<p>\n";
		layer.innerHTML = titleTxt;
	});
	alert (locLat);
//	alert("Out of gdu: " + locType + "-" + locZoom + "-" + locLat + "-" + locLng + "-" + locName);
	newLoc(locLat,locLng,locZoom,locType);
  
   }
  
  
/*
	Gets the lat, lng, zoom level and map type (really only
	hybrid or map -- no satellite at the moment) and creates a URL
	passing this info in the query string
	Next up, making an array of the filters so you can keep the filter type too
*/

  function createLink(){
    	var lat = map.getCenter().lat();
  	var lng = map.getCenter().lng();
  	var zooml = map.getZoom();
  	var mapType;
  	var url = "http://badanes.com/map/index.html?";
  	if(map.getCurrentMapType() == map.getMapTypes()[2]){
  		mapType = 1;
  	}else{
  		mapType = 0;
  	}
  	url = url + "lat="+lat+"&lng="+lng+"&zoom="+zooml+"&mType="+mapType;
  	//alert("lat is " + lat + " lng is " + lng + " and zoom is " + zooml + " map type is " + mapType);
  	//alert(url);
  	window.location=url;
  	
  
  }

  function getCenterCoord(){
	var lat = map.getCenter().lat();
	var lng = map.getCenter().lng();
	alert("The first data bit is:\n<marker lat=\"" + lat + "\" lng=\"" + lng + "\"");

  }
/*
  Now that I've branched out of a single central point, I needed a way to 
  move from one center to another. This basically resets the map and, based
  on the new center, zoom level provided, it redraws the map in the new place
  and loads the markers again.
  Another new addition: the ability to have the location as a hybrid map
  Right now, assumes no filters (in fact, it clears them). If coming from a permalink
  this will need to be dealt with
*/
  function newLoc(a,b,c,d){
  	//alert(a + b + c + d);
  	var lat = a;
  	var lng = b
  	var zoom = c;
  	var maptype = d;
//  	alert(lat + "   " + lng + "   " + zoom + "   " + maptype);
  	sortedCat=null;
  	map = null;
	map = new GMap2(document.getElementById("map"));
	//map.addMapType("G_HYBRID_MAP");
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());

	map.setCenter(new GLatLng(lat, lng), zoom);
	if(maptype){
			map.setMapType(G_HYBRID_MAP);
	}
	//alert(map.getCurrentMapType().toString());
	createMapAll(map);
  }
	
  	

// Creates list of categories to filter off of from checkbox form on web page. 
// It's a | delimited string to be split in a later function.
// Once the filters are created, it makes the map.

    function initFilter(){

    	//alert("length is " + document.filters.category.length);
		sortedCat = "";
    	for(var i = 0; i < document.filters.category.length; i++){
			if(document.filters.category[i].checked){
				sortedCat += document.filters.category[i].value + "|";
			}
    	}
    	//alert("we'd be searching for " + sortedCat);
    	initMap();
    }

// All functions enter this function at some point.
// If the page has already loaded, the map doesn't refresh. At this point, this will happen if someone
// wants to manipulate the filters, so the existing markers (overlays) are cleared so the newly relevant ones 
// can be placed
// If it's a fresh map, it creates a new map object based on a central point of my choosing
// After that, it's time to go into the data file and build the points
	function initMap(){
    		if(map){
    			var center = map.getCenter();
    			map.clearOverlays();
    			//alert("Center is " + center);
    		}else{
    			//alert("Fresh new map");
    			map = new GMap2(document.getElementById("map"));
	        	map.addControl(new GSmallMapControl());
	        	map.addControl(new GMapTypeControl());
	        	map.setCenter(new GLatLng(51.549965, -0.0895), 12);
	        }
	        createMapAll(map);
	}
/*
  Previously, the sidebar was completely static. This function will now generate the
  sidebar on the initial load. Currently, the only dynamic piece is the categories.
  The rest is static. The static shite should be in a static file of sorts. Not hardcoded
*/
	function makeSidebar(){
		GDownloadUrl("catData.xml", function(data) {
		var xml = GXml.parse(data);
		var categories = xml.documentElement.getElementsByTagName("category");
		//alert("sidebar!");
		var layer = document.getElementById('sidebar');
		var sidebarTxt = "\t\t\t\tFilters:<br>\n\t\t\t<form name=\"filters\">\n";
		for (var i = 0; i < categories.length; i++) {
			var catName = categories[i].getAttribute("categoryName");
			var catDisplay = categories[i].getAttribute("categoryDisplay");
			sidebarTxt += "\t\t\t\t<input type=checkbox name=\"category\" value=\"" + catName + "\">"  + catDisplay + "<br>\n";
		}
		sidebarTxt += '\n\t\t\t\t<input type=button value="Filter" onClick="initFilter();"><br>\n\t\t\t\t</form>\n\t\t\t\n<p>\n\t\t\t\t<li><a href="javascript:sortCat(null);">Clear Filters</a>\n\t\t\t\t\n<li><a href="javascript:resetMap();">Reset Map</a>\n\t\t\t\t<p>\n\t\t\t\tOther Locations:\n\t\t\t\t<br>\n\t\t\t\t<li><a href="javascript:newLoc(50.829903,-0.152264, 14, 0)">Brighton</a>\n\t\t\t\t<li><a href="javascript:newLoc(51.549965, -0.0895, 12, 0)">London</a>\n\t\t\t\t<li><a href="javascript:newLoc(51.248942, 0.629675, 16,1)">Leeds Castle</a>\n\t\t\t\t<li><a href="javascript:newLoc(59.324433,18.091564, 14, 1)">Stockholm</a>\n\t\t\t\t<li><a href="javascript:newLoc(41.94519164538106,-87.65338897705078, 12, 0)">Chicago</a>\n<br><font size=1>(In Progress!!)</font>\n\t\t\t\t<p><font size=1>(Make sure you zoom and move around some)</font>\n\t\t\t\t<br><a href="javascript:createLink()">PermaLink</a><p>\n\t\t\t\t<li><a href="javascript:helpWindow(\'mapHelp.html\',\'Help\');">Confused??</a>\n\t\t\t\t<p><font color="#FFFFFF"><a href="javascript:getCenterCoord()">Center Coordinates</a></font>\n'; 
		layer.innerHTML = sidebarTxt;
		
		});
			
	}

/*
  Not really creating the map. It's creating the points based on the data file.
  I really want to get a lot of this shit out of the GDownloadURL struct.
  Two things are happening here:
  	1) It loads the data file and puts the data in the relevant variable value
  	2) If someone is filtering, then it'll search in the category value for the filter(s)
  Besides that, it puts down markers on the map based on filter criteria
*/ 
	function createMapAll(map){
		if (GBrowserIsCompatible()) {

		var category,point,locName,imgName,desc,blogLink,iheight,iwidth,clickText;

		GDownloadUrl("mapData.xml", function(data) {
			var xml = GXml.parse(data);
			
			var markers = xml.documentElement.getElementsByTagName("marker");
			for (var i = 0; i < markers.length; i++) {

				point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
									parseFloat(markers[i].getAttribute("lng")));
				locName = markers[i].getAttribute("locName");
				imgName = markers[i].getAttribute("imgName");
				category = markers[i].getAttribute("category");
				desc = markers[i].getAttribute("desc");
				blogLink = markers[i].getAttribute("blogLink");
				iheight = parseFloat(markers[i].getAttribute("iheight"));
				iwidth = parseFloat(markers[i].getAttribute("iwidth"));
				clickText = createClickText(locName,imgName,category,desc,blogLink,iheight,iwidth);
				//alert("sorted search = " + sortedCat);
	          	
	          	if(sortedCat){
	          		var catGroup = sortedCat.split("|");
	          		//alert(catGroup.length);
	          		//alert("1st entry is " + catGroup[0]);
	          		for(var j = 0; j < catGroup.length-1; j++){
	          			var searchFor = new RegExp(catGroup[j]);
						//alert("search for " + searchFor);
	          			var found = searchFor.exec(category);
	          			if(found){
	          				//alert(found);
	          				map.addOverlay(createMarker(point,clickText));
	          			}
	          		}
	          	}else{
	          		map.addOverlay(createMarker(point,clickText));
	          	}
	          }
		});
/* 
  This gets called for each entry in the data file (it should only be for the entries that'll end up as markers)
  Based on the info provided it:
  	1) Checks to see if there is an image for the entry. If not, it puts a default image in its place
  	2) Formats the text based on whether or not there's an associated blog link for that entry
  	3) Puts it altogether to be stuck in the marker's info box.
  Formatting of the info box (as of today):
  	Title
  	Img
  	Description
  	Link to Blog (if necessary)  
*/
        function createClickText(locName,imgName,category,desc,blogLink,iheight,iwidth){
          		var descTxt,clickTxt;
          		if(!imgName){
          			imgName =  "noImage.jpg";
          			iwidth = 200;
          			iheight = 150;
          		}
          		if(blogLink){
          			descTxt = desc + "<br><a href=\"" + blogLink + "\" target=\"_new\">View Writeup</a>";
          		}else{
          			descTxt = desc;
          		}
			clickTxt = "<div STYLE=\"width:200px\"><b>" + locName + "</b><br><img src=\"img/" + imgName + "\" height=" + iheight + " width=" + iwidth + " border=0><br>" + descTxt + "</div>";
          		return clickTxt;
          }
/*
  Makes an Info Window for each marker on the map
*/
          function createMarker(point, clickText){
          	//var baseIcon = new GIcon();
		//baseIcon.iconSize = new GSize(12, 20);
		//baseIcon.image = "http://labs.google.com/ridefinder/images/mm_20_black.png";
		//baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		//baseIcon.shadowSize= new GSize(20, 34);
		//baseIcon.iconAnchor = new GPoint(9, 34);
          	var marker = new GMarker(point); //, baseIcon);
          	GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml(clickText);
		});
			return marker;
		}
      }

    }

// Not sure why, but i added a help window. This opens it. fun fun
	function helpWindow(url, name){
		window.open(url, name,'width=200,height=300,resizeable=yes,scrollbars=yes');
	}

