var map = null;
var mgr = null;
var geocoder = null;
 
GEvent.addDomListener(window,'load',function(){
loadGoogleMap();
map.setCenter(new GLatLng(35.0,-14),0);
})
function loadGoogleMap(){
  map = new GMap2(document.getElementById("large-google-map"));
 
  // add the controls
  map.addControl(new TextualZoomControl());
  map.addControl(new GSmallMapControl()); 
  geocoder = new GClientGeocoder();  
  map.addControl(new GZoomControl(
		/* first set of options is for the visual overlay.*/
		{
			nOpacity:.2,
			sBorder:"2px solid red"
		},
		/* second set of optionis is for everything else */
		{
			sButtonHTML:"<img src='images/zoom-button.gif' />",
			sButtonZoomingHTML:"<img src='images/zoom-button-activated.gif' />",
			oButtonStartingStyle:{width:'24px',height:'24px'}
		}	
		
	));

map.setCenter(new GLatLng(35.0,-14),0);
 map.enableDoubleClickZoom();
}


function drawPlace(placetodraw){
map.checkResize();
          if (geocoder) {
        geocoder.getLatLng(placetodraw,
          function(point) {
            if (!point) {
              alert("Google could not map "+placetodraw);
            } else {            
            map.setCenter(point, 3);                             
            var marker = new GMarker(point);
        var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        var lngDelta = (northEast.lng() - southWest.lng()) / 4;
        var latDelta = (northEast.lat() - southWest.lat()) / 4;
        var rectBounds = new GLatLngBounds(
            new GLatLng(southWest.lat() + latDelta,
                        southWest.lng() + lngDelta),
            new GLatLng(northEast.lat() - latDelta,
                        northEast.lng() - lngDelta));
        map.setZoom(map.getBoundsZoomLevel(bounds));    
        map.setCenter(bounds.getCenter());                    
        map.clearOverlays();                 
        map.addOverlay(new Rectangle(rectBounds));               	
   
            }       }
        );
      }
  else{
   document.getElementById("north").value = "";
   document.getElementById("west").value = "";
   document.getElementById("south").value = "";
   document.getElementById("east").value = "";   
   map.clearOverlays();
   query();
   }
      
    }





  function spatialBounding(placeList) { 
  if(placeList != "Select from list"){
  var spatial = document.getElementById("placeList").value; 
  Place1.getPlace(spatial, updateSpatialList)
    map.checkResize(); 
    }
    }
 function updateSpatialList(data)
    {  
        var splitter =new Array();
        splitter = data.split(" ");       
        dwr.util.setValue("south",splitter[2]);
        dwr.util.setValue("west",splitter[1]);
        dwr.util.setValue("north",splitter[0]);
        dwr.util.setValue("east",splitter[3]);
        
        joiner = new Array();
        joiner = splitter.join(",");
    	dwr.util.setValue("complete",joiner);     	
    	loadMap1();
        query();              
       	
    }  
      function Rectangle(bounds, opt_weight, opt_color) {
      this.bounds_ = bounds;
      this.weight_ = opt_weight || 3;
      this.color_ = opt_color || "red";
    }
    Rectangle.prototype = new GOverlay();
    // Creates the DIV representing this rectangle.
    Rectangle.prototype.initialize = function(map) {
      // Create the DIV representing our rectangle
      var div = document.createElement("div");
      div.style.border = this.weight_ + "px solid " + this.color_;
      div.style.position = "absolute";

      // Our rectangle is flat against the map, so we add our selves to the
      // MAP_PANE pane, which is at the same z-index as the map itself (i.e.,
      // below the marker shadows)
      map.getPane(G_MAP_MAP_PANE).appendChild(div);

      this.map_ = map;
      this.div_ = div;
    }
    
    // Remove the main DIV from the map pane
    Rectangle.prototype.remove = function() {
      this.div_.parentNode.removeChild(this.div_);
    }

    // Copy our data to a new Rectangle
    Rectangle.prototype.copy = function() {
      return new Rectangle(this.bounds_, this.weight_, this.color_,
                           this.backgroundColor_, this.opacity_);
    }

    // Redraw the rectangle based on the current projection and zoom level
    Rectangle.prototype.redraw = function(force) {
      // We only need to redraw if the coordinate system has changed
      if (!force) return;

      // Calculate the DIV coordinates of two opposite corners of our bounds to
      // get the size and position of our rectangle
      var c1 = this.map_.fromLatLngToDivPixel(this.bounds_.getSouthWest());
      var c2 = this.map_.fromLatLngToDivPixel(this.bounds_.getNorthEast());

      // Now position our DIV based on the DIV coordinates of our bounds
      this.div_.style.width = Math.abs(c2.x - c1.x) + "px";
      this.div_.style.height = Math.abs(c2.y - c1.y) + "px";
      this.div_.style.left = (Math.min(c2.x, c1.x) - this.weight_) + "px";
      this.div_.style.top = (Math.min(c2.y, c1.y) - this.weight_) + "px";
    } 
   
        








  //<![CDATA[
