$(document).ready(function() {
	// Get reference to zip and city input fields
	var zipElement = $('.postnr div input');
	var cityElement = $('.by div input');
	
	// Listen to the zip input' keyup event. If it's length is greater than four, make the ajax call
	zipElement.keyup(function() {
                if($(this).val().length == 4) {
                    // Build the service url
		    var serviceUrl = "http://geo.oiorest.dk/postnumre/" + $(this).val() + ".json";
                    ajaxCall(serviceUrl);
                }
                else {
		    // If the length of zip input is less than four, reset the city field
                    cityElement.val("");
                }
        });
	
	// ajax call to get the city name corresponding to a given zipcode
	function ajaxCall(uri) {
                $.ajax({
                   url: uri,
                   dataType: 'jsonp',
                   success: function(data){
                        cityElement.val(data.navn);
                    }
		});
        }
});
