var map;
var geocoder;
var marker;

function mapInit() {
      if (!GBrowserIsCompatible()) return;

        map = new GMap2(document.getElementById("gmap"));
	geocoder = new GClientGeocoder();

	// if event has location, put marker there
	if (eloc) {
		var pt = new GLatLng(eloc.lat,eloc.lon);
        	map.setCenter(pt, 14);
        	marker = new GMarker(pt);
        	map.addOverlay(marker);
	        GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(eloc.address, { maxWidth: 200 } ); } );
	} else {
		map.setCenter(new GLatLng(city.lat,city.lon), parseInt(city.zoom));
	}
	map.savePosition();

  	map.addControl(new GSmallMapControl())
	map.addControl(new GMapTypeControl());

  	//map.setMapType(G_MAP_TYPE);
	map.enableScrollWheelZoom();
	map.enableContinuousZoom();
}
function checkAdd(f, noadd) {
	if (!f) f = showAdd;
	var a,c,s,z,l;
	c = $('city').value;
	s = $('state').value;
	a = $('address').value;
	z = $('zip').value;
	l = $('location').value;

	if (!(l || c || a || s || z)) {
		alert("You must fill in the Venue, Address, City, State, and/or Zip");
		return;
	}

	var address = c+' '+s+' '+z;
	/*
	if (l && !a) 
		address = l+' '+address;
	else 
	*/
	if (!noadd) address = a+' '+address;
		
	geocoder.getLocations(address, f);
}
function showAdd(res) {
      //console.log(res);
      if (res['Status'].code != '200') {
        alert(res.name + " not found");
      } else {
        if (marker) map.removeOverlay(marker);
        var m = res.Placemark[0];
	var cs = m.Point.coordinates;
	var pt = new GLatLng(cs[1],cs[0]);
        map.setCenter(pt, 14);
        marker = new GMarker(pt);

        map.addOverlay(marker);
        GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(m.address, { maxWidth: 200 } ); } );

	var d = m.AddressDetails;

	// Set the GPS fields
	$('GpsRes').value = d.Accuracy;	
	$('Latitude').value = cs[1];	
	$('Longitude').value = cs[0];	

	// Fill in the address fields
	var d = d.Country.AdministrativeArea;
	
	// State
	var o = $('state');
	var n = d.AdministrativeAreaName;
	//if (!o.value && n) o.value = n;
	if (n) o.value = n;

	// City
	if (d.SubAdministrativeArea) d = d.SubAdministrativeArea;
	o = $('city');
	d = d.Locality;
	if (!d) return;
	n = d.LocalityName;
	//if (!o.value && n) o.value = n;
	if (n) o.value = n;
	
	// Zip
	o = $('zip');
	if (d.PostalCode) {
		n = d.PostalCode.PostalCodeNumber;
		//if (!o.value && n) o.value = n;
		if (n) o.value = n;
	}

	// Address
	if (d.Thoroughfare) {
		o = $('address');	
		n = d.Thoroughfare.ThoroughfareName;
		//if (!o.value && n) o.value = n;
		if (n) o.value = n;
	}

      }
}

