var mapBounds = new GLatLngBounds(new GLatLng(40.038, -76.326123), new GLatLng(40.056, -76.313891));
var mapMinZoom = 15;
var mapMaxZoom = 19;
var startZoom = 16;
var opacity = 1;
var map;
var hybridOverlay;
var gmarkers = [];
var to_htmls = [];
var from_htmls = [];

var mapBounds1 = new GLatLngBounds(new GLatLng(40.038, -76.326123), new GLatLng(40.056, -76.313891));

var cent2 = new GLatLng(40.0444, -76.3138);
var zoom2 = 15;
var cent1 = new GLatLng(40.0484, -76.3183);
var zoom1 = 17;

function center1(){
	map.setCenter( cent1, zoom1 );
  
};
function center2(){
	map.setCenter( cent2, zoom2 );
  
};
var icon = new GIcon();
      icon.image = "http://web1.fandm.edu/campusmap/icons/marker_campus.png";
      icon.iconSize = new GSize(20, 34);
      icon.shadow = "http://maps.google.com/intl/en_us/mapfiles/shadow50.png";
      icon.shadowSize = new GSize(36, 34);
      icon.iconAnchor = new GPoint(10, 34);
      icon.infoWindowAnchor = new GPoint(10, 2);
      icon.imageMap=[9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0];
      
      var icon2 = new GIcon();
      	icon2.image = "http://web1.fandm.edu/campusmap/icons/square_dining.png";
      	icon2.iconSize = new GSize(35, 35);
      	icon2.shadow = "http://web1.fandm.edu/campusmap/icons/square_shadow.png";
      	icon2.shadowSize = new GSize(35, 52);
      	icon2.iconAnchor = new GPoint(17, 34);
      	icon2.infoWindowAnchor = new GPoint(17, 2);
      	icon2.imageMap=[9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0];

        var icon3 = new GIcon();
        	icon3.image = "http://web1.fandm.edu/campusmap/icons/square_lodging.png";
        	icon3.iconSize = new GSize(35, 35);
        	icon3.shadow = "http://web1.fandm.edu/campusmap/icons/square_shadow.png";
        	icon3.shadowSize = new GSize(35, 52);
        	icon3.iconAnchor = new GPoint(17, 34);
        	icon3.infoWindowAnchor = new GPoint(17, 2);
        	icon3.imageMap=[9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0];

/* [listing 6-15] */
var deselectCurrent = function() {};


function initializePoint(pointData) {
	var point = new GLatLng(pointData.latitude, pointData.longitude);

	var marker = new GMarker(point,icon);
	
	var listItem = document.createElement('li');
	var listItemLink = listItem.appendChild(document.createElement('a'));
	var visible = false;
	
	listItemLink.href = "#";
	if (pointData.code == "")
		listItemLink.innerHTML = "<strong>" + pointData.name + "</strong>";
	else
		listItemLink.innerHTML = "<strong>" + pointData.name + "</strong> " + pointData.code;
	
	var focusPoint = function() {
		deselectCurrent();
		listItem.className = 'current';
		deselectCurrent = function() { listItem.className = ''; }
		marker.openInfoWindowHtml("<strong>" + pointData.name + "</strong><br><em>" + pointData.address + "</em><br>" + pointData.departments);
		map.panTo(point);
		return false;
	}

	GEvent.addListener(marker, 'click', focusPoint);	
	listItemLink.onclick = focusPoint;

	pointData.show = function() {
		if (!visible) {
			document.getElementById('mapbar-list').appendChild(listItem);
			map.addOverlay(marker);
			visible = true;
		}
	}
	pointData.hide = function() {
		if (visible) {
			document.getElementById('mapbar-list').removeChild(listItem);
			map.removeOverlay(marker);
			visible = false;
		}
	}

//	pointData.show();
}
// functions that open the directions forms
function tohere(i) {
  gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}
function fromhere(i) {
  gmarkers[i].openInfoWindowHtml(from_htmls[i]);
}
function getDirections() {
  // ==== Set up the walk and avoid highways options ====
  var opts = {};
  if (document.getElementById("walk").checked) {
     opts.travelMode = G_TRAVEL_MODE_WALKING;
  }
  if (document.getElementById("highways").checked) {
     opts.avoidHighways = true;
  }
  // ==== set the start and end locations ====
  var saddr = document.getElementById("saddr").value
  var daddr = document.getElementById("daddr").value
  gdir.load("from: "+saddr+" to: "+daddr, opts);
}

