<?php /*>*/

// deleted a line here which includes some global vars referenced below.

/* open up the database */
if (!($con = mysql_connect($db_host_port,$db_user,$db_pwd)))
{
  die('could not connect: ' . mysql_error());
}
mysql_select_db($db_name, $con);

// including the "get" handling so that this script can be called with url args for testing, e.g.:
// location_lookahead.php?s=iceland

foreach ($_GET as $key => $value) {
  switch ($key) {
  case "search":
    $name = $value;
    break;
    
  case "s":
      $name = $value;
      break;
  }
}

foreach ($_POST as $key => $value) {
  switch ($key) {
  case "search":
    $name = $value;
    break;
    
  case "s":
    $name = $value;
    break;
  }
}

$num_rows = 10;
$geo_names_query = "http://ws.geonames.org/search?name=".urlencode($name)."&maxRows=$num_rows&style=full";
$response = file_get_contents($geo_names_query);

if ($response)
{
  $parsed_xml = simplexml_load_string($response);
  
  echo "<ul class=\"autocompleter\">";
  for($i = 0; $i<$num_rows; $i++) {
    if($parsed_xml && $parsed_xml->geoname[$i]) {
      $return_name = $parsed_xml->geoname[$i]->name;
      $lat = $parsed_xml->geoname[$i]->lat;
      $lng = $parsed_xml->geoname[$i]->lng;
      $countrycode = $parsed_xml->geoname[$i]->countryCode;
      $countryname = $parsed_xml->geoname[$i]->countryName;
      $fcl = $parsed_xml->geoname[$i]->fcl;
      $fcode = $parsed_xml->geoname[$i]->fcode; 
      $fid = $parsed_xml->geoname[$i]->geonameId; 
      $adminName1 = $parsed_xml->geoname[$i]->adminName1; 
      
      $desc = "";
      
      // geonames_features is simply a replication of the geonames codes
      // as described here: http://www.geonames.org/export/codes.html
      $query = "select * from geonames_features where fcode = '$fcode'";
      $result = mysql_query($query);
      
      while ($row = mysql_fetch_array($result)) {
	$desc = $row['short_desc'];
      }
      
      if(!($adminName1 == "")){$countryname = $adminName1.", ".$countryname; }
      
      if(!$countryname || $countryname == ""){
	echo "<li class=\"autocompleter\" id=\"$fid\">$return_name<span class=\"informal\"> (<i>$desc</i>)</span></li>";
      }
      else {
	echo "<li class=\"autocompleter\" id=\"$fid\">$return_name<span class=\"informal\"> (<b>$countryname</b>, <i>$desc</i>)</span></li>";
      }
    }
  }
  echo "</ul>";
}

?>







