jQuery( function(){
	zipcodeCompleter.init();
});

var zipcodeCompleter = function(){
	
	var apiProxy = '/proxy.php?action=zip&url=';
	
	// 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 apiUrl = 'http://postcode.oberon.nl/api/';
		apiUrl = apiUrl + '?zip=' + $zip.val();
		apiUrl = apiUrl + '&nr=' + $nr.val();
		var params = {};
		jQuery.getJSON(apiProxy + encodeURIComponent(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
		if( $city.val() == '' ){
			$city.val(resp.city);
		}
		if( $street.val() == '' ){
			$street.val(resp.street);	
		}
		
		$zip.val(resp.zip);
	}

	return {
		init: init
	};
}();

