jQuery( function(){
	zipcodeCompleter.init();
});

var zipcodeCompleter = function(){
	
	var apiUrl = 'http://postcode.oberon.nl/api/?callback=?';
	
	// references to JQ objects of various inputs
	var $zip = null;    
	var $nr = null;
	var $street = null;
	var $city = null;
	
	function init(){
		
		$zip = jQuery('#zip'); 
		$nr = jQuery('#streetnumber');
		$street = jQuery('#street');
		$city = jQuery('#city');
		
		if ( !$zip.length || !$nr.length || !$street.length || !$city.length ){
			// Quit if one of the id's isn't provided. 
			return false;
		}

		$zip.change( doZipcodeRequest );
		$nr.change( doZipcodeRequest );
	}
	
	function doZipcodeRequest(){
		if( $zip.val().length < 6 ){
			return false;
		}
		var params = {zip: $zip.val(), nr: $nr.val() };
		jQuery.getJSON(apiUrl, params, handleZipcodeRequest );
	}	
	
	function handleZipcodeRequest(resp){

		if( resp.error != '0' ){
			return false;
		}
		
		// Users should be able to correct errors. So only fill if fields are empty
		$city.val(resp.city);
		$street.val(resp.street);	
		$zip.val(resp.zip.replace(' ', ''));
	}

	return {
		init: init
	};
}();

