//Code to impliment a Google Map in Mike's Kayak Journal
//a script on the server, named xmlmap.php, is called AJAX style
//to find images, stories and routes that fit on the map
//this is re-done every time the map moves or sizes.
    function load(lat1,lng1,lat2,lng2)
    {
      if (GBrowserIsCompatible())
      {
	var bound = new GLatLngBounds(new GLatLng(lat1,lng1),new GLatLng(lat2,lng2))
	var map = new GMap2(document.getElementById("map"));
        map.setCenter(bound.getCenter());
	map.setZoom(map.getBoundsZoomLevel(bound));
	map.setMapType(G_SATELLITE_MAP);
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl( ));
//	map.addControl(new GOverviewMapControl());
	map.addMapType(G_SATELLITE_3D_MAP);
				//define my new icons
			// Create our camera marker icon
	var icon = new GIcon();
	icon.image = "http://www.kayaker.net/images/camera.png";
	icon.shadow = "http://www.kayaker.net/images/camshad.png";
	icon.iconSize = new GSize(33, 31);
	icon.shadowSize = new GSize(42, 31);
	icon.iconAnchor = new GPoint(1, 22);
	icon.infoWindowAnchor = new GPoint(16, 10);
			//create the route line joint 'knot' as a marker icon
	var jcon = new GIcon();
	jcon.image = "http://www.kayaker.net/images/knot.png";
	jcon.shadow = "http://www.kayaker.net/images/knots.png";
	jcon.iconSize = new GSize(5, 5);
	jcon.shadowSize = new GSize(9, 9);
	jcon.iconAnchor = new GPoint(3, 3);
	jcon.infoWindowAnchor = new GPoint(3, 3);
			//and the kayaker icon
	var kicon = new GIcon();
	kicon.image = "http://www.kayaker.net/images/kayak40.png";
	kicon.shadow = "http://www.kayaker.net/images/kayshad40.png";
	kicon.iconSize = new GSize(40, 43);
	kicon.shadowSize = new GSize(66, 43);
	kicon.iconAnchor = new GPoint(38,41);
	kicon.infoWindowAnchor = new GPoint(20, 9);



	var markers = new Array;		//keep an array of all markers here
	var mcount = 0;				//marker counter




	function domark(id,Vlong,Vlat,html,picon)	//routine to ignore, create, re-use markers on map
	{
	  for (var i=0;i<markers.length;i++)	//look through all the existing markers
	  {
	    if (markers[i].imageID == id)		//if it is already there
	    {
	      markers[i].imageage=0;		//mark it as one to save
	      return;				//leave existing ones alone
	    }
	  }
	  var marker= new GMarker(new GPoint(Vlong,Vlat),picon); //create a new one
	  marker.imageID=id;		//remember my DB id for each one
	  marker.imageHTML=html;	//save the HTML description for infowindows
          marker.imageage=0;		//mark this as a new one
	  map.addOverlay(marker);	//add it to the map
	  markers.push(marker);		//save the markers in an array
	}

	function oldmark()		//function to remove old markers
	{
	  for (var i=0;i<markers.length;i++)	//look at all the markers
	  {
	    if (markers[i].imageage>0)	//if it is an old stale one,
	    {
	      map.removeOverlay(markers[i])	//then remove it
	      markers.splice(i,1);		//remove it from my array
	      i -=1;	//prevent the index from skipping next one
	    }
	    else
	      markers[i].imageage=1;		//mark saved ones for next pass
	  }
	} //end function oldmark
    var polylist = new Array;		//list of polylines
    function loadXMLDoc() 
    {
      var req;			//object to hold XML string from server

      function processReqChange() 	//routine to read XML string
      {
        if (req.readyState == 4)     // only if req shows "complete"
        {
          if (req.status == 200)    // only if "OK"
          {
            var xmlDoc = req.responseXML;
		//get the statistics from this search
            var stats   = xmlDoc.getElementsByTagName("info")
	    var fimages = stats[0].getAttribute("images");
	    var uimages = stats[0].getAttribute("iused");
	    var fentries= stats[0].getAttribute("entries");
	    var uentries= stats[0].getAttribute("eused");
	    var rpoints = stats[0].getAttribute("points");
	    var rpused  = stats[0].getAttribute("pused");
            var maptitle= xmlDoc.getElementsByTagName("maptitle");
	    var mtitle  = maptitle[0].getAttribute("mtitle");
	    if (mtitle != "")
	      document.getElementById("mhead").innerHTML = mtitle;
	    var oldmap = maptitle[0].getAttribute("oldmap");
	    if (oldmap != "")
	      document.getElementById("oldmap").innerHTML = "Return to the <a href=\""+oldmap+"\">old static map</a> for this location.";
	    var mindex = maptitle[0].getAttribute("mindex");
	    if (mindex != "world")
	      document.getElementById("intro").innerHTML = "";
	    var upmap  = maptitle[0].getAttribute("upmap");
	    if (upmap != "")
	    {
	      document.getElementById("upmap").innerHTML = "Go up to the <a href=\"gmapmap.php?id="+upmap+"&bypass=on\">"+maptitle[0].getAttribute("regnam")+"</a> map.";
	    }
	    else
	      document.getElementById("upmap").innerHTML = "";
				//build the children (maps inside this one) selctor
	    var children = xmlDoc.documentElement.getElementsByTagName("childmap");
	    if (children.length>0)
	    {
	      $htring="<form action=\"gmapmap.php\" method=get>\nMaps in this region:\  <select name=id>\n";
	      for (var i=0;i<children.length;i++)
	      {
	        $htring += "    <option value=\""+children[i].getAttribute("cindex")+"\">";
		$htring += children[i].getAttribute("ctitle")+"\n";
	      }
	      $htring+="  <input type=submit value=GO>\n  <input type=hidden name=bypass value=on>\n</form>\n";
	      document.getElementById("inmap").innerHTML = $htring;
	    }
	    else
	      document.getElementById("inmap").innerHTML = "";
				//build the list of nearby maps
	    var nearby = xmlDoc.documentElement.getElementsByTagName("nearmap");
	    if (nearby.length>0)
	    {
	      $htring="<form action=\"gmapmap.php\" method=get>\nMaps near this one:\  <select name=id>\n";
	      for (var i=0;i<nearby.length;i++)
	      {
	        $htring += "    <option value=\""+nearby[i].getAttribute("nindex")+"\">";
		$htring += nearby[i].getAttribute("ntitle")+"\n";
	      }
	      $htring+="  <input type=submit value=GO>\n  <input type=hidden name=bypass value=on>\n</form>\n";
	      document.getElementById("nearmap").innerHTML = $htring;
	    }
	    else
	      document.getElementById("nearmap").innerHTML = "";

			//delete all the old polylines on the display
	    for (var i=0;i<polylist.length;i++)
	      map.removeOverlay(polylist[i]);
	    polylist = new Array;
			//loop through all the polylines in the XML file
	    var polylines = xmlDoc.documentElement.getElementsByTagName("polyline");
	    for (var i=0;i<polylines.length;i++)
	    {
	      var polyid = polylines[i].getAttribute("id");
	      var polytitle = polylines[i].getAttribute("title");

			//loop through all the points in each polyline
	      var parr = new Array;	//array to hold all the points
	      var points = polylines[i].getElementsByTagName("point");
	      for (var j=0;j<points.length;j++)
	      {
		var lat = parseFloat(points[j].getAttribute("lat"));
		var lng = parseFloat(points[j].getAttribute("lng"));
		parr.push(new GLatLng(lat,lng));	//store the points in an array
		var pmarker= new GMarker(new GLatLng(lat,lng),jcon); //create a new one
			//save the HTML description for infowindows
		pmarker.imageHTML='<a href="../php/journal.php?id='+polyid+'" target="entrybox">'+polytitle+'</a>';
		map.addOverlay(pmarker);		//add it to the map
	 	polylist.push(pmarker);		//save the markers in an array
	      }
	      var rpoly = new GPolyline(parr,"#ff0000",1,1);	//build a GPolyline
	      map.addOverlay(rpoly);				//display the GPolyline
	      polylist.push(rpoly);	//save the GPolyline for deleting next time around
	    }

            	// obtain the array of markers and loop through them
            var Xmarkers = xmlDoc.documentElement.getElementsByTagName("marker");
            for (var i = 0; i < Xmarkers.length; i++)
            {
            	// obtain the attribues of each marker from the XML string
              var id = Xmarkers[i].getAttribute("id");
              var lat = parseFloat(Xmarkers[i].getAttribute("lat"));
              var lng = parseFloat(Xmarkers[i].getAttribute("lng"));
              var hinfo = Xmarkers[i].getAttribute("info");
              var type = Xmarkers[i].getAttribute("type");
              if (type=="image")
              {
                var file = Xmarkers[i].getAttribute("file");
                var xsiz = Xmarkers[i].getAttribute("wide");
                var ysiz = Xmarkers[i].getAttribute("tall");
			//construct the html string
                var html='<a href="../php/image.php?id='+id+'" target="imagebox"><img src="'+file+'" width='+xsiz+' height='+ysiz+' align=left></a>';
                html += hinfo;
	    	domark(id,lng,lat,html,icon);		//call domark to display the marker
              }
              if (type=="entry")	//is it a journal entry
              {
                var html='<a href="../php/journal.php?id='+id+'" target="entrybox">'+hinfo+'</a>';
                domark(id,lng,lat,html,kicon);
              }
            }
            oldmark();	//delete markers no longer needed

				//display statistics about the search
            fentries +=' journal entries were found on this map, only '+uentries+' of them fit.<br>';
            fentries += fimages+' images were found, only '+uimages+' of them fit without crowding.<br>';
	    fentries += rpoints+' route points found, only '+rpused+' of them used.<br>\n';
            document.getElementById("imagebar").innerHTML = fentries;
          }
          else
          {
            alert("There was a problem retrieving the XML data:\n" + req.statusText);
          }
        }
      } //end function processReqChange()
	  var ll = map.getBounds().getSouthWest();
	  var ur = map.getBounds().getNorthEast();
      var url="xmlmap.php?lat1="+ur.lat()+"&lng1="+ll.lng()+"&lat2="+ll.lat()+"&lng2="+ur.lng();
      if (document.stories.stories.checked==false)
	url = url+"&stories=no";
      if (document.routes.routes.checked==false)
	url = url+"&routes=no";
      if (document.images.images.checked==false)
	url = url+"&images=no";
//document.getElementById("debugbar").innerHTML = url;
      req = GXmlHttp.create();	//create the XMLHttpRequest object
      req.onreadystatechange = processReqChange;
      req.open("GET", url, true);
      req.send(null);
    } //end function loadXMLDOC()

    	loadXMLDoc();		//call it once to load the first batch of icons


    GEvent.addListener(map, 'moveend',function(){loadXMLDoc();});
    GEvent.addListener(map, 'zoom',   function(){loadXMLDoc();});
    GEvent.addListener(map, 'click',
      function(overlay, point)
      {
        if (overlay)
        {
          if (overlay.imageHTML)	//if it has one of my html strings,
          {
            var htmldiv = '<div style="white-space:nowrap;"><p>'+overlay.imageHTML+'</p></div>';
            overlay.openInfoWindowHtml(htmldiv);
          }
        }
        if (point)
        {
          map.setCenter(point);
        }
      }
    );

      } //end if browser is compatible
    } //end load map function


