var centerLatitude=40;
var centerLongitude=-100;
var startZoom=3;
var locationZoom=13;
var address = null; 
var lat = null; 
var lng = null;
var locations = null;
//var description="Event location"; 
  


var map;
var geocoder;
//var location;

function init() {
  if (GBrowserIsCompatible()) {
    map=new GMap2(document.getElementById("map"));
	var location=new GLatLng(centerLatitude, centerLongitude);
	var point;
	if (lat!=null && lng !=null && address!=null && lat!='' && lng !='' && address!='') {
		window_content="<div><b>"+address+"&nbsp;&nbsp;</b>"+"<br/><form action=\"http://maps.google.com/maps\" method=\"get\" target=\"_new\"><label for=\"saddr\"><br/>Get directions from:<br/></label><input type=\"text\" name=\"saddr\" id=\"saddr\" size=\"30\" value=\"\" /><input type=\"submit\" value=\"Go\" /><input type=\"hidden\" name=\"daddr\" value=\""+address+"\"><input type=\"hidden\" name=\"hl\" value=\"en\" /></p></form></div>"
		point = new GLatLng(lat,lng);
		marker = new GMarker(point);
		map.setCenter(point, locationZoom);
	    map.addOverlay(marker);
	    marker.openInfoWindowHtml(window_content);
	} else {
    	map.setCenter(location, startZoom);
	}
	
	//locations = [{"lng": -74.607015, "lat": 40.462755}, {"lng": -75.306994, "lat": 40.3691635}, {"lng": null, "lat": null}, {"lng": null, "lat": null}, {"lng": -74.623193, "lat": 40.598909}];

	if (locations!=null) {		
		for (var i = 0; i < locations.length; i++)  { //loop over collection size, creating a point based on each collection element's coordinates
			var point = new GLatLng(locations[i].lat,locations[i].lng);    
			map.addOverlay(new GMarker(point));
		}
	}
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
	
	/*
	//check for existing location and stake it
	showLocation(map);
	
	//clicking remaps the location
	GEvent.addListener(map, "click", function(overlay, latlng) {	
		map.clearOverlays();		
		marker=new GMarker(latlng); 
		document.getElementById("event_marker_lng").value=latlng.lng();
		document.getElementById("event_marker_lat").value=latlng.lat();
		alert("lng: "+document.getElementById("event_marker_lng").value);
		alert("lat: " +document.getElementById("event_marker_lat").value);
		map.addOverlay(marker);
		map.openInfoWindow (latlng,document.createTextNode("Address will show up here"));
	})
	*/
  }
}
/*
function showAddress(address) {
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " not found. Please try again.");
            } else {
              map.setCenter(point, 13);
              var marker = new GMarker(point);
              map.addOverlay(marker);
              //marker.openInfoWindowHtml(address);
            }
          }
        );
      }
}
*/

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
var lat_fld_name;
var lng_fld_name;
var address_fld_name;
var located=null;

function showLocation(address, lat_field_name, lng_field_name, address_field_name) {
	located=null;
	lat_fld_name=lat_field_name;
	lng_fld_name=lng_field_name;	
	address_fld_name=address_field_name;
	geocoder = new GClientGeocoder();
    geocoder.getLocations(address, addAddressToMap);
}

// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address
function addAddressToMap(response) {
  map.clearOverlays();
  if (!response || response.Status.code != 200) {
  	located='no';
    alert("Sorry, we were unable to locate this address. Please try again, or click 'Google Maps' for more detailed search. Once done with the search at Google maps, don't forget to paste the address into the 'address' field of the new event.");
	document.getElementById(lat_fld_name).value=""; //they are already null, this is just a sanity check
	document.getElementById(lng_fld_name).value="";
  } else {
  	located='yes';
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
    marker = new GMarker(point);
	map.setCenter(point, locationZoom);
    map.addOverlay(marker);
    marker.openInfoWindowHtml("<b>"+place.address+"</b>");
	document.getElementById(lng_fld_name).value=place.Point.coordinates[0];
	document.getElementById(lat_fld_name).value=place.Point.coordinates[1];
	document.getElementById(address_fld_name).value=place.address;
  }
}

function verifyLocation (address, lat_field_name, lng_field_name, address_field_name)	{
	alert("verifyLocation, located: "+located);
	if (located!='yes') {
		located=null;
		lat_fld_name=lat_field_name;
		lng_fld_name=lng_field_name;	
		address_fld_name=address_field_name;
		geocoder = new GClientGeocoder();
	    geocoder.getLocations(address, addAddressToPage);
		//waitForLocation();
	}	
}

function addAddressToPage(response) {
  alert("addAddressToPage, located: "+located);
  if (!response || response.Status.code != 200) {
  	located='no';
	alert("located: "+located);
    alert("Sorry, we were unable to locate this address. Please try again, or click 'Google Maps' for more detailed search. Once done with the search at Google maps, don't forget to paste the address into the 'address' field of the new event.");
	document.getElementById(lat_fld_name).value=""; //they are already null, this is just a sanity check
	document.getElementById(lng_fld_name).value="";
  } else {
  	located='yes';
	alert("located: "+located);
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
	document.getElementById(lng_fld_name).value=place.Point.coordinates[0];
	document.getElementById(lat_fld_name).value=place.Point.coordinates[1];
	document.getElementById(address_fld_name).value=place.address;
	alert(document.getElementById(lat_fld_name).value);
  }
}

function waitForLocation(){
	while (located==null){
		pause(50);
	}
}

/*
* This function will not return until (at least)
* the specified number of milliseconds have passed.
* It does a busy-wait loop.
*/
function pause(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}




/*
 function showLocationMarker(map) {
	map.clearOverlays();	
	lng=document.getElementById("event_marker_lng").value;
	lat=document.getElementById("event_marker_lat").value;
	if (lng=="" || lat=="") return;
	latlng=new GLatLng(lat,lng);
	//location=new GLatLng(centerLatitude, centerLongitude);
	marker=new GMarker(latlng); 
	map.addOverlay(marker);
	map.openInfoWindow (latlng,document.createTextNode("Address will show up here"));
}*/

	
/*
function saveMarker(latlng) {
	var request=GXmlHttp.create();
	var lng=latlng.lng();
	var lat=latlng.lat();
	//queryString="?m[lng]=" + lng + "&m[lat]=" + lat;
	alert(queryString);
	request.open('GET', 'create' + queryString, true);
}*/




window.onload=init;
window.onunload="GUnload()";