//map variables
var map;
var centerLatitude = 41.648288;
var centerLongitude = -72.696533;
var center = new GLatLng(centerLatitude, centerLongitude);
var startZoom = 9;
var maptype = G_PHYSICAL_MAP;

//marker variables
var gmarkers = [];
var htmls = [];
var i = 0;
var to_htmls = [];

//line measuring variables
var COLORS = [["red", "#ff0000"], ["orange", "#ff8800"], ["green","#008000"],
              ["blue", "#000080"], ["purple", "#800080"]];
var options = {};
var lineCounter_ = 0;
var shapeCounter_ = 0;
var markerCounter_ = 0;
var colorIndex_ = 0;
var featureTable_;

    // === Create an associative array of GIcons() ===
      
var iconHike = new GIcon();
iconHike.image = "images/parking.png";
iconHike.iconSize = new GSize(15, 15);
iconHike.iconAnchor = new GPoint(7, 15);
iconHike.infoWindowAnchor = new GPoint(5, 5);
    
var iconWaterfall = new GIcon();
iconWaterfall.image = "images/hikect_waterfall_icon.png";
iconWaterfall.iconSize = new GSize(30, 30);
iconWaterfall.iconAnchor = new GPoint(15, 15);
iconWaterfall.infoWindowAnchor = new GPoint(25, 8);

var gicons = [];
gicons["hike"] = iconHike;
gicons["waterfall"] = iconWaterfall;

      // skip the first character, we are not interested in the "?"
      var query = location.search.substring(1);

      // split the rest at each "&" character to give a list of  "argname=value"  pairs
      var pairs = query.split("&");
      for (var k=0; k<pairs.length; k++) {
        // break each pair at the first "=" to obtain the argname and value
	var pos = pairs[k].indexOf("=");
	var argname = pairs[k].substring(0,pos).toLowerCase();
	var value = pairs[k].substring(pos+1).toLowerCase();

        // process each possible argname
        if (argname == "lat") {centerLatitude = parseFloat(value);}
        if (argname == "lng") {centerLongitude = parseFloat(value);}
        if (argname == "zoom") {startZoom = parseInt(value);}
        if (argname == "type") {
          if (value == "m") {maptype = G_NORMAL_MAP;}
          if (value == "k") {maptype = G_SATELLITE_MAP;}
          if (value == "h") {maptype = G_HYBRID_MAP;}
          if (value == "p") {maptype = G_PHYSICAL_MAP;}
          if (value == "c") {maptype = USGS_TOPO_TILES;}
          var center = new GLatLng(centerLatitude, centerLongitude);
        }
      }

function select(buttonId) {
  document.getElementById("hand_b").className="unselected";
  document.getElementById("line_b").className="unselected";
  document.getElementById(buttonId).className="selected";
}

function stopEditing() {
  select("hand_b");
}

function getColor(named) {
  return COLORS[(colorIndex_++) % COLORS.length][named ? 0 : 1];
}

function startLine() {
  select("line_b");
  var color = getColor(false);
  var line = new GPolyline([], color);
  startDrawing(line, "Line " + (++lineCounter_), function() {
    var cell = this;
    var len = line.getLength();
    cell.innerHTML = (Math.round(len * 0.621371192 / 10) / 100 ) + " miles";
  }, color);
}

function addFeatureEntry(name, color) {
  currentRow_ = document.createElement("tr");
  var colorCell = document.createElement("td");
  currentRow_.appendChild(colorCell);
  colorCell.style.backgroundColor = color;
  colorCell.style.width = "1em";
  var nameCell = document.createElement("td");
  currentRow_.appendChild(nameCell);
  nameCell.innerHTML = name;
  var descriptionCell = document.createElement("td");
  currentRow_.appendChild(descriptionCell);
  featureTable_.appendChild(currentRow_);
  return {desc: descriptionCell, color: colorCell};
}

function startDrawing(poly, name, onUpdate, color) {
  map.addOverlay(poly);
  poly.enableDrawing(options);
  poly.enableEditing({onEvent: "mouseover"});
  poly.disableEditing({onEvent: "mouseout"});
  
  GEvent.addListener(poly, "endline", function() {
    select("hand_b");
    var cells = addFeatureEntry(name, color);
    GEvent.bind(poly, "lineupdated", cells.desc, onUpdate);
    GEvent.addListener(poly, "click", function(latlng, index) {
      if (typeof index == "number") {
        poly.deleteVertex(index);
      } else {
        var newColor = getColor(false);
        cells.color.style.backgroundColor = newColor
        poly.setStrokeStyle({color: newColor, weight: 4});
      }
    });
  });
}      
      
if (GBrowserIsCompatible()) {
	
		  // A function to create the marker and set up the event window
      function createMarker(point,html,icontype) {
      // === create a marker with the requested icon ===
      var marker = new GMarker(point, gicons[icontype]);
      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
      });
      
        to_htmls[i] = html + "<DIV class='infowin'>" +
           'Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
                  // "(" + name + ")" + 
           '"/>'+"</DIV>";
                 
      // save the info we need to use later
      gmarkers[i] = marker;
      htmls[i] = html;
      i++;
      return marker;
      }

