<?php 

$country = $tools->keyGlobals('country', 0);
$region = $tools->keyGlobals('region', 0);
$city = $tools->keyGlobals('city', 0);
$type = $tools->keyGlobals('type', 0);
$return = $tools->keyGlobals('r', 'get', 'city');
$search = $tools->keyGlobals('q', 0);

if ($type == 'json') {
    $sortWhere = array();
    
    if (!preg_match('/^.{1}/us', $search)) { 
        $search = iconv("windows-1251", "utf-8", $search); 
    }
    
    if ($country) {
        $sortWhere[] = " AND c.country_id = '" . (int) $country . "'";
    }
    
    $json = null;
    $where = implode('', $sortWhere);
    
    $q = mysql_query("SELECT c.*, r.name AS regionName, s.name AS countryName
                      FROM `city` AS c
                      LEFT JOIN region AS r ON c.region_id = r.region_id
                      RIGHT JOIN country AS s ON c.country_id = s.country_id
                      WHERE c.name like '" . my_esc($search) . "%' $where");

    while ($post = mysql_fetch_assoc($q)) {
        $json[] = array('city' => $post['city_id'], 
                        'region' => $post['region_id'], 
                        'country' => $post['country_id'], 
                        'name' => $post['name'],
                        'regionName' => $post['regionName'],
                        'countryName' => $post['countryName'],
                  );
    }  
    
    echo json_encode($json ? $json : array());
    exit;
}

if ($country) {
    $country = mysql_fetch_assoc(mysql_query("SELECT * FROM country WHERE country_id = " . (int) $country));
}

if ($region) {
    $region = mysql_fetch_assoc(mysql_query("SELECT * FROM region WHERE region_id = " . (int) $region));
}

if ($city) {
    $city = mysql_fetch_assoc(mysql_query("SELECT * FROM city WHERE city_id = " . (int) $city));
    
    if (!isset($location[$return])) {
        if (is_file('ini/redirect.'.$return.'.ini')) {
            $loc = parse_ini_file('ini/redirect.'.$return.'.ini');
            $location = array_merge($location, $loc);
        }
    }
    
    if ($city['city_id'] && isset($location[$return])) {
        if (isset($user)) {
            mysql_query("UPDATE user SET ank_city = '$city[name]' WHERE id = '$user[id]' LIMIT 1");
        }
        
        header('Location: ' . $tools->get_amp_request($location[$return], 'city=' . $city['city_id']));
        exit;
    }
}

$set['title'] = __('Местоположение');
require H.'sys/inc/thead.php';
title();
aut();

if (!$country) {
    ?>
    <div class="mess">
    <b><?= __('Выберите вашу страну')?></b>
    </div>
    <?php
    $q = mysql_query("SELECT * FROM country");
    
    while ($post = mysql_fetch_assoc($q)) {
        $i++;
        ?>
        <div class="<?php echo ($i % 2 ? 'nav1' : 'nav2'); ?>">
          <a href="?func=<?= $func?>&amp;r=<?= $return?>&amp;country=<?= $post['country_id']?>"><img src="/style/flags/<?= $post['short']?>.gif" class="icon" /> <?= __($post['name'])?></a>
        </div>
        <?php
    }  
}

elseif (!$region && !$search) {
    
    ?>
    <div class="mess">
      <img src="/style/flags/<?= $country['short']?>.gif" class="icon" /> <b><?= __($country['name'])?></b> &raquo; 
      <a href="?func=<?= $func?>&amp;r=<?= $return?>"><?= __('Другая страна')?></a>
    </div>
    
    <div class="nav2">
      <form action="?" method="GET">
        <input type="hidden" name="func" value="<?= $func?>">
        <input type="hidden" name="r" value="<?= $return?>">
        <input type="hidden" name="country" value="<?= $country['country_id']?>">
        <input type="search" name="q" placeholder="<?= __('Введите город')?>" value="" onkeyup="citySearch(this)"/>
        <button type="submit"><?= __('Искать')?></button>
      </form>
    </div>
    <?
    $q = mysql_query("SELECT * FROM region WHERE country_id = " . $country['country_id']);
    
    while ($post = mysql_fetch_assoc($q)) {
        $i++;
        ?>
        <div class="<?php echo ($i % 2 ? 'nav1' : 'nav2'); ?>">
          <a href="?func=<?= $func?>&amp;r=<?= $return?>&amp;country=<?= $post['country_id']?>&amp;region=<?= $post['region_id']?>"><?= $post['name']?></a>
        </div>
        <?
    }  
}

elseif (!$city) {
    if (!preg_match('/^.{1}/us', $search)) { 
        $search = iconv("windows-1251", "utf-8", $search); 
    }
    
    if ($search) {
        $where = "c.name like '" . my_esc($search) . "%'";
    } else {
        $where = "c.region_id = " . $region['region_id'];
    }
    ?>
    <div class="mess">
      <? if (!$search) { ?>
      <b><?= __($region['name'])?></b> &raquo;
      <a href="?country=<?= __($country['country_id'])?>"><?= __('Другой регион')?></a>
      <? } else { ?>
      <form action="?" method="GET">
        <input type="hidden" name="func" value="<?= $func?>">
        <input type="hidden" name="r" value="<?= $return?>">
        <input type="hidden" name="country" value="<?= $country['country_id']?>">
        <input type="search" name="q" placeholder="<?= __('Введите город')?>" value="<?= text($search)?>" onkeyup="citySearch(this)"/>
        <button type="submit"><?= __('Искать')?></button>
      </form>
      <? } ?>
    </div>
    
    <?
    $q = mysql_query("SELECT c.*, r.name AS regionName
                      FROM `city` AS c
                      LEFT JOIN region AS r ON c.region_id = r.region_id
                      WHERE $where");

    while ($post = mysql_fetch_assoc($q)) {
        $i++;
        ?>
        <div class="<?php echo ($i % 2 ? 'nav1' : 'nav2'); ?>">
        <a href="?func=<?= $func?>&amp;r=<?= $return?>&amp;country=<?= $post['country_id']?>&amp;region=<?= $post['region_id']?>&amp;city=<?= $post['city_id']?>"><b><?= $post['name']?></b> (<?= $post['regionName']?>)</a>
        </div>
        <?
    }  
}
?>
<script>
function citySearch() {
    var sCity = $("input[name='q']").val();
    
    if (sCity.length >= 1) {
        $("#search-result").html('<div class="list-group-item loading"></div>');
        
        $.getJSON('?country=<?= $country['country_id']?>&q=' + sCity + '&type=json', function(data) {
            var count = $(data).length;
            var html = '';
            
            if (count > 0) {
                for(i = 0; count > i; i++) {
                    html += '<div class="nav2"><a href="?func=<?= $func?>&amp;r=<?= $return?>&amp;country=' + data[i].country + '&amp;region=' + data[i].region + '&amp;city=' + data[i].city + '"><b>' + data[i].name + '</b> (' + data[i].countryName + ', ' + data[i].regionName + ')</a></div>';   
                }             
            } else {
                html = '<div class="mess">Ничего не найдено</div>'
            }
            
            $("#search-result").html(html);
        });          
    }

}
</script>