// JavaScript Document

// STUFF 
	var map;
	var directions;
	var directionsRequestSource;
	var locations = new Array();
	var watersheds = new Array();
	var waterfronts = new Array();
	var trcaActivities = new Array();
	var displayWatershedBoundries = false;
	var displayLakeOntarioWaterfrontInterestPoints = false;
// ACTIVITIES
	function trcaActivity(name, icon, link) {
		this.name = name;
		this.icon = icon;
		this.link = link;
	}
	trcaActivity.prototype.display = function() {
		return "<a href='" + this.link + "' title ='" + this.name + "'><img alt='" + this.name + "' src='" + this.icon + "' width='30' height='30'/></a>";
	}
	// DO NOT CHANGE ORDER
	trcaActivities[0] = new trcaActivity(    "Birdwatching", "http://www.trca.on.ca/global/images/activityIcons/bird_watching.png", "/enjoy/activities/bird-watching.dot");
	trcaActivities[1] = new trcaActivity(    "Camping",    "http://www.trca.on.ca/global/images/activityIcons/camping.png",    "/enjoy/activities/camping.dot");
	trcaActivities[2] = new trcaActivity(    "Canoeing / Paddling",    "http://www.trca.on.ca/global/images/activityIcons/canoeing.png",    "/enjoy/activities/canoeing-paddling.dot");
	trcaActivities[3] = new trcaActivity(    "Cross-country Skiing",    "http://www.trca.on.ca/global/images/activityIcons/x_country_skiing.png",    "/enjoy/activities/cross-country-skiing.dot");
	trcaActivities[4] = new trcaActivity(    "Fishing",    "http://www.trca.on.ca/global/images/activityIcons/fishing.png",    "/enjoy/activities/fishing.dot");
	trcaActivities[5] = new trcaActivity(    "Fly-Fishing",    "http://www.trca.on.ca/global/images/activityIcons/fly_fishing.png",    "/enjoy/activities/fly-fishing.dot");
	trcaActivities[6] = new trcaActivity(    "Golfing",    "http://www.trca.on.ca/global/images/activityIcons/golfing.png",    "/enjoy/activities/golfing.dot");
	trcaActivities[7] = new trcaActivity(    "Hiking",    "http://www.trca.on.ca/global/images/activityIcons/hiking.png",    "/enjoy/activities/hiking.dot");
	trcaActivities[8] = new trcaActivity(    "Historic Sight-Seeing",    "http://www.trca.on.ca/global/images/activityIcons/historic_site_seeing.png",    "/enjoy/activities/historic-sight-seeing.dot");
	trcaActivities[9] = new trcaActivity(    "Mountain Biking",    "http://www.trca.on.ca/global/images/activityIcons/mountain_biking.png",    "/enjoy/activities/mountain-biking.dot");
	trcaActivities[10] = new trcaActivity(    "Picnics",    "http://www.trca.on.ca/global/images/activityIcons/picnics.png",    "/enjoy/activities/picnics.dot");
	trcaActivities[11] = new trcaActivity(    "Playgrounds",    "http://www.trca.on.ca/global/images/activityIcons/playgrounds.png",    "/enjoy/activities/playgrounds.dot");
	trcaActivities[12] = new trcaActivity(    "Maple Syrup Festival",    "http://www.trca.on.ca/global/images/activityIcons/maple_syrup_festival.png",    "/enjoy/activities/maple-syrup-festival.dot");
	trcaActivities[13] = new trcaActivity(    "Swimming",    "http://www.trca.on.ca/global/images/activityIcons/swimming.png",    "/enjoy/activities/swimming.dot");
	trcaActivities[14] = new trcaActivity(    "Dog Walking",    "http://www.trca.on.ca/global/images/activityIcons/dog_walking.png",    "/enjoy/activities/dog-walking.dot");
        trcaActivities[15] = new trcaActivity(    "Horse Back Riding",    "http://www.trca.on.ca/global/images/activityIcons/horseback.png",    "/enjoy/activities/horse-back-riding.dot");