var map1;	
	
	// Load the GMap in the page
function loadMap1() {
//alert("inside loadMap1");
	size = 0 + 1;
	var set = new Array(size);
	var coord = new Array();	
	coord[0] = document.getElementById("north").value;
	coord[1] = document.getElementById("west").value;
	coord[2] = document.getElementById("south").value;
	coord[3] = document.getElementById("east").value;
	wkt0 = formulateWKT(coord[2], coord[1], coord[0], coord[3]);

	set[0] = wkt0;
	
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("large-google-map"));
		map.addControl(new TextualZoomControl());
  		map.addControl(new GSmallMapControl());
  		
  		map.addControl(new GZoomControl(
		/* first set of options is for the visual overlay.*/
		{	
			nOpacity:.2,
			sBorder:"2px solid red"
		},
		/* second set of optionis is for everything else */
		{
			sButtonHTML:"<img src='images/zoom-button.gif' />",
			sButtonZoomingHTML:"<img src='images/zoom-button-activated.gif' />",
			oButtonStartingStyle:{width:'24px',height:'24px'}
		}	
		
	));

	// need to set the the map before adding overlays
		map.setCenter(new GLatLng(0, 0), 20);

		for (j = 0; j < set.length; j++) {
			highlightFeature(set[j]);
		}
		var bounds = jpGetGBoundsForAllWKT(set);
		mhFocusOnBox(map, bounds);
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		var lngDelta = (northEast.lng() - southWest.lng()) / 4;
		var latDelta = (northEast.lat() - southWest.lat()) / 4;
	}
}

	// Zooms to global view of world
function zoomOutToWorld() {
	map.setCenter(new GLatLng(0, 0), 0); // v2
}

	// Draws a coverage on the map
	// wkt = A single coverage in WKT format
function highlightFeature(wkt) {
	var bounds = jpGetGBoundsForWKT(wkt);
	var width = mhGetBoxWidth(bounds);
	var height = mhGetBoxHeight(bounds);
	if ((width == 0) && (height == 0)) {
		var markerLatLng = new GLatLng(bounds.getCenter().lat(), bounds.getCenter().lng());
		var icon = new GIcon();
		icon.image = "../images/marker16.png";
		icon.iconSize = new GSize(27, 27);
		icon.shadowSize = new GSize(5, 9);
		icon.iconAnchor = new GPoint(16, 27);
		var marker = new GMarker(markerLatLng, icon);
		map.addOverlay(marker);
		map.setCenter(markerLatLng);
	} else {
		var poly = mhCreateBoundsPoly(map, bounds);
		map.addOverlay(poly);
	}
}
    //]]>
//function getKey() {
//	return "ABQIAAAAlS3JK-ZqWSF9DvlsVuKDyBStLbd1zlO1JgMSKHwKtpUL2VUKEBSmWsDDBEvoiZmIBv4jFIgbYNMZ6g";
//}

// Include Google Maps API from maps.google.com
//document.write("<scr" + "ipt src=\"http://maps.google.com/maps?file=api&amp;v=2&amp;key=" + getKey() + "\" type=\"text/javascript\"></scr" + "ipt>");
document.write(tag);
/** Reusable functions from Mark Harwood */

	// Creates a polyline (box) for the given map and GLatLngBounds
	// box = GLatLngBounds