//       function ZoomIN(i) {
// 	    map.closeInfoWindow();  
// 	    map.setCenter(gmarkers[i].getPoint(), 15);
//         gmarkers[i].openInfoWindowHtml(htmls[i]);
//       }
      
      function ZoomOUT(i) {
	    map.closeInfoWindow();  
	    map.setCenter(center, 9);
        gmarkers[i].openInfoWindowHtml(htmls[i]);
      }
      
      function tohere(i) {
        gmarkers[i].openInfoWindowHtml(to_htmls[i]);
      }
      
    	 // ========== This function will create the "link to this page"
      function makeLink() {
        var a="http://maps.hikect.com/index.php" 
           + "?lat=" + map.getCenter().lat().toFixed(6)
           + "&lng=" + map.getCenter().lng().toFixed(6)
           + "&zoom=" + map.getZoom()
           + "&type=" + map.getCurrentMapType().getUrlArg();
        document.getElementById("link").innerHTML = '<a href="' +a+ '" rel="bookmark">Link</a>&nbsp<a href="' +a+ '" rel="bookmark"><img src="images/link.png" /></a>';
      }

	//Create the tile layer object
	var detailLayer = new GTileLayer(new GCopyrightCollection(''));
	var tileOverlay = new GTileLayerOverlay(detailLayer);

	//Method to retrieve the URL of the tile
	detailLayer.getTileUrl = function(tile, zoom){
    	//pass the x and y position as wel as the zoom
    	var tileURL = "server.php?x="+tile.x+"&y="+tile.y+"&zoom="+zoom;
    	return tileURL;
	};

	detailLayer.isPng = function() {
   		//The example uses GIF's
    	return false;
	}

	function init() {
		container = document.getElementById("map");
		document.getElementById('button-sidebar-hide').onclick = function() { return changeBodyClass('sidebar-right', 'nosidebar'); };
		document.getElementById('button-sidebar-show').onclick = function() { return changeBodyClass('nosidebar', 'sidebar-right'); };
		resizeMap();
    	map = new GMap2(container);
    	map.addMapType(G_PHYSICAL_MAP);
    	map.addControl(new GLargeMapControl3D());
    	Add_Custom_Layers(map);
    	map.addControl(new GScaleControl());
    	map.addControl(new GMapTypeControl());
    	map.setCenter(center, startZoom);
    	map.setMapType(maptype);
    	map.addOverlay(tileOverlay);
    	map.enableScrollWheelZoom();
        featureTable_ = document.getElementById("featuretbody");
        select("hand_b");    	

    	
    	GDownloadUrl("genxml.php", function(data) {
          var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName("marker");
          for (var i = 0; i < markers.length; i++) {
            var name = markers[i].getAttribute("name");
            var weblink = markers[i].getAttribute("weblink");
            var icontype = markers[i].getAttribute("icontype");
            if ( icontype == "hike" ) {	
            var html = "<DIV class='infowin'>" + name + 
            "<br/> <a href=http://www.hikect.com/trails/" + weblink + " target='_self'>Details</a>" +
//             "<br/> <a href='javascript:ZoomIN(" + i + ")' >Zoom to Street</a>" + "&nbsp;&nbsp;&nbsp;" +
            "<br/> <a href='javascript:ZoomOUT(" + i + ")' >Zoom to State</a> <br/>" +
            " <b>Directions: </b><a href='javascript:tohere("+i+")'>To here</a> </DIV>";
            }
            if ( icontype == "waterfall" ) {	
            var html = "<DIV class='infowin'>" + name + 
            "<br/> <a href=http://www.hikect.com/trails/" + weblink + " target='_self'>Details</a>" +
            "<br/> <a href='javascript:ZoomIN(" + i + ")' >Zoom to Street</a>" + "&nbsp;&nbsp;&nbsp;" +" <a href='javascript:ZoomOUT(" + i + ")' >Zoom to State</a> <br/><b>Directions: </b><a href='javascript:tohere("+i+")'>To here</a> </DIV>";
            }
            // html = html + '<br>Directions: <a href="javascript:tohere('+i+')">To here</a>';            
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                    parseFloat(markers[i].getAttribute("lng")));
            
            var manager = new GMarkerManager(map);
            var marker = createMarker(point, html, icontype);
            manager.addMarker(marker, 12); 
            //map.addOverlay(marker);
            
            
         	/* You need to refresh after zooming to make markers (dis)appear. */
    		GEvent.addListener(map, "zoomend", function(old, current) {
        		manager.refresh();
    		}); 
          }
        }); 

      // Make the link the first time when the page opens
      makeLink();

      // Make the link again whenever the map changes
      GEvent.addListener(map, 'maptypechanged', makeLink);
      GEvent.addListener(map, 'moveend', makeLink);
	}

	function windowHeight() {
  	if( typeof( window.innerWidth ) == 'number' ) {
    	//Non-IE
    	return window.innerHeight;
  	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	    return document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
	    return document.body.clientHeight;
	  }
	}
	
	function resizeMap() {
		var height = windowHeight() - document.getElementById('logo').offsetHeight;
		document.getElementById('map-wrapper').style.height = height + 'px';
		document.getElementById('map').style.height = height + 'px';
	}

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

}

	else {
		alert("Sorry, the Google Maps API is not compatible with this browser");
}

window.onload = init;
window.onresize = resizeMap;