// LOCATIONS
	function trcaLocation(name, link, address, phone, logo, latitude, longitude, activities, iconImg) {
		this.name = name;
		this.link = link;
		this.address = address;
		this.phone = phone;
		this.logo = logo;
		this.activities = activities;
		this.iconImg = iconImg;
		this.point = new GLatLng(latitude, longitude);
		// create the marker
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		var locationIcon = new GIcon(baseIcon);
		locationIcon.image = this.iconImg;
		var markerOptions = {
				title: name,
				icon :locationIcon
		};
		this.marker = new GMarker(this.point, markerOptions);
		// About Info Tab
		var info = "<div class='aboutTab'>";
		if(this.logo != '') {
			if(this.link !='') {
				info = info + "<a href='"+this.link+"' title='Find out more'><img class='logo' alt='Logo image' src='"+ this.logo + "' alt='logo'/></a>";
			} else {
				info = info + "<img class='logo' alt='Logo image' src='"+ this.logo + "' alt='logo'/>";
			} 
		}
		info = info + "<div class='locationInfo'><h3>";
		if(this.link !='') {
			info = info + "<a href='"+this.link+"' title='Find out more'>"+this.name+"</a>";
		} else {
			info = info + this.name;
		} 
		info = info + "</h3>" + this.address + "<br/>" + this.phone 
					+ "</div><div class='activities'>";
		for ( var j = 0; j < this.activities.length; j++) {
			info = info + this.activities[j].display();
		}
		info = info +"</div></div>"
		// Direction Info Tab
		var directionsTab = '<div id="directionsTab_embedded" class="directionsTab">'
				+ '<div><label>To:</label>' + this.name +'</div>'
				+ '<label for="saddr_embed">Start Address:</label>'
				+ '<div class="saddrContainer">'
				+ '<input type="text" value="" id="saddr_embed" name="saddr" onKeyPress="if (event.keyCode == 13 || event.which == 13) { showRoute(\'#directionsTab_embedded\'); }" />'
				+ '<div class="help">Address, City, Province, Postal Code</div>'
				+ '</div>'
				+ '<div class="clear"></div>'
				+ '<input type="hidden" value="' + this.address + '" id="daddr_embed" name="daddr"/>'
				+ '<input class="button" type="button" value="Get Directions" onclick="showRoute(\'#directionsTab_embedded\')"/>'
				+ '</div>';
		if (this.address.length==0)
    		this.infoTabs = [ new GInfoWindowTab("About", info) ];
    	else
	    	this.infoTabs = [ new GInfoWindowTab("About", info),new GInfoWindowTab("Directions", directionsTab) ];
		// bind events to open info tabs
		GEvent.bind(this.marker, "click", this, this.openInfoTabs);
		
		// duplicate directions box outside of canvas
		if (locations.length < 1 && this.address.length > 0) {
  		$("#map_canvas").before('<div id="directionsTab_above" class="directionsTab">'
  				+ '<div><label>To:</label>' + this.name +'</div>'
  				+ '<label for="saddr_top">Start Address:</label>'
  				+ '<div class="saddrContainer">'
  				+ '<input type="text" value="" id="saddr_top" name="saddr" onKeyPress="if (event.keyCode == 13 || event.which == 13) { showRoute(\'#directionsTab_above\'); }" />'
  				+ '<div class="help">Address, City, Province, Postal Code</div>'
  				+ '</div>'
  				+ '<div class="clear"></div>'
  				+ '<input type="hidden" value="' + this.address + '" id="daddr_top" name="daddr"/>'
  				+ '<input class="button" type="button" value="Get Directions" onclick="showRoute(\'#directionsTab_above\')"/>'
  				+ '</div><p></p>');
  		} else {
  		  $("#directionsTab_above").hide();
  		}
	}
	trcaLocation.prototype.openInfoTabs = function() {
		this.marker.openInfoWindowTabsHtml(this.infoTabs); 

	}
// DIRECTIONS
	function showRoute(src) {
	  directionsRequestSource = src;
		var start = $(src + " input[name=saddr]").val();
		var destination = $(src + " input[name=daddr]").val();
		directions.load("from: " + start + " to: " + destination);
	}
	function handleDirectionsErrors() {
		if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
			alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect. Error code: "			+ directions.getStatus().code);
		} else if (directions.getStatus().code == G_GEO_SERVER_ERROR) {
			alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known. Error code: "+ directions.getStatus().code);
		} else if (directions.getStatus().code == G_GEO_MISSING_QUERY) {
			alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input. Error code: "		+ directions.getStatus().code);
		} else if (directions.getStatus().code == G_GEO_BAD_KEY) {
			alert("The given key is either invalid or does not match the domain for which it was given. Error code: "+ directions.getStatus().code);
		} else if (directions.getStatus().code == G_GEO_BAD_REQUEST) {
			alert("A directions request could not be successfully parsed. Error code: "+ directions.getStatus().code);
		} else {
			alert("An unknown error occurred.");
		}
	}
	function handleDirectionsLoad() {
		$(directionsRequestSource + " input[name=saddr]").attr('value','');
		$('#clearDirections').show();
	}
