//global variable declarations, arrays are to track drawing and removal of overlays
var map;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var markersArray = [];
var plinesArray = [];

//basic map initialization - api version 3
function initialize() {
		directionsDisplay = new google.maps.DirectionsRenderer();
		var mapcenter = new google.maps.LatLng(40.000000,-75.160000);
		var mapOptions = {
			zoom: 11,
			center: mapcenter,
			mapTypeId: google.maps.MapTypeId.TERRAIN
		};
		map = new google.maps.Map(document.getElementById("map"), mapOptions);
		directionsDisplay.setMap(map);
		directionsDisplay.setPanel(document.getElementById("directionsPanel"));
		//gets the layers and goes through the various necessary initializations
		getLayers();
}

//draws a point overlay - called from toggleLayer()
function initializePoint(pointData, pointIcon, pointArray) {
	//grabbing the data from the layers JSON object
	var pointLatLng = new google.maps.LatLng(pointData.lat, pointData.lng);
	var pointName = pointData.name;
	var iconImg = pointIcon;
 	//defining the marker
 	var marker = new google.maps.Marker({
      position: pointLatLng, 
      map: map, 
      title: pointName,
      icon: iconImg
  	});
  	//adds this marker to the point overlay tracking array
  	pointArray.push(marker);
  	//drawing the marker
  	marker.setMap(map); 
}

//draws a polyline overlay - called from toggleLayer(), 
function initializeLine(lineData, lineColor, lineArray) {
  	//creates an array to hold the line coordinates, and sets the value
  	var lineCoords = new Array();
  	lineCoords = lineData.coords;
    //defining the polyline    	
	var pLine = new google.maps.Polyline({
 	 	path: lineCoords,
	    strokeColor: lineColor,
	    strokeOpacity: 1.0,
	    strokeWeight: 2
	});
	//adds this polyline to the line overlay tracking array
	lineArray.push(pLine);
	//draws the line
	pLine.setMap(map);
}

//cycles through the layer data in the external JSON file, called from initialize()
function getLayers() {
	
	for(var layer in layers) {
    //adds a table row for each layer to the legend, checks it on, and sets the toggle function
    addTR(layer, layers[layer].legend);
    document.getElementById(layer).checked = true;
    toggleLayer(layer, true);
    }
}

//creating toggle functionality for the map layers
function toggleLayer(layer, checked) {
	//set a variable to handle the layer object (necessary? - seems cleaner)
	var thisLayer = layers[layer];
  //if the checkbox is just checked
  if (checked) {
  	//see if the layer type is a point
  	if (thisLayer.layertype=="point"){
  		//create a new sub-array in the point overlay tracker, keyed to this layer
  		markersArray[layer] = [];
		//initialize each point in the layer, and key it to the tracker sub-array
		for(id in thisLayer.data) {
    		initializePoint(thisLayer.data[id], thisLayer.icon, markersArray[layer]);
    	}
    //or if the layer type is a polyline
    } else if (layers[layer].layertype=="line") {
    	//create a new sub-array in the polyline overlay tracker, keyed to this layer
    	plinesArray[layer] = [];
		//initialize each line in the layer, and key it to the tracker sub-array
		for(id in thisLayer.data) {
    		initializeLine(thisLayer.data[id], thisLayer.color, plinesArray[layer]);
    	}
    } else {
   		//if the layer doesn't have a type, fix it
   		alert("Layer type is undefined! Fix Me!");
    }
  //or if the checkbox was just unchecked
  } else {
		//once a layer has been initialized, it seems that it's a waste to delete the tracker array.
		//is there a way to hide and then show the layer without deleting and recreating it?
		  //if it's a point layer
		  if (markersArray[layer]) {
				//remove each point in the tracker sub-array
				for (i in markersArray[layer]) {
				  markersArray[layer][i].setMap(null);
				}
				//delete the sub-array? this is also a relic FIXME
				markersArray[layer].length = 0;
		  } else if (plinesArray[layer]) {
				//remove each line in the tracker sub-array
				for (i in plinesArray[layer]) {
				  plinesArray[layer][i].setMap(null);
				}
				//delete the sub-array? this is also a relic FIXME
				plinesArray[layer].length = 0;
		  }
   }
  
}

function addTR(id) {
  var layerTR = document.createElement("tr");

  var inputTD = document.createElement("td");
  var input = document.createElement("input");
  input.type = "checkbox";
  input.id = id;
  input.onclick = function () { toggleLayer(this.id, this.checked) };
  inputTD.appendChild(input);

  var nameTD = document.createElement("td");
  var name = document.createTextNode(layers[id].legend);
  nameTD.appendChild(name);

  layerTR.appendChild(inputTD);
  layerTR.appendChild(nameTD);
  document.getElementById("legendTBODY").appendChild(layerTR);
}

function calcRoute() {
    var start = document.getElementById("start").value;
    var end = document.getElementById("end").value;
    var request = {
        origin:start, 
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.BICYCLING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
}

function showLegend() {
	var o = document.getElementById('legend');
	if(o.style.visibility == 'hidden') {
		o.style.visibility = 'visible';
	} else if(o.style.visibility == '') {
		o.style.visibility = 'hidden';
	} else {
		o.style.visibility = 'hidden';
	}
}