function mhCreateBoundsPoly(map, box) {

                // if width > 180, google bug will draw the box with
		// east and west reversed because GLatLngBounds get normalized
		// So, must add two extra points at (nLat, centerLng) and
		// (sLat, centerLng) to force it to draw the correct box
	var c = box.getCenter().lng(); // center lng
	var c2 = box.getCenter().lat(); // center lat
	var height = box.toSpan().lat();
	var hDiff = 0;
	if (height > 0) {
		hDiff = height / 100;
	}
	var width = mhGetBoxWidth(box);
	var wDiff = 0;
	if (width > 0) {
		wDiff = width / 100;
	}
	var points = [];
	var n = box.getNorthEast().lat();
	var s = box.getSouthWest().lat();
	var e = box.getNorthEast().lng();
	var w = box.getSouthWest().lng();
	if (s != -90) {
		var sNew = s + hDiff;
		s = sNew;
	} else {
		s = -85;
	}
	if (n != 90) {
		var nNew = n - hDiff;
		n = nNew;
	} else {
		n = 85;
	}
	var wNew = w + wDiff;
	w = wNew;
	var eNew = e - wDiff;
	e = eNew;
	points.push(new GLatLng(n, w));
	points.push(new GLatLng(c2, w)); // extra center lat point
	points.push(new GLatLng(s, w));
	if (width >= 180) {
		points.push(new GLatLng(s, c));
	}
	points.push(new GLatLng(s, e));
	points.push(new GLatLng(c2, e));  // extra center lat point
	points.push(new GLatLng(n, e));
	if (width >= 180) {
		points.push(new GLatLng(n, c));
	}
	points.push(new GLatLng(n, w));

		//var color = "#666699";
	var color = "#cc0000";
	var weight = 3; // int equal to width in pixels
	var opacity = 0.75; // float from 0 to 1

//		alert("points = "+points);
	return new GPolyline(points, color, weight, opacity);
}


	//parses out coordinates from polygons (TODO no POINT/Line etc support here yet!)	
function jpGetGBoundsForWKT(wkt) {
	var cStart = wkt.lastIndexOf("(") + 1;
	var cEnd = wkt.indexOf(")");
	var coords = wkt.substring(cStart, cEnd);
				
		//alert("splitting["+coords+ "]from["+wkt);
	var points = coords.split(",");
	var sw = points[3];
	var ne = points[1];
	var s = 9999;
	var n = -9999;
	var e = -9999;
	var w = 9999;
	var latLon = sw.split(" ");
	s = parseFloat(latLon[0]);
	w = parseFloat(latLon[1]);
	latLon = ne.split(" ");
	n = parseFloat(latLon[0]);
	e = parseFloat(latLon[1]);
	return new GLatLngBounds(new GLatLng(s, w), new GLatLng(n, e));
}


	// Parses out coordinates from polygons (TODO no POINT/Line etc support here yet!)
	// to determine the bounds for the _set_ of polygons
	// set = Array of wkt polygons
function jpGetGBoundsForAllWKT(set) {

	   // the max extent for the entire SET of coverages
	var setN = -9999;
	var setS = 9999;
	var setE = -9999;
	var setW = 9999;
	for (j = 0; j < set.length; j++) {
		var wkt = set[j];
		// wkt = (slat wlon, slat elon, nlat elon, nlat wlon, slat wlon)
		// wkt = (LL, LR, UR, UL, LL)
		var cStart = wkt.lastIndexOf("(") + 1;
		var cEnd = wkt.indexOf(")");
		var coords = wkt.substring(cStart, cEnd);
				
		//alert("splitting["+coords+ "]from["+wkt);
		var points = coords.split(",");
		for (i = 0; i < points.length; i++) { // should be 5 points
		}
		var sw = points[3];
		var ne = points[1];
		var latLon = sw.split(" ");
		s = parseFloat(latLon[0]);
		w = parseFloat(latLon[1]);
		latLon = ne.split(" ");
		n = parseFloat(latLon[0]);
		e = parseFloat(latLon[1]);
		setW = Math.min(w, setW);
		setE = Math.max(e, setE);
		setS = Math.min(s, setS);
		setN = Math.max(n, setN);
	}
	return new GLatLngBounds(new GLatLng(setS, setW), new GLatLng(setN, setE));
}


	
	// sets position and zoom level appropriately so that box is visible on the map
	// map = GMap2
	// box = GLatLngBounds