// WATERSHEDS
	function watershed(id, name) {
		this.name = name;
		this.id = id;
		this.control = '#'+id;
		this.overlay = null; // IE seems to get errors if we try loading all overlays at once so only load it when we need it
		this.active = false;
		this.clicked = false;
	}
	watershed.prototype.attachControl = function() {
		$(this.control).bind("click", {watershed: this}, clickWatershedHandler);
		$(this.control).bind("mouseenter", {watershed: this}, mouseenterWatershedHandler);
		$(this.control).bind("mouseleave", {watershed: this}, mouseleaveWatershedHandler);
	}
	watershed.prototype.getOverlay = function() {
		if(this.overlay == null) {
			this.overlay = new GGeoXml('http://216.86.157.96/global/kml/4/'+this.id+'.kml' );
		}
		return this.overlay;
	}
	function clickWatershedHandler(event) {
		event.data.watershed.clicked = !event.data.watershed.clicked;
		if(event.data.watershed.clicked) {
			showWatershed(event.data.watershed);
		} else {
			hideWatershed(event.data.watershed);
		}
		return false;
	}
	function mouseenterWatershedHandler(event) {
		if(!event.data.watershed.active) {
			showWatershed(event.data.watershed);
		}
	}
	function mouseleaveWatershedHandler(event) {
		if(!event.data.watershed.clicked) {
			hideWatershed(event.data.watershed);
		}
	}
	function showWatershed(watershed) {
		$(watershed.control).addClass('active');
		map.addOverlay(watershed.getOverlay());
		watershed.active = true;
	}
	function hideWatershed(watershed) {
		$(watershed.control).removeClass('active');
		map.removeOverlay(watershed.getOverlay());
		watershed.active = false;
	}	

// WATERFRONTS
	function waterfront(id, name, latitude, longitude, zoom_inc) {
		this.name = name;
		this.id = id;
		this.control = '#'+id;
		this.overlay = null; // IE seems to get errors if we try loading all overlays at once so only load it when we need it
		this.kmlurl = null;
		this.active = false;
		this.clicked = false;
		this.latitude = latitude;
		this.longitude = longitude;
		this.zoom_inc = zoom_inc; // how much to increment the default zoom by
	}
	waterfront.prototype.attachControl = function() {
		$(this.control).bind("click", {waterfront: this}, clickWaterfrontHandler);
		$(this.control).bind("mouseenter", {waterfront: this}, mouseenterWaterfrontHandler);
		$(this.control).bind("mouseleave", {waterfront: this}, mouseleaveWaterfrontHandler);
	}
	waterfront.prototype.getKmlUrl = function() {
	  if(this.kmlurl == null) {
		  if (this.id == "etobicoke-waterfront") {
		    this.kmlurl = 'http://www.trca.on.ca/global/kml/EtobicokeSector_Bnd.kml';
		  } else if (this.id == "central") {
		    this.kmlurl = 'http://www.trca.on.ca/global/kml/CentralWaterfrontSector.kml';
		  } else if (this.id == "scarborough") {
		    this.kmlurl = 'http://www.trca.on.ca/global/kml/ScarboroughSector.kml';
		  } else if (this.id == "pickering") {
		    this.kmlurl = 'http://www.trca.on.ca/global/kml/Pickering_AjaxSector.kml';
		  }
		}
		return this.kmlurl;
	}
	waterfront.prototype.zoomToCenter = function() {
    var centerPoint = new GLatLng(this.latitude, this.longitude);
    // alert(map.getCenter().lat() + " " + map.getCenter().lng())
    map.setCenter(centerPoint, startZoomLevel + this.zoom_inc);
	}
	waterfront.prototype.getOverlay = function() {
		if(this.overlay == null) {
      // if (this.id == "etobicoke-waterfront") {
      //   this.overlay = new GGeoXml('http://www.trca.on.ca/global/kml/7/EtobicokeSector_Bnd.kml' );
      // } else if (this.id == "central") {
      //   this.overlay = new GGeoXml('http://www.trca.on.ca/global/kml/7/CentralWaterfrontSector.kml' );        
      // } else if (this.id == "scarborough") {
      //   this.overlay = new GGeoXml('http://www.trca.on.ca/global/kml/7/ScarboroughSector.kml' );
      // } else if (this.id == "pickering") {
      //   this.overlay = new GGeoXml('http://www.trca.on.ca/global/kml/7/Pickering_AjaxSector.kml' );
      // }
	    this.overlay = new GGeoXml(this.getKmlUrl());
		}
		return this.overlay;
	}	
	function clickWaterfrontHandler(event) {
		event.data.waterfront.clicked = !event.data.waterfront.clicked;
		if(event.data.waterfront.clicked) {
			showWaterfront(event.data.waterfront);
		} else {
			hideWaterfront(event.data.waterfront);
		}
		return false;
	}
	function mouseenterWaterfrontHandler(event) {
		showWaterfront(event.data.waterfront);
	}
	function mouseleaveWaterfrontHandler(event) {
		if(!event.data.waterfront.clicked) {
			hideWaterfront(event.data.waterfront);
		}
	}
	function showWaterfront(waterfront) {
		$(waterfront.control).addClass('active');
		map.addOverlay(waterfront.getOverlay());
		waterfront.zoomToCenter();
		waterfront.active = true;
	}
	function hideWaterfront(waterfront) {
		$(waterfront.control).removeClass('active');
		map.removeOverlay(waterfront.getOverlay());
		waterfront.active = false;
	}


