/*
 *	This all really needs to be tidied up, there's lot of 
*	functions doing basically the same thing and there
*	is no reason why we can't use a lot of the same
*	code to provide the maps for the landmark, route
* 	and gmap filter if only things were organised a bit
*	more sensibly
*/

gradientOverlay = null;
gpts = [];
gradientRequested = false;
gradientRetrieved = true;
gradientMarker = null;
markerMoving = false;
firstTime = true;
iconset = [];		
gmarkers = [];
htmls = [];
 map = null;
point = null;
retrievingData = false;
var geo = new GClientGeocoder();
var point1overlay=null;

function landmark_insert_map() {
/*
 *	This function is used by the landmark module to
 *	provide a map which you can add a marker to
 *	and which will update two boxes on the page
 *	with the latitude and longitude of the marker
 */


	var mycontrol=null;
	var point1overlay=null;
	
	if (GBrowserIsCompatible()) {

		map = new GMap2(document.getElementById("map"));
						
		var center = new GLatLng(52.496159531097106,-1.93084716796875);
		map.setCenter(center,6); 
		map.addControl(new GSmallMapControl()); 
		map.addControl(new GMapTypeControl()); 
		
		GEvent.addListener(map, 'click', function(overlay, point) {
			if (overlay) {
				map.removeOverlay(overlay);
			} else if (point) {
			map.addOverlay(marker = new GMarker(point));
				map.removeOverlay ( point1overlay );
				point1overlay = marker;
				document.landmarkform["edit-longitude"].value=point.x;
				document.landmarkform["edit-latitude"].value=point.y;
			}
		});
	}
}

function route_insert_map_original() {
/*
 *	This function is used by the route module to
 *	provide a map which you can add a route to
 * and which will update the database with
 * that route
 */

	var mycontrol=null;
	var point1overlay=null;
	var line1overlay=null;
	line1points=new Array(); 
	var line1string=new String();
	
	if (GBrowserIsCompatible()) {

		map = new GMap2(document.getElementById("map"));
						
		var center = new GLatLng(52.496159531097106,-1.93084716796875);
		map.setCenter(center,6); 
		map.addControl(new GSmallMapControl()); 
		map.addControl(new GMapTypeControl()); 
		
		GEvent.addListener( map, 'click', function(overlay, point) {
						  															
			if ( line1points.length > 30 ) {
				// Save the current points to the database
				// except for the current one 
				saveRouteData ( line1string );								
				line1string = "";
				line1points = new Array;
			}

			line1points.push(point);
			if (line1overlay) map.removeOverlay(line1overlay);						  
			line1overlay=new GPolyline(line1points,"#FF0000", 8);						  	
			map.addOverlay(new GPolyline(line1points,"#FF0000", 8));
						  	
			if (line1string.length > 0) line1string += ' + ';
			line1string += point.x + ',' + point.y;
			document.landmarkform["edit-route"].value = line1string;   						 			
		});
	}	

	function saveRouteData( linedata ) {	
		url = ( "http://" + location.hostname + "/club-test/node/addroute/" + linedata );		
		request = GXmlHttp.create();        			
		request.open("GET", url,true);			
		request.onreadystatechange = function() {
			if ( request.readyState==4 ){    	
			}
		}
		request.send(null)								
	}

}

