// Global storage for Location objects
var MBLocations = new Array();

// MapBuilder.net: Location  Definition Class
function MBLocation (Latitude, Longitude, Address, City, State, Zip, Country) {
  this.Latitude = Latitude;
  this.Longitude = Longitude;
  this.Address = Address;
  this.City = City;
  this.State = State;
  this.Zip = Zip;
  this.Country = Country;

  // Create well formatted location address
  this.GetAddress = function() {
    var addressItem = ''; 

    if (this.Address != '') {
       addressItem = this.Address;
    }
    if (this.City != '') {
       addressItem = (addressItem=='') ? this.City : addressItem + ", " + this.City;
    }
    if (this != '') {
       addressItem = (addressItem=='') ? this.State : addressItem + ", " + this.State;
    }
    if (this.Zip != '') {
       addressItem = (addressItem=='') ? this.Zip : addressItem + ", " + this.Zip;
    }
    if (this.Country != '') {
       addressItem = (addressItem=='') ? this.Country : addressItem + ", " + this.Country;
    }

    return addressItem;
  }
}

// global flag
var isIE = false;

// Remove all previuos results from the screen
function clearAll() {
    clearSelect("GeoSuggestList");
    document.getElementById('searchInfo').innerHTML = '';
}

// Empty select list content
function clearSelect(select_name) {
    var select = document.getElementById(select_name);
    while (select.length > 0) {
        select.remove(0);
    }
}

// Add item to select element 
function appendToSelect(select, value, content) {
    var opt;
    opt = document.createElement("option");
    opt.value = value;
    opt.appendChild(content);
    select.appendChild(opt);
}

// Fill Loactions select list with items from the XML document
function buildGeoSuggestList() {
    
    document.getElementById('searchInfo').style.display = 'block';
    //document.getElementById("searchInfo").style.visibility = 'visible';
    
    var select = document.getElementById("GeoSuggestList");
    var errors = req.responseXML.getElementsByTagName("Error");
    // Do we have Error in xml?
    if (errors.length > 0) {
      document.getElementById('searchInfo').innerHTML = "<span style=\"color:red\">Yahoo returned the following error: " + 
        getElementTextNS("", "Message", errors[0], 0) + 
        "</span>";
      document.getElementById('GeoResults').style.display = 'none';
      document.getElementById("GeoSuggest").style.display = 'none';
      //document.getElementById("GeoResults").style.visibility = 'hidden';
      //document.getElementById("GeoSuggest").style.visibility = 'hidden';
      return;
    }

    var items = req.responseXML.getElementsByTagName("Response").getElementsByTagName("Placemark");
    
    /* Get precision attibutes.
    * Looks like yahoo return the same 'precision' attribute for multiple "Result" element
    */
    var precision = items[0].getAttribute('precision');

    // loop through <Result > elements, and add each nested to the "Suggest" drop down
    for (var i = 0; i < items.length; i++) {

        // Craete location object and store it in the array
        MBLocations[i] = new MBLocation
        (
          getElementTextNS("", "Latitude", items[i], 0),
          getElementTextNS("", "Longitude", items[i], 0),
          getElementTextNS("", "Address", items[i], 0),
          getElementTextNS("", "City", items[i], 0),
          getElementTextNS("", "State", items[i], 0),
          getElementTextNS("", "Zip", items[i], 0),
          getElementTextNS("", "Country", items[i], 0)
        );
        //Add node to the drop down
        appendToSelect(select, i, document.createTextNode(MBLocations[i].GetAddress()));
    }
    
    // Dump geocoding results
    // Show first available result
    DumpGeoInfo('0');
    
    // Do we have some suggestions from Yahoo?
    if (items.length > 1) {
      document.getElementById('searchInfo').innerHTML = 'We suggest you to select the most suitable geocoding result:';
      document.getElementById("GeoSuggest").style.display = 'block';
      //document.getElementById("GeoSuggest").style.visibility = 'visible';
    }
    else {
      document.getElementById('searchInfo').style.display = 'none';
      document.getElementById("GeoSuggest").style.display = 'none';
      //document.getElementById('searchInfo').style.visibility = 'hidden';
      //document.getElementById("GeoSuggest").style.visibility = 'hidden';
    }
}

