<?php
$xoopsOption['nocommon'] = 1;
require '../../mainfile.php';

error_reporting(0);

$q = (isset($_GET['q']))? $_GET['q'] : "";

$dats = array();
$oq = $q = str_replace("\0","",$q);

if ($q !== "")
{
	$q = addslashes($q);

	$where1 = " WHERE s.`name` LIKE '".$q."%'";
	$where2 = " WHERE (s.`name` LIKE '%".$q."%' AND s.`name` NOT LIKE '".$q."%') OR c.`name` LIKE '".$q."%'";
	$order = " ORDER BY s.`name` ASC";
	$limit = 50;

	mysql_connect(XOOPS_DB_HOST, XOOPS_DB_USER, XOOPS_DB_PASS) or die(mysql_error());
	mysql_select_db(XOOPS_DB_NAME); 
	
	$query = "SELECT Distinct s.`loc`, s.`name`, c.`name` FROM `".XOOPS_DB_PREFIX."_xpweather_station` AS `s` LEFT JOIN `".XOOPS_DB_PREFIX."_xpweather_country` AS `c` ON s.ctry_id = c.ctry_id".$where1.$order." LIMIT ".$limit;
	
	$suggests = $tags = array();
	if ($result = mysql_query($query))
	{
		while($dat = mysql_fetch_row($result))
		{
			$tags[] = '"'.str_replace('"','\"',$dat[1]." [".$dat[2]."]").'"';
		}
	}
	
	$count = count($tags);
	if ($count < $limit)
	{
		$query = "SELECT Distinct s.`loc`, s.`name`, c.`name` FROM `".XOOPS_DB_PREFIX."_xpweather_station` AS `s` LEFT JOIN `".XOOPS_DB_PREFIX."_xpweather_country` AS `c` ON s.ctry_id = c.ctry_id".$where2.$order." LIMIT ".($limit-$count);
		if ($result = mysql_query($query))
		{
			while($dat = mysql_fetch_row($result))
			{
				$tags[] = '"'.str_replace('"','\"',$dat[1]." [".$dat[2]."]").'"';
			}
		}		
	}
}

$oq = '"'.str_replace('"','\"',$oq).'"';
$ret = "this.setSuggest($oq,new Array(".join(", ",$tags)."));";

header ("Content-Type: text/html; charset=UTF-8");
header ("Content-Length: ".strlen($ret));
echo $ret;

?>
