var map = null;
var geocoder = null;

function getAddress(overlay, latlng) {
	if (latlng != null) {
		address = latlng;
		geocoder.getLocations(latlng, showAddress);
	}
}

var geocoder = new GClientGeocoder();

function showAddress(address, vform, country, stateprov, city, coordinates) {
	val_form = vform;
	val_country = country;
	val_stateprov = stateprov;
	val_city = city;
	val_coordinates = coordinates;
	geocoder.getLatLng(
		address,
		function(point) {
			if (!point) {
				alert(address + ": Invalid Zip/Postal Code");
			}
			else {
				getlocationinfo(point);
			}
		}
	);
}

function getlocationinfo(obj) {
	geocoder.getLocations(obj, setinfo);
}

function setinfo(obj) {
	var rescountrycode="";
	var rescountry="";
	var resprov="";
	var rescity="";
	if (obj.Status.code == 602) {
	}
	else {
		n=obj.Placemark.length
		for (i=0 ; i < n ; i++) {
			var place = obj.Placemark[i];
			if (place.AddressDetails != null) {
				var niveau =place.AddressDetails.Accuracy
				if(place.AddressDetails.Country.AdministrativeArea != null) {
					rescountry=place.AddressDetails.Country.CountryName
					rescountrycode=place.AddressDetails.Country.CountryNameCode
					resprov = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName 
					if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea != null) {
						if(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality  != null) {
							rescity = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName 
						}
					}
					else {
						if (place.AddressDetails.Country.AdministrativeArea != null) {
							if (place.AddressDetails.Country.AdministrativeArea.Locality != null){
								rescity = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName
								if(place.AddressDetails.Country.AdministrativeArea.Locality.Country != null) {
									rescountrycode=place.AddressDetails.Country.AdministrativeArea.Locality.Country.CountryNameCode
								}
							}
						}
					}
				}
				if ((rescountry != "" ) && (rescity != "" ) && (resprov != "" )) {
					i=n;
					document.forms[val_form].elements[val_country].value = rescountrycode;
					document.forms[val_form].elements[val_stateprov].value = resprov;
					document.forms[val_form].elements[val_city].value = rescity;
					document.forms[val_form].elements[val_coordinates].value = obj.name;
				}
			}
		}
	}
}