// AJAX call to make geocoding
function GeoCode(address) {
  if (trim(address)=='') {
    alert ("Please, specify address for geocoding.")
    return;
  }

  // Do not disable text entry field
  //document.LocationSearchForm.LocationSearch.setAttribute("readonly","readonly");
  //document.getElementById('searchInfo').style.display = 'block';
  document.getElementById('searchInfo').innerHTML = 'Searching...';

  //loadXMLDoc("./Service/geocode.google.php?address=" + encode(address));
  	var gGeocoder = new GClientGeocoder();
	gGeocoder.getLocations(
		address,

		GEvent.callback(this, function(response) 
		{
			if (!response || response.Status.code != 200) {
				//alert("\"" + address + "\" not found. Error code: " + response.Status.code);
				document.getElementById('searchInfo').innerHTML = "\"" + address + "\" not found. Error code: " + response.Status.code;
			} else {
			    document.getElementById('searchInfo').style.display = 'none';
			    document.getElementById("GeoSuggest").style.display = 'none';

				place = response.Placemark[0];
				accuracy = place.AddressDetails.Accuracy;
				document.getElementById("GeoResults").style.visibility = 'visible';
  
				// Center Map and show marker
				showMarker(place.Point.coordinates[1], place.Point.coordinates[0], '3', "x", document.getElementById("GeoResults").innerHTML);
				// Set an Address
				var a = '';
				var c = '';
				var z = '';
				var s = '';
				var country = '';

				if (place.AddressDetails && place.AddressDetails.Country) {
					if (place.AddressDetails.Country.AdministrativeArea) {
						if (place.AddressDetails.Country.AdministrativeArea.Locality) {
							if (place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare) {
								var a = place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName || '';
							}
							var c = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName || '';
							var z = place.AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber || '';
						}
						var s = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName || '';
					}
					var country = place.AddressDetails.Country.CountryNameCode || '';
				}
				SetAddress(a, c, z, s, country);
			}
		})
	);

}

// Show geo information received from Yahoo for the given ID of MBLocation object
function DumpGeoInfo(id) {
  /* Do not show resultson the screen. MapBuilder will display results using SetAddress method 
  document.getElementById("GeoResults").innerHTML = 
  "<b>Geocode Result</b><br \>" +
  "Latitude: " + MBLocations[id].Latitude  + "<br \>" +
  "Longitude: " + MBLocations[id].Longitude + "<br \>" +
  "Address: " + MBLocations[id].Address + "<br \>" +
  "City: " + MBLocations[id].City + "<br \>" +
  "State: " + MBLocations[id].State + "<br \>" +
  "Zip: " + MBLocations[id].Zip + "<br \>" +
  "Country: " + MBLocations[id].Country;
  */

  //document.getElementById("GeoResults").style.display = 'block';
  document.getElementById("GeoResults").style.visibility = 'visible';
  
  // Center Map and show marker
  showMarker(MBLocations[id].Latitude, MBLocations[id].Longitude, '3', "x", document.getElementById("GeoResults").innerHTML);
  // Set Address
  SetAddress(MBLocations[id].Address, MBLocations[id].City, MBLocations[id].Zip, MBLocations[id].State, MBLocations[id].Country);

}

// Get address, put it on the form and geocode
function ForceGeoCode(address) {
  document.LocationSearchForm.LocationSearch.value = address;
  GeoCode(address);
}

// Show marker with label and text for mouse click event
function showMarker(Latitude, Longitude, Zoom, Label, Text) {
  // Create a lat/lon object
  Latitude = parseFloat(Latitude);
  Longitude = parseFloat(Longitude);

  var point = new GPoint(Longitude, Latitude); 

  // Set empty values
  ResetLocationForm();
  map.clearOverlays();
  // Load user's locations
  LoadLocations();

  markerforremove = new GMarker(point, iconpointer);
  map.addOverlay(new GMarker(point, iconpointer));
  //Center at this location
  map.setCenter(new GLatLng(Latitude, Longitude));
  document.F.latitude.value = Latitude;
  document.F.longitude.value = Longitude;

}