function route_insert_map() {
/*
 *	This function is used by the route module to
 *	provide a map which you can add a route to
 * and which will update the database with
 * that route
 *
 *	This version is an attempt to use the road
 * hugging technique whereby we let google
 * navigate between the points and the attempt
 *	to retrieve the lat and long of each point
 * along the route.
 */

	var mycontrol=null;
	var point1overlay=null;
	var line1overlay=null;
	line1points=new Array(); 
	var line1string=new String();

	var dirn1 = new GDirections();
   var dirn2 = new GDirections();
   var dirn3 = new GDirections();

   var firstpoint = true;
   var gmarkers = [];
   var gpolys = [];
   var lastindex = 0;
	
if (GBrowserIsCompatible()) {
 
      var map = new GMap2(document.getElementById("map"));
      map.setCenter(new GLatLng(53.7877, -2.9832),13)
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      // == use different GDirections for adding and dragging, it is just simpler that way ==
      var dirn1 = new GDirections();
      var dirn2 = new GDirections();
      var dirn3 = new GDirections();

      var firstpoint = true;
      var gmarkers = [];
      var gpolys = [];
      var lastindex = 0;


      GEvent.addListener(map, "click", function(overlay,point) {
        // == When the user clicks on a the map, get directiobns from that point to itself ==
        if (point) {
          if (firstpoint) {
            dirn1.loadFromWaypoints([point.toUrlValue(6),point.toUrlValue(6)],{getPolyline:true});
          } else {
            dirn1.loadFromWaypoints([gmarkers[gmarkers.length-1].getPoint(),point.toUrlValue(6)],{getPolyline:true});
				for (var n=0; n < gpolys.length; n++) {
					for (var m=0; m < gpolys[n].getVertexCount(); m++) {
						var pt = gpolys[n].getVertex(m);
						line1string += pt.x + ',' + pt.y + ' + ';
					}
				}				
				document.landmarkform["edit-route"].value = line1string;
          }
			}
      });


      // == when the load event completes, plot the point on the street ==
      GEvent.addListener(dirn1,"load", function() {
        // snap to last vertex in the polyline
        var n = dirn1.getPolyline().getVertexCount();
        var p=  dirn1.getPolyline().getVertex(n-1);

        var marker=new GMarker(p,{draggable:true});
			
        GEvent.addListener(marker, "dragend", function() {
          lastIndex = marker.MyIndex;
          var point = marker.getPoint();
          if (lastIndex>0) {
            // recalculate the polyline preceding this point
            dirn2.loadFromWaypoints([gmarkers[lastIndex-1].getPoint(),point.toUrlValue(6)],{getPolyline:true});
          }
          if (lastIndex<gmarkers.length-1) {
            // recalculate the polyline following this point
            dirn3.loadFromWaypoints([point.toUrlValue(6),gmarkers[lastIndex+1].getPoint()],{getPolyline:true});
          }
        });
        map.addOverlay(marker);
        // store the details

        marker.MyIndex=gmarkers.length;
        gmarkers.push(marker);
        if (!firstpoint) {
          map.addOverlay(dirn1.getPolyline());
          gpolys.push(dirn1.getPolyline());				          
        }
        firstpoint = false;

			if (gmarkers.length>1 && gmarkers.length<26) {								
				document.getElementById("link").style.display="";			
        	} else {
          	document.getElementById("link").style.display="none";
        	}					
      });

      // == move the polyline preceding this point ==
      GEvent.addListener(dirn2,"load", function() {
        // snap to last vertex in the polyline
        var n = dirn2.getPolyline().getVertexCount();
        var p=dirn2.getPolyline().getVertex(n-1);
        gmarkers[lastIndex].setPoint(p);
        // remove the old polyline
        map.removeOverlay(gpolys[lastIndex-1]);
        // add the new polyline
        map.addOverlay(dirn2.getPolyline());
        gpolys[lastIndex-1] = (dirn2.getPolyline());
        calculateDistance();
      });

      // == move the polyline following this point ==
      GEvent.addListener(dirn3,"load", function() {
        // snap to first vertex in the polyline
        var p=dirn3.getPolyline().getVertex(0);
        gmarkers[lastIndex].setPoint(p);
        // remove the old polyline
        map.removeOverlay(gpolys[lastIndex]);
        // add the new polyline
        map.addOverlay(dirn3.getPolyline());
        gpolys[lastIndex] = (dirn3.getPolyline());		  	
        calculateDistance();
      });

      GEvent.addListener(dirn1,"error", function() {
        GLog.write("Failed: "+dirn1.getStatus().code);
      });
      GEvent.addListener(dirn2,"error", function() {
        GLog.write("Failed: "+dirn2.getStatus().code);
      });
      GEvent.addListener(dirn3,"error", function() {
        GLog.write("Failed: "+dirn3.getStatus().code);
      });

      function linkToGoogle() {
        var url="http://maps.google.com?q=from:+Start@" + gmarkers[0].getPoint().toUrlValue(5);
        for (var i=1; i<gmarkers.length-1; i++) {
          url+="+to:+"+gmarkers[i].getPoint().toUrlValue(5)
        }
        url+="+to:+End@"+gmarkers[gmarkers.length-1].getPoint().toUrlValue(5);
        window.location = url;
      }

    }
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }	
	
	function saveRouteData() {
		/* 
		 *	Use AJAX to save the current route data
		 *
		 * url = ( base_url() + "node/addroute/" + linedata );		
		 */
		
		for (var n=0; n < gpolys.length; n++) {
			for (var m=0; m < gpolys[n].getVertexCount(); m++) {
				var pt = gpolys[n].getVertex(m);
				linedata += pt.x + ',' + pt.y + ' + ';
			}
		}				
		
		url = ( "http://" + location.hostname + "/club-test/node/addroute/" + linedata );		
		request = GXmlHttp.create();        			
		request.open("GET", url,true);			
		request.onreadystatechange = function() {
			if ( request.readyState==4 ){}								
		}
		request.send(null)								
	}
}
		
