// Because we are using a geolocation service we need to make sure sensor=true
//google.load("maps", "2", {"other_params":"sensor=true"});

var geocoder;
var lat;
var lng;
var acc;
var map;



//global variable declarations, arrays are to track drawing and removal of overlays
var markersArray = [];
var plinesArray = [];

//basic map initialization - api version 3
function initialize() {
	 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);
	 //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;
	//defining the marker
	var marker = new google.maps.Marker({
      position: pointLatLng, 
      map: map,
      icon: pointIcon, 
      title: pointName
  	});
  	//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 {
	 //FIXME is this loop necessary? relic of earlier attempts...
	 for(id in thisLayer.data) {
	 //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[iM].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[iM].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 findLocation() {

  if(navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
      placeNow = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
	  map.setCenter(placeNow);
   	  map.setZoom(14);
   
   	  var manIcon = "http://www.ravensmile.com/placekeepr/images/man.png";
	  var currentPlace = new google.maps.Marker({
      position: placeNow,
      map: map,
      icon: manIcon
  	  });

	  currentPlace.setMap(map);
	}, function() {
      handleNoGeolocation(browserSupportFlag);
    });
    } else {
    browserSupportFlag = false;
    handleNoGeolocation(browserSupportFlag);
  }
}

  function handleNoGeolocation(errorFlag) {
    if (errorFlag == true) {
      alert("Geolocation service failed.");
    } else {
      alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
    }
  }


// function foundLocation(position)
// {
// 	lat = position.coords.latitude;
// 	lng = position.coords.longitude;
// 	acc = position.coords.accuracy;
// 	showLocation();
// }
// 
// function noLocation(error)
// {
// 	document.getElementById("message").innerHTML  = 'Could not find location';
// 	 alert(error.message);
// }
// 
// function showLocation() {
//     var placeNow = new googl.maps.LatLng(lat, lng);
//   	map.setCenter(placeNow);
//   	map.setZoom(14);
//    
//    	var manIcon = "http://www.ravensmile.com/placekeepr/images/man.png";
// 	var currentPlace = new google.maps.Marker({
//       position: placeNow,
//       map: map,
//       icon: manIcon
//   });
// 
// 	currentPlace.setMap(map);
// }


function showOverlay() {
	var o = document.getElementById('legend');
	o.style.visibility = 'visible';
}
function hideOverlay() {
	var o = document.getElementById('legend');
	o.style.visibility = 'hidden';
}

function resetMap() {
	var zoom=10;
	var center= new GLatLng(40.000000,-75.160000);
	map.setUIToDefault();
  	map.setCenter(center, zoom);
  	map.setMapType(G_PHYSICAL_MAP);
}