// INITIALIZE	 
	function initialize() {
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("map_canvas"));
			directions = new GDirections(map, document.getElementById("route"));
			directionsRequestSource = "#directionsTab_embedded";
			$('#clearDirections').click(function() {
				directions.clear();
				$(this).hide();
			});
			GEvent.addListener(directions, "error", handleDirectionsErrors);
			GEvent.addListener(directions, "load", handleDirectionsLoad);
			var mapControl = new GMapTypeControl();
			map.addControl(mapControl);
			map.addControl(new GLargeMapControl());
			var centerPoint = new GLatLng(defaultCenterLatitude, defaultCenterLongitude);
			map.setCenter(centerPoint, startZoomLevel);
					
			for(var wi=0; wi<watersheds.length; wi++) {
				$('#mapControls').append('<a href="#" id="'+watersheds[wi].id+'">'+watersheds[wi].name+'</a>');
				watersheds[wi].attachControl()
			}

			for(var wi=0; wi<waterfronts.length; wi++) {
				$('#mapControls').append('<a href="#" id="'+waterfronts[wi].id+'">'+waterfronts[wi].name+'</a>');
				waterfronts[wi].attachControl();
			}

			if(locations.length > 0) {
				$('#mapControls').append('<select id="locationControls" name="locations"><option value="-1" id="showMe">Show me ...</option></select>');
				for(var li=0; li<locations.length; li++) {
					$('#locationControls').append('<option value="'+li+'">'+locations[li].name+'</option>');
					map.addOverlay(locations[li].marker);
				}
				$('#locationControls').change(function() {
					var index = $(this).children('option:selected').attr('value');
					if( index>= 0) {
						locations[index].openInfoTabs();
					}
					$(this).children('option:selected').attr('selected', '');
					$(this).children('#showMe').attr('selected', 'selected');
				});
				if (locations.length == 1) {
					map.setCenter(locations[0].point, 9, G_HYBRID_MAP);
				}
			}
			if(displayWatershedBoundries) {
				map.addOverlay(new GGeoXml('http://www.trca.on.ca/global/kml/7/watersheds.kml' ));
			}	
			if(displayLakeOntarioWaterfrontInterestPoints){
				map.addOverlay(new GGeoXml('http://www.trca.on.ca/global/kml/7/TRCAPts.kml' ));
			}
			if(displayLakeOntarioWaterfrontBoundaries){
			  // replace boundaries with KML containing black borders of regions
        // map.addOverlay(new GGeoXml('http://trca.on.ca/global/kml/7/CentralWaterfrontSector.kml' ));
        // map.addOverlay(new GGeoXml('http://trca.on.ca/global/kml/7/EtobicokeSector_Bnd.kml' ));
        // map.addOverlay(new GGeoXml('http://trca.on.ca/global/kml/7/Pickering_AjaxSector.kml' ));
        // map.addOverlay(new GGeoXml('http://trca.on.ca/global/kml/7/ScarboroughSector.kml' ));
			}
                        		
			if(watersheds.length > 0){
				$('#mapControls a').click(function() {
					return false;
				});
				$('#mapControls').append('<div id="mapInstructions">* Mouse over a watershed to see it on the map, click a watershed to keep it on the map.</div>');
			}
			
			if(waterfronts.length > 0){
				$('#mapControls a').click(function() {
					return false;
				});
				$('#mapControls').append('<div id="mapInstructions">* Mouse over a waterfront sector to see it on the map, click a waterfront sector to keep it on the map.</div>');
			}
		}
	}