function gmapnew_load_map( parameters ) {
/*
 *	This function is used by the gmap filter module to replace the filter
 * 	with a working google map containing all the landmarks and routes
 *	specified in the filter
 */
	
 
	if ( parameters['mapControl'] == 'small' ) {
		var mycontrol=new GSmallMapControl();
	} else {
	 	 var mycontrol=new GLargeMapControl();
	}
	
	var mapType = G_NORMAL_MAP;
	
	if ( parameters['mapType'] == 'hybrid' ) {
		mapType = G_HYBRID_MAP; 
	}
	
	if ( parameters['mapType'] == 'satellite' ) {
		mapType = G_SATELLITE_MAP;
	}
	
	routess = parameters['routes'];
	urlP = parameters['urlPath'];
	mapObject = new GMap2(document.getElementById( parameters['containerID'] ));
	mapObject.addControl(mycontrol);	
	mapObject.addControl(new GMapTypeControl()); 
	

	/*
	 *		Centre the map and zoom to the correct level to display
	 *		all the data
	 */

	var maxBounds = new GLatLng( parameters['positioningData' ][ 'maxLat'], parameters['positioningData'][ 'minLong'] );
	var minBounds = new GLatLng( parameters['positioningData'][ 'minLat'], parameters['positioningData'][ 'maxLong'] );
	var startBounds = new GLatLngBounds(); 
	startBounds.extend(maxBounds);
	startBounds.extend(minBounds);
	mapObject.setCenter(startBounds.getCenter(), mapObject.getBoundsZoomLevel(startBounds));
		
	loadDatav2( parameters['urlPath'], parameters['waypoints'], parameters['routes'] );
	mapObject.setMapType(mapType);
	
	/*
	 *	Maybe use some kind of timer so we don't 
	 *	actually start to do anything until the dragging 
	 *	has really stopped
	 */
	
	GEvent.addListener(mapObject, "dragend", function() {   	
		currentBounds = mapObject.getBounds();				
		if (!(currentMarkerSpread.containsBounds(currentBounds))) {																					
			if ( !(retrievingData) ) {
				loadDatav2( parameters['urlPath'], parameters['waypoints'], parameters['routes'] );
			}				
		}	 											
	});
		 	
	GEvent.addListener(mapObject, "zoomend", function() {
			if ( !(retrievingData) ) {
				loadDatav2( parameters['urlPath'], parameters['waypoints'], parameters['routes'] );
			}					
 	});
}

/*
 *
 *	Create the markers for the gmapnew_load_map
 * 	function
 */