function initializePoint2(pointData) {
	var point = new GLatLng(pointData.latitude, pointData.longitude);
	
	if (pointData.type == "Restaurants")
	  var marker = new GMarker(point,icon2);
	else
	  var marker = new GMarker(point,icon3);
	
	  var i = gmarkers.length;
  
	var listItem = document.createElement('li');
	var listItemLink = listItem.appendChild(document.createElement('a'));
	var visible = false;
	
	listItemLink.href = "#";
	if (pointData.cuisine == "")
		listItemLink.innerHTML = "<strong>" + pointData.name + "</strong>";
	else
		listItemLink.innerHTML = "<strong>" + pointData.name + "</strong> " + pointData.cuisine;
	
	var focusPoint = function() {
		deselectCurrent();
		listItem.className = 'current';
		deselectCurrent = function() { listItem.className = ''; }
		var thisString = "<strong>" + pointData.name + "</strong><br />";
  	if (pointData.cuisine != "") thisString = thisString + pointData.cuisine+ "<br />";
		thisString = thisString + "<em>" + pointData.location + "</em><br>" + pointData.phone + "<br><a href=\"" + pointData.url + "\">" + pointData.url + "</a>";
		//<br><br><a href=\"http://maps.google.com/maps?saddr=&daddr=" + pointData.location + "\">Get Directions</a>
    // The info window version with the "to here" form open
    to_htmls[i] = thisString + '<br>Directions: <b>To here<\/b> - <a href="javascript:fromhere(' + i + ')">From here<\/a>' +
       '<br>Start address:<form action="javascript:getDirections()">' +
       '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
       '<INPUT value="Get Directions" TYPE="SUBMIT"><br>' +
       'Walk <input type="checkbox" name="walk" id="walk" /> &nbsp; Avoid Highways <input type="checkbox" name="highways" id="highways" />' +
       '<input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + 
       '"/>';
    // The info window version with the "from here" form open
    from_htmls[i] = thisString + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here<\/a> - <b>From here<\/b>' +
       '<br>End address:<form action="javascript:getDirections()">' +
       '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
       '<INPUT value="Get Directions" TYPE="SUBMIT"><br>' +
       'Walk <input type="checkbox" name="walk" id="walk" /> &nbsp; Avoid Highways <input type="checkbox" name="highways" id="highways" />' +
       '<input type="hidden" id="saddr" value="'+name+"@"+ point.lat() + ',' + point.lng() +
       '"/>';
    // The inactive version of the direction info
		thisString = thisString + '<br>Directions: <a href="javascript:tohere('+i+')">To here<\/a> - <a href="javascript:fromhere('+i+')">From here<\/a>';
    		
		marker.openInfoWindowHtml(thisString);
		map.panTo(point);
		return false;
	}
	gmarkers.push(marker);
	GEvent.addListener(marker, 'click', focusPoint);	
	listItemLink.onclick = focusPoint;
	pointData.show = function() {
		if (!visible) {
			document.getElementById('mapbar-list').appendChild(listItem);
			map.addOverlay(marker);
			visible = true;
		}
	}
	pointData.hide = function() {
		if (visible) {
			document.getElementById('mapbar-list').removeChild(listItem);
			map.removeOverlay(marker);
			visible = false;
		}
	}
	pointData.show();
}

function initializeSortTab(type) {
	var listItem = document.createElement('li');
	var listItemLink = listItem.appendChild(document.createElement('a'));

	listItemLink.href = "#";
	listItemLink.innerHTML = type;
	listItemLink.onclick = function() {
		changeBodyClass('standby', 'loading');
		for(id in markers) {
			markers[id].hide();	
		}
		for(id in markers2) {
				markers2[id].hide();	
		}
		for(id in markers) {
			if (markers[id].type == type || 'All of Campus' == type)
				markers[id].show();
		}
		changeBodyClass('loading', 'standby');
		return false;
	}
	document.getElementById('filters').appendChild(listItem);
}
function initializeSortTab2(type) {
	var listItem = document.createElement('li');
	var listItemLink = listItem.appendChild(document.createElement('a'));

	listItemLink.href = "#";
	listItemLink.innerHTML = type;
	listItemLink.onclick = function() {
		changeBodyClass('standby', 'loading');
		for(id in markers) {
			markers[id].hide();	
		}
		for(id in markers2) {
				markers2[id].hide();	
		}
		for(id in markers2) {
			if (markers2[id].type == type || 'Everything' == type)
				markers2[id].show();
		}
		changeBodyClass('loading', 'standby');
		return false;
	}
	document.getElementById('filters2').appendChild(listItem);
}
function showNone() {
	for(id in markers2) {
			markers2[id].hide();	
	}
	for(id in markers) {
			markers[id].hide();
	}	
}
function showOne() {
  showNone();
	for(id in markers) {
			markers[id].show();
	}	
}
function showTwo() {
  showNone();
	for(id in markers2) {
			markers2[id].show();
	}	
}
function windowHeight() {
	if (self.innerHeight) return self.innerHeight;
	if (document.documentElement && document.documentElement.clientHeight) return document.documentElement.clientHeight;
	if (document.body) return document.body.clientHeight;
	return 0;
}