function mhFocusOnBox(map, box) {
	
		// Just for testing purposes
	var lat = box.getCenter().lat();
	var lng = box.getCenter().lng();
		//alert("setting center to "+lat+", "+lng);
	var boxCenter = box.getCenter();
	map.setCenter(boxCenter, 3); // need to zoom in a bit first
	var viewbox = map.getBounds();
	if (!viewbox.containsBounds(box)) {
			//alert("map does NOT contain cov bounds");

			//zoom out to show polygon
		var lastZoomLevel = 9999;
		var zoomLevel = map.getZoom();
		while ((!viewbox.containsBounds(box)) && (zoomLevel != lastZoomLevel)) {
				//alert("too close, zooming out ("+zoomLevel+")");
			lastZoomLevel = zoomLevel;
			map.setCenter(boxCenter, zoomLevel - 1);
			viewbox = map.getBounds();
			zoomLevel = map.getZoom();
		}

			// if map is centered more to the north or more to the south, because
			// of mercator projection, it will appear as though it is not centered.
			// Try to adjust to accomodate this.
		var lastCenter = new GLatLng(-999, -999, true);
		var center = boxCenter;
		while ((!viewbox.containsBounds(box)) && (center != lastCenter) && (center.lat() != 0)) {
			lastCenter = center;
			var lastCenterLat = lastCenter.lat();
			if (lastCenterLat > 0) {
				lastCenterLat += 2;
				if (lastCenterLat > 90) {
					break;
				}
			} else {
				lastCenterLat -= 2;
				if (lastCenterLat < -90) {
					break;
				}
			}
			center = new GLatLng(lastCenterLat, lastCenter.lng());
			map.setCenter(center, zoomLevel);
			viewbox = map.getBounds();
			zoomLevel = map.getZoom();
		}
	} else {
			//alert("map DOES contain cov bounds");

			//TODO Check sufficiently zoomed in for box to be visible -need min 30% of view width
		var bWidth = mhGetBoxWidth(box);
		var bHeight = mhGetBoxHeight(box);
		var vWidth = mhGetBoxWidth(viewbox);
		var vHeight = mhGetBoxHeight(viewbox);
		var lastZoomLevel = 9999;
		var zoomLevel = map.getZoom();
		while (((bWidth / vWidth < 0.3) && (bHeight / vHeight < 0.3)) && (zoomLevel != lastZoomLevel) && (zoomLevel > 1)) {
				//alert("too far away, zooming in ("+zoomLevel+")");

				// zoomed in farther usually gives no data, so set limit
			if (zoomLevel > 6) {
				zoomLevel = 10;
				map.setCenter(boxCenter, zoomLevel);
				return;
			}
			lastZoomLevel = zoomLevel;
			map.setCenter(boxCenter, zoomLevel + 1);
			viewbox = map.getBounds();
			vWidth = mhGetBoxWidth(viewbox);
			vHeight = mhGetBoxHeight(viewbox);
			zoomLevel = map.getZoom();
		}
	}
}
	

	// Returns the width of the box in degrees
	// bounds = GLatLngBounds
function mhGetBoxWidth(bounds) {
	var w = bounds.getSouthWest().lng();
	var e = bounds.getNorthEast().lng();
	if (w > e) {
			//alert("crosses int dateline w="+w+" and e="+e)
		var rtOfIntLine = e + 180;
		var ltOfIntLine = 180 - w;
			//alert("box width = "+( rtOfIntLine + ltOfIntLine));
		return rtOfIntLine + ltOfIntLine;
	}
	return e - w;
}


	// Returns the height of the box in degrees
	// bounds = GLatLngBounds
function mhGetBoxHeight(bounds) { 
	//alert(bounds);
	var s = bounds.getSouthWest().lat();
	var n = bounds.getNorthEast().lat();
	return n - s;
}


	// formulates the proper syntax for a WKT POLYGON
function formulateWKT(south, west, north, east) {	
		// syntax = POLYGON ((N W,N E,S E,S W,N W))
	var string = "POLYGON ((";
	string += north + " " + west + ",";
	string += north + " " + east + ",";
	string += south + " " + east + ",";
	string += south + " " + west + ",";
	string += north + " " + west + "))";
	return string;
}
function goToCov(south, west, north, east, map) {
	var wkt = formulateWKT(south, west, north, east);
	var bounds = jpGetGBoundsForWKT(wkt); // now a GLatLngBounds
	mhFocusOnBox(map, bounds);
}

   
