  $(document).ready(function () {
    $('#country').change(function () {
      getStates( $(this).attr('value') );
    });
    $('#state').change(function () {
      getCities( $(this).attr('value') );
    });    
  });
  
  function getCountries(id) {
    $.getJSON('./controllers/countries.php', {"query":"countries", "id":id}, function (obj) {
      var options = '';
      
      for(key in obj) {
        if(options == '')
          getStates(key);
        
        options += '<option value="' + key + '">' + obj[key][0] + '</option>';
      }
      
      $('#country').html(options);
 
      $('#cities').show();
      $('#top_locations, #map').hide();
    });
  }

  function getStates(id) {
    $.getJSON('./controllers/countries.php', {"query":"states", "id":id}, function (obj) {
      var options = '';
      
      for(key in obj) {
        if(options == '') {
          $('.state_title').html(obj[key][0]);
          
          getCities(key);
        }
        
        options += '<option value="' + key + '">' + obj[key][0] + '</option>';
      }
      $('#state').html(options);
    });
  }

  function getCities(id, sorting) {
    $.getJSON('./controllers/countries.php', {'query':'cities', 'id':id, 'sorting':sorting}, 
    function (obj) {
      var cities = '';
      
      for(key in obj) {
//          href = obj[key][1] > 0 ? '/index.php?page=landing&id=' + key : '#';
//          href = obj[key][0] ? '/index.php?page=landing&id=' + key : '#';
          cities += obj[key][0] + ' (' + obj[key][1] + ')\n';

      }

      $('#required_cities').html(cities);
    });
  }
  
  function getSortedCities(sorting) {
    var state = $('#state option:selected').attr('value');
    
    getCities(state, sorting);
  }