function handleResize() {
//	var height = windowHeight() - document.getElementById('toolbar').offsetHeight - 215;
	//document.getElementById('bd').style.height = height + 'px';
	// height = height - 25;
	//document.getElementById('map').style.height = height + 'px';
	//document.getElementById('mapbar').style.height = height + 'px';
}

function changeBodyClass(from, to) {
     document.body.className = document.body.className.replace(from, to);
     return false;
}

function init() {
	var type;
	var allTypes = { 'All of Campus':[] };
	var allTypes2 = { 'Everything':[] };
	document.getElementById('button-mapbar-hide').onclick = function() { return changeBodyClass('mapbar-right', 'nomapbar'); };
	document.getElementById('button-mapbar-show').onclick = function() { return changeBodyClass('nomapbar', 'mapbar-right'); };
	document.getElementById('navGuide').onclick = function() { 
    changeBodyClass('header1', 'header2');	 
    showTwo();
    center2();
	return true;
	  };
document.getElementById('navMap').onclick = function() { 
        changeBodyClass('header2', 'header1'); 
        showOne();
        center1();
        return true;
};

//	handleResize();
	
	map = new GMap2( document.getElementById("map"), { backgroundColor: '#fff' } );

	map.addMapType(G_PHYSICAL_MAP);
	map.setMapType(G_PHYSICAL_MAP);

  center2();
  gdir=new GDirections(map, document.getElementById("mapbar-dir"));

	hybridOverlay = new GTileLayerOverlay( G_HYBRID_MAP.getTileLayers()[1] );
	
	GEvent.addListener(map, "maptypechanged", function() {
	  if (map.getCurrentMapType() == G_HYBRID_MAP) {
        map.addOverlay(hybridOverlay);
	  } else  if (map.getCurrentMapType() == G_PHYSICAL_MAP) {
        map.addOverlay(overlay);
  	  } else {
	    map.removeOverlay(overlay);
  	   map.removeOverlay(hybridOverlay);
	  }
    
	} );
	
  reasons=[];
  reasons[G_GEO_SUCCESS]            = "Success";
  reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
  reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
  reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
  reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
  reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
  reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
  reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
  reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
  reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";

  GEvent.addListener(gdir, "error", function() {
    var code = gdir.getStatus().code;
    var reason="Code "+code;
    if (reasons[code]) {
      reason = reasons[code]
    } 

    alert("Failed to obtain directions, "+reason);

  });
  
  GEvent.addListener(gdir, "load", onGDirectionsLoad);
  
  function onGDirectionsLoad(){
    // map.addOverlay(gdir.getPolyline());
    map.closeInfoWindow();
    showNone();
    changeBodyClass('search', 'directions');
		
  }

	var tilelayer = new GTileLayer(GCopyrightCollection(''), mapMinZoom, mapMaxZoom);
	var mercator = new GMercatorProjection(mapMaxZoom+1);
	tilelayer.getTileUrl = function(tile,zoom) {
	    if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
	        return "http://www.maptiler.org/img/none.png";
	    } 
	    var ymax = 1 << zoom;
	    var y = ymax - tile.y -1;
	    var tileBounds = new GLatLngBounds(
	        mercator.fromPixelToLatLng( new GPoint( (tile.x)*256, (tile.y+1)*256 ) , zoom ),
	        mercator.fromPixelToLatLng( new GPoint( (tile.x+1)*256, (tile.y)*256 ) , zoom )
	    );
	    if (mapBounds.intersects(tileBounds)) {
	        return zoom+"/"+tile.x+"/"+y+".png";
	    } else {
	        return "http://www.maptiler.org/img/none.png";
	    }
	}
	// IE 7-: support for PNG alpha channel
	// Unfortunately, the opacity for whole overlay is then not changeable, either or...
	tilelayer.isPng = function() { return true;};
	tilelayer.getOpacity = function() { return opacity; }

	overlay = new GTileLayerOverlay( tilelayer );
	map.addOverlay(overlay);

	map.addControl(new GLargeMapControl());
	map.addControl(new GHierarchicalMapTypeControl());
		
	map.enableContinuousZoom();
	map.enableScrollWheelZoom();

	map.setMapType(G_HYBRID_MAP);
	
	for(id in markers) {
		initializePoint(markers[id]);
		allTypes[markers[id].type] = false;
	}
	for(id in markers2) {
		initializePoint2(markers2[id]);
		allTypes2[markers2[id].type] = true;
	}

	for(type in allTypes) {
		initializeSortTab(type);
	}
	for(type in allTypes2) {
		initializeSortTab2(type);
	}
	

}

window.onresize = handleResize;
window.onload = init;