function createMarker(point,name,html, colour ) {
 		
		/*
		 * Set up all the stuff for the icons, I'm sure a lot of this
		 * must be unecessary...
		 */
 		iconImagePath = "http://maps.google.com/mapfiles/kml/pal2/";
 		iconShadowPath = "http://maps.google.com/mapfiles/kml/pal2/";
 		iconSizeWidth = 32;
 		iconSizeHeight = 32;
 		iconShadowSizeWidth = 56;
 		iconShadowSizeHeight = 32;
 		iconAnchorWidth = 16;
 		iconAnchorHeight = 32;
 		iconWindowAnchorWidth = 16;
 		iconWindowAnchorHeight = 0;
 		iconShadowWindowAnchorWidth = 18;
 		iconShadowAnchorWindowHeight = 25;
 	
		var baseIcon = new GIcon();
		baseIcon.shadow = iconShadowPath;
		baseIcon.iconSize = new GSize(iconSizeWidth, iconSizeHeight);
		baseIcon.shadowSize = new GSize(iconShadowSizeWidth, iconShadowSizeHeight);
		baseIcon.iconAnchor = new GPoint(iconAnchorWidth, iconAnchorHeight);
		baseIcon.infoWindowAnchor = new GPoint(iconWindowAnchorWidth, iconWindowAnchorHeight);
		baseIcon.infoShadowAnchor = new GPoint(iconShadowWindowAnchorWidth, iconShadowAnchorWindowHeight);

	    var baseIcon = new GIcon();
        baseIcon.iconSize=new GSize(32,32);
        baseIcon.shadowSize=new GSize(56,32);
        baseIcon.iconAnchor=new GPoint(16,32);
        baseIcon.infoWindowAnchor=new GPoint(16,0);;

        
	    iconset["Pub"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon27.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon27s.png");
		iconset["Plane"]   = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon56.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon56s.png");
        iconset["Pushpin"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal5/icon14.png", null, "http://maps.google.com/mapfiles/kml/pal5/icon14s.png");
        iconset["Restaurant"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon40.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon40s.png");
        iconset["Cafe"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon62.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon62s.png");
        iconset["Airport"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon56.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon56s.png");
        iconset["More"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon7.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon7s.png");
        iconset["Railway station"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon9.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon9s.png");
        iconset["Shop"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon26.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon26s.png");
        iconset["Tourist info"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon43.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon43s.png");
        iconset["Hotel"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon10.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon10s.png");
        iconset["Bed and breakfast"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon28.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon28s.png");
        iconset["YHA"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal5/icon12.png", null, "http://maps.google.com/mapfiles/kml/pal5/icon12s.png");
        iconset["Leisure centre"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon57.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon57s.png");
        iconset["Bus stop"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal4/icon15.png", null, "http://maps.google.com/mapfiles/kml/pal4/icon15s.png");
        iconset["Campsite"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon12.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon12s.png");
		iconset["Activity centre"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon13.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon13s.png");
 		iconset["Water park"] = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal4/icon43.png", null, "http://maps.google.com/mapfiles/kml/pal4/icon43s.png");
		iconset["FIB"] = new GIcon(baseIcon, "http://localhost/club/modules/gmap/icons/fib.png", null, "");
		iconset["Sandwich shop"] = new GIcon(baseIcon, "http://localhost/club/modules/gmap/icons/sandwich.png", null, "");
		iconset["Pizza shop"] = new GIcon(baseIcon, "http://localhost/club/modules/gmap/icons/Pizza-shop.png", null, "");
		iconset["Fast food"] = new GIcon(baseIcon, "http://localhost/club/modules/gmap/icons/Fast-food.png", null, "");
		iconset["Henge"] = new GIcon(baseIcon, "http://localhost/club/modules/gmap/icons/Henge.png", null, "");		 	 		 	 	 	 
		html = '<div class="gmap-popup" style="width:250px; font-size: 12px; line-height:14px"><p>' + html + '</p></div>';
		
		/*
		 *	colour is actually the string telling us which icons we can use
		 * for this marker. This is a comma delimited list so the first
		 *	thing we need to do is split it up	
		 */

		var userIcons = colour.split(",");
		var icon_type = "Pushpin";
		/*
		 *	Now see if any of the values in this array matches any of the keys
	     *	in the icons array. At the moment we don't care about anything
		 * other than getting one match but later we'll need to keep track
		 * of all the terms for this marker in case we want to use filtering
		 * on the map of produce a legend or something
	 	 * 
		 */

		for ( p=0; p < userIcons.length; p++ ) {
			if ( iconset[userIcons[p] ] && iconset[userIcons[p]] != "" ) {				
				icon_type = userIcons[p];
			}
		}	

	
		colour = icon_type;
	
		if ( colour == "white" ) {
			var marker = new GMarker(point);
		} else
		{
			var icon = new GIcon(baseIcon);
			var marker = new GMarker(point, iconset[colour]);
		} 		
   	
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(html);
			});
		gmarkers[name] = marker;
        htmls[name] = html;

		return marker;
}

function myclick(i) {
	gmarkers[i].openInfoWindowHtml(htmls[i]);
}
  		  
function loadDatav2( urlPath, waypoints, routes ) {
/*
 *	This function is called from gmapnew_load_map
 *	and takes care of the calls to the ajax.php server
 *	which gets the landmarks and route data in the 
 *	current viewport
 */	

	var bounds = new GLatLngBounds(); 
	url = returnUrl ( returnBounds(), urlPath, waypoints, routes );
	firstTime = true;	
	retrievingData = true;
	GDownloadUrl(url, function(data, responseCode) {					
 		mapObject.clearOverlays();
		var xmlDoc = GXml.parse(data); 	
		markers = xmlDoc.documentElement.getElementsByTagName("marker");    					
				
		for ( i=0; i < markers.length; i++ ) {
			lat=parseFloat(markers[i].getAttribute("lat"));
			lng=parseFloat(markers[i].getAttribute("lng"));					
			point = new GLatLng( lat, lng ); 								
			html = decode(markers[i].getElementsByTagName("infowindow")); 									
			label = markers[i].getAttribute("label");
			colour = markers[i].getAttribute("icon");									
			marker = createMarker(point,label,html, colour);
			mapObject.addOverlay(marker);
		}

		lines = xmlDoc.documentElement.getElementsByTagName("line");

		for ( a = 0; a < lines.length; a++) {
			colour = lines[a].getAttribute("colour");
			width  = parseFloat(lines[a].getAttribute("width"));
			points = lines[a].getElementsByTagName("point");
			pts = [];
			for ( i = 0; i < points.length; i++) {							
				pts[i] = new GLatLng( parseFloat(points[i].getAttribute("lat")), parseFloat(points[i].getAttribute("lng")) );				
				}
			mapObject.addOverlay(new GPolyline(pts,"#000099",4,1));
		}		
		currentMarkerSpread =scaleBounds(mapObject.getBounds(),2.5);
		retrievingData = false;
	})
	
}
		
// The geo-coding code from the econm whatever website
//	this works brilliantly but wont do UK addresses thanks
// to the dreadful british post office :-(

function gmap_geocodeaddress(search) {
	var reasons = [];
   	reasons[G_GEO_SUCCESS]            				= "Success";
   	reasons[G_GEO_MISSING_ADDRESS]    		= "Missing Address: The address was either missing or had no value.";
   	reasons[G_GEO_UNKNOWN_ADDRESS]    	= "Unknown Address:  No corresponding geographic location could be found for the specified address.";
   	reasons[G_GEO_UNAVAILABLE_ADDRESS]	= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
   	reasons[G_GEO_BAD_KEY]            				= "Bad Key: The API key is either invalid or does not match the domain for which it was given";
   	reasons[G_GEO_TOO_MANY_QUERIES]   	= "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
	reasons[G_GEO_SERVER_ERROR]       		= "Server error: The geocoding request could not be successfully processed.";    

	// ====== Perform the Geocoding ======        
	geo.getLocations(search, function (result)
	{ 
    	 // If that was successful
       	if (result.Status.code == G_GEO_SUCCESS) {
			// How many resuts were found
			document.getElementById("landmark-messages").innerHTML = "Found " +result.Placemark.length +" results";
			//document.landmarkform["landmark-messages"].value	= "Found " +result.Placemark.length +" results";
			// Loop through the results, placing markers
         	for (var i=0; i<result.Placemark.length; i++) {
           		var p = result.Placemark[i].Point.coordinates;
                gmarkers[i] = new GMarker(new GLatLng(p[1],p[0]));
				document.getElementById("landmark-messages").innerHTML += '<br><a href="javascript:landmark_centreOnResult(' + i + ')">' +(i+1)+": "+ result.Placemark[i].address + '</a>';
				//document.landmarkform["landmark-messages"].value += "<br>"+(i+1)+": "+ result.Placemark[i].address + marker.getPoint();	             
                map.addOverlay(gmarkers[i]);
         	}
           	// centre the map on the first result
           	var p = result.Placemark[0].Point.coordinates;
           	map.setCenter(new GLatLng(p[1],p[0]),14);
			document.landmarkform["edit-longitude"].value=p[0];
			document.landmarkform["edit-latitude"].value=p[1];
            }
            // ====== Decode the error status ======
            else {
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              } 
              document.getElementById("landmark-messages").innerHTML = ('Could not find "'+search+ '" ' + reason);
            }
          }
        );
      }

function landmark_centreOnResult ( markerNumber ) {
	
	map.setCenter( gmarkers[markerNumber].getPoint(),14);
	gmarkers[markerNumber].showMapBlowup();
	document.landmarkform["edit-longitude"].value= gmarkers[markerNumber].getPoint().lng();
	document.landmarkform["edit-latitude"].value=gmarkers[markerNumber].getPoint().lat();
}

function nearbyGeocoder ( postcode ) {
	
	url = 'http://' + location.hostname + '/club/ajax.php?op=postcode&postcode=' + postcode;
	
	GDownloadUrl(url, function(returnData, responseCode) {					
 		coords = returnData.split( "," );
		landmark_CentreOnMarker ( parseFloat(coords[0]),parseFloat (coords[1]) ); 	
	})
	
}

function landmark_CentreOnMarker ( lat, lng ){
	point = new GLatLng( lat, lng ); 	
	if  (point) {
		map.addOverlay(marker = new GMarker(point));
		map.removeOverlay ( point1overlay );
		point1overlay = marker;
		map.setCenter(point,15); 
	}
	document.landmarkform["edit-longitude"].value=lng;
	document.landmarkform["edit-latitude"].value=lat;
}
	

/***
 *
 *	Unfinished code for gradient displayer
 *
 *	I think it basically worked but there were still
 *	some problems !
 *
 */		

function showGradient ( percentage ) {
	//
	//		Display the section of the map currently
	//		shown in the gradient view
	//
	
	loadDataGradient( urlP, percentage, routess );
	
}
	/*
	 *
	 * Various utility functions 
	 *
	 */
    								 
	function returnBounds () {
     	
		var maxLat = mapObject.getBounds().getNorthEast().lat();
		var minLat = mapObject.getBounds().getSouthWest().lat();
		var maxLng = mapObject.getBounds().getNorthEast().lng();
		var minLng = mapObject.getBounds().getSouthWest().lng();  		

		return new Array ( minLng, minLat, maxLng, maxLat );				

 	}
    			
 	function returnMarkerBounds ( currentBounds ) {
    	var maxLat = ( currentBounds[2] - currentBounds[0] ) + currentBounds[2];
		var minLat = currentBounds[0] - ( currentBounds[2] - currentBounds[0] );
		var maxLng = ( currentBounds[3] - currentBounds[1] ) + currentBounds[3];
		var minLng = currentBounds[1] - ( currentBounds[3] - currentBounds[1] );
					
		if ( minLat > 180 ) {		
			minLat = ( minLat + 180 ) * (-1);
		}
					
		if ( maxLng < -180 ) {		
			maxLng = ( maxLng - 180 ) * (-1);
		}
					
		return new Array (  minLng, minLat, maxLng, maxLat  );
   }

	function scaleBounds(tmpBounds,scale){
		var tmpCoords = boundsToCoords(tmpBounds);
		var midLat = (tmpCoords.north+tmpCoords.south)/2; 
		var midLng = (tmpCoords.east+tmpCoords.west)/2;
		
		tmpCoords.north = midLat + (tmpCoords.north - midLat)*scale; 
		tmpCoords.south = midLat + (tmpCoords.south - midLat)*scale; 
		tmpCoords.east  = midLng + (tmpCoords.east -  midLng)*scale; 
		tmpCoords.west  = midLng + (tmpCoords.west -  midLng)*scale; 
		
		if (tmpCoords.north > 85.932567920988){
			tmpCoords.north = 85.932567920988
		}
		
		if (tmpCoords.east > 180){
			tmpCoords.east = +180
		}
		
		if (tmpCoords.south < -128.8235826668448){
			tmpCoords.south = -128.8235826668448
		}
		
		if (tmpCoords.west < -180){
			tmpCoords.west = -180
		}
		
		var newBounds = new GLatLngBounds(new GLatLng(tmpCoords.south, tmpCoords.west), new GLatLng(tmpCoords.north, tmpCoords.east));
		return (newBounds);
	}

	function boundsToCoords(tmpBounds){
		var north=tmpBounds.getNorthEast().lat();
		var east=tmpBounds.getNorthEast().lng();
		var south=tmpBounds.getSouthWest().lat();
		var west=tmpBounds.getSouthWest().lng();
		return {north : north, east : east, west : west, south : south};
	}
    			
   function returnUrl ( currentBounds, urlPath, waypoints, routes ) {
    	currentZoomLevel =  mapObject.getZoom(); 		
		boundsString = currentBounds[2] + ", " + currentBounds[3] + " + " + currentBounds[0] + ", " + currentBounds[1];
    	//return urlPath + "/" + boundsString + "/" + currentZoomLevel + "/" + waypoints +	"/" + routes;
		return urlPath + "ajax.php" + "?bounds=" +boundsString + "&zoomLevel=" + currentZoomLevel + "&waypoints=" + waypoints + "&routes=" + routes;
   }

   function returnGradientUrl ( urlPath,  percentage, routes ) {
    	currentZoomLevel =  mapObject.getZoom(); 				
		return urlPath + "ajax.php" + "?op=gradient" + "&percentage=" + percentage + "&routes=" + routes;
   }
    			    			
  	function decode(a) {
		var b = "";
		if (a.length > 0) {
			if (a[0]) {
				if (a[0].firstChild) {
					b = a[0].firstChild.nodeValue;
				 }
			}
		}
		return b;
  	}

function loadDataGradient( urlPath, percentage, routes ) {
		
	if (!(gradientRequested)) {
		gradientRequested = true;
		url = returnGradientUrl( urlPath, percentage, routes);		
		GDownloadUrl(url, function(data, responseCode) {				
			var xmlDoc = GXml.parse(data); 	
			lines = xmlDoc.documentElement.getElementsByTagName("line");
		
			for ( a = 0; a < lines.length; a++) {
				colour = lines[a].getAttribute("colour");
				width  = parseFloat(lines[a].getAttribute("width"));
				points = lines[a].getElementsByTagName("point");
				gpts = [];
				for ( i = 0; i < points.length; i++) {							
					gpts[i] = new GLatLng( parseFloat(points[i].getAttribute("lat")), parseFloat(points[i].getAttribute("lng")) );				
					}
				}
				gradientRetrieved = true;							 
			})	
	}
		
		
	if ( gradientRetrieved && !( markerMoving)) {
		markerMoving = true;
		// Calulate total distance
		curr_distance = 0;
		for ( b = 0;b < gpts.length; b++ ) {
			if ( b==0 ) {
				curr_distance = 0;
			} 
			else {
				curr_distance = curr_distance + gpts[b].distanceFrom( gpts[b-1]);
			}	
		}
			
		plotPts = [];
		requiredDistance = (curr_distance * percentage) / 100;
		minDistance = requiredDistance - 75;
		maxDistance = requiredDistance + 75;
			
		if ( minDistance < 0 ) minDistance =0;
		if (maxDistance > curr_distance) maxDistance = curr_distance;
			
		for ( c=0;c < gpts.length;c++) {
			if ( c==0 ) {
				plotDistance = 0;
			} 
			else {
				plotDistance = plotDistance + gpts[c].distanceFrom( gpts[c-1]);
			}	
				
			//alert ( "Plot Distance: " + plotDistance + " Min Distance " + minDistance + " Max Distance " + maxDistance );
			if (  plotDistance >= minDistance && plotDistance <= maxDistance ) {				
				plotPts.push(gpts[c]);
			}
		}
				
		
		if (!( firstTime) ) {
			if ( plotPts[0] ) {
				gradientMarker.setPoint(plotPts[0]);					
				gradientMarker.redraw(true);
				markerMoving = false; 		
			}
		} else
		{
			if ( plotPts[0] ) {
				gradientMarker = createMarker(plotPts[0],"gradient","gradient", "green");
				mapObject.addOverlay(gradientMarker);
				markerMoving = false;
				firstTime = false;
			} else {
				firstTime = true;
			}
		}			
		markerMoving = false;
	}
}
	

/***
 *
 *	The below seems to be connected to the Route 
 *	module in some manner
 *
 

function gmapnew_loadrouteplanner( urlbase ) {
	
	var map=null;
	var mycontrol=null;
	var line1overlay=null;
	line1points=new Array(); 
	var line1string=new String();
	
	gmapload();		
	
	function mapat(instring) {
		var splitstring=instring.split(",");
			map.centerAtLatLng(new GPoint(splitstring[0],splitstring[1]));
		}

	function docontrol(incontrol) {
		map.addControl(mycontrol = new GSmallMapControl());
	}

	function changetype(intype) {
		 //map.setMapType(G_MAP_TYPE);
	}

	function removeWaypoint () {
		line1points.pop();
		 if (line1overlay) map.removeOverlay(line1overlay);
			line1overlay=new GPolyline(line1points,"#FF0000", 8);
			map.addOverlay(line1overlay);
						  
			number_of_points = line1points.length;
						  
			line1string = "";
						  
			for ( x = 0; x = number_of_points; x++ )
			{
				line1string += line1points[x].point.x + ',' + point.y;
			}
				document.routeform["edit[route]"].value = line1string;  
	}

	function saveRouteData( linedata ) {
		// 
		//	Use AJAX to save the current route data
		//
		//url = ( base_url() + "node/addroute/" + linedata );		
		//alert(url);		
		
		url = ( "http://" + location.hostname + "/club-test/node/addroute/" + linedata );		
		request = GXmlHttp.create();        			
		request.open("GET", url,true);			
		request.onreadystatechange = function() {
						if ( request.readyState==4 ){    	
							
								}
								
						}
											
					request.send(null)								
	}

	function gmapload() {
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("map"));
			//map.setMapType(G_MAP_TYPE);
			//map.centerAndZoom(new GPoint(-1.93084716796875, 52.496159531097106), 7);
			var center = new GLatLng(52.496159531097106,-1.93084716796875);
			map.setCenter(center,6); 
			map.addControl(new GSmallMapControl()); 
			map.addControl(new GMapTypeControl()); 

			GEvent.addListener(map, 'click', function(overlay, point) {
						  															
				if ( line1points.length > 30 ) {
					// Save the current points to the database
					// except for the current one 
					saveRouteData ( line1string );								
					line1string = "";
					line1points = new Array;
				}
					line1points.push(point);
					if (line1overlay) map.removeOverlay(line1overlay);						  
						line1overlay=new GPolyline(line1points,"#FF0000", 8);						  	
						map.addOverlay(new GPolyline(line1points,"#FF0000", 8));
						  	
						if (line1string.length > 0) line1string += ' + ';
							line1string += point.x + ',' + point.y;
						  	document.routeform["edit[route]"].value = line1string;   						 			
			});
		}
	}
}

*/
/***
 *
 *	Utility functions to enable the legend menu
 *	displayed with maps to fold and unfold
 *
 */

function gogirl(e) {
    if (document.getElementById(e).style.display == 'none') {
        document.getElementById(e).style.display = 'block';
    } else {
        document.getElementById(e).style.display = 'none';
    }
}

function hideall() {
        var Nodes = document.getElementsByTagName('ul')
        var max = Nodes.length
        for(var i = 0;i < max;i++) {
                var nodeObj = Nodes.item(i)
				if ( checkMapNode( nodeObj.className ) ) {                	
					nodeObj.style.display = 'none';
				}
        }
}

function checkMapNode( mynodeName ) {
	// Check if a node is a part of the map concertina display
	nodeTerms = mynodeName.split("-");
	//alert ( mynodeName + " -- " + nodeTerms[0] ) ;
	if (  nodeTerms[0] == "concertina" ) {
		return true;
	} else {
		return false;
	}
}