function valid_postal_code_digits(digits)
{
  if ( digits.match(/^[0-9]{4} ?[a-zA-Z]{0,2}$/) )
  {
    return true;
  }
  return false;
}

function request6pp(postcode, city_el)
{
  $.getJSON(
    'http://6pp.kvdb.net/services/lookup?jsonp=?',
    { postcode: postcode.match(/^[0-9]{4}/)[0], tg_format: 'json'},
    function(data) 
    {
      if ( data['result'].length == 1 )
      {
        $(city_el).attr('value',data['result'][0].city);
      }
    }
  );
}

$(document).ready(
	function() {
	  var postal_code_digits  = $('#advertiser_postal_code');
	  var address_city        = $('#advertiser_city');
	
	  if (postal_code_digits) {
	    postal_code_digits.bind('keyup',function(){
	      if ( valid_postal_code_digits(this.value) )
	      {
	        var postal_code = this.value;
	        request6pp(postal_code, address_city);
	      }
	    });
	  }
	}
) 
