$(document).ready(
  function() {
    $('#id_city_name').keyup(
      function() {
        getCities( $(this).val() );
      }
    );

    $('#results').hide();
  }
);

function getCities(cityName) {
  var r = $('#results');

  //special case: the user deletes the letters with backspace until none is left
  if (cityName=='') {
    r.html('').hide();
    return;
  }

  if (cityName.length > 1)
  {
    var url = "/city_search";
    var params = {q : cityName};
  
  	$.getJSON(url, params, 
      function(json){ displayResults(json); }
    );
  }
}

function displayResults(json) {
  var r = $('#results');
  r.html(''); //clear the div
  r.show();
  var rlen = json.length;
  var max = 10;
  if (rlen < max) { max = rlen; }

  for(i=0; i<max; i++) {
    r.html(r.html() + "<div class='result' id='" + json[i].pk + "' onclick=\"selectCity( $(this).attr('id'), $(this).text() );\">" + json[i].fields.name + "</div>");
  }
}

function selectCity(id, name) {
  $('#id_city_pk').val(id);
  $('#id_city_name').val(name);
  $('#results').html('').hide();
}
