// This key only works from the kvdb.net domain, for demo purposes.
// Replace this auth_key with your own.
var pro6pp_auth_key = "n5SEkGlaFzbkWDfj";

// Create closure to keep namespace clean and hide implementation.
(function($) {
	
	var jsonscript   = 'proxy6pp.php?';
	var postcode     = '.postcode';
	var street       = '.street';
	var housenumber  = '.housenumber';
	var hintClass    = 'bw6pp_help';
	var hintText     = 'Er kon geen geldig resultaat voor de opgegeven postcode gevonden worden.';
	var city         = '.city';
	var orgStreet    = '';
	var cache        = {};
	var resultsFound = null;
	
	$.fn.bw6pp = function( fieldNames ) {
		var parent_obj = this;
		
		// .extend() would be nice here
		if ( fieldNames ) {
			if ( fieldNames.postcode ) { postcode = fieldNames.postcode; }
			if ( fieldNames.street ) { street = fieldNames.street; }
			if ( fieldNames.housenumber ) { housenumber = fieldNames.housenumber; }
			if ( fieldNames.city ) { city = fieldNames.city; }
			if ( fieldNames.hintClass ) { hintClass = fieldNames.hintClass; }
			if ( fieldNames.hintText ) { hintText = fieldNames.hintText; }
		}
		
		// this.find returns an array
		if(this.find(postcode).length > 0 ){
			// disable the fields that are populated automatically
			if(this.find(postcode).val() =="" && this.find(street).val() == "" && this.find(city).val() == "" ) {
				disableFields();
			}
			
			this.find(postcode).keyup(function() {
				autocomplete(parent_obj);
			});
		}
		// store the original street object
		orgStreet = $(street);
		
		// allow chaining
		return this;
	};
	
	function autocomplete(obj){
		var postcodeRequest = $(obj).find(postcode).val();
		if (postcodeRequest.match(/[\d]{4}\s?[a-zA-Z]{2}/) ){
			var base = document.getElementsByTagName("base"); 
			var url = base[0].href + jsonscript;
			url += 'postcode='+escape(postcodeRequest);
			
			if ( $(housenumber).val() != "" && $(housenumber).val() != "undefined" ) {
				url += '&housenumber=' + escape( $(housenumber).val() );
			}
			
			getCachedObj(obj, url, parseJsonToForm);
		}
	}
	
	function getCachedObj(obj, url, callback){
		key = escape(url);
		if ( cache.hasOwnProperty(key) ) {
			callback(obj, cache[key]);
		} else {
			$.getJSON(url, function(data){
				cache[key] = data;
				callback(obj, data);
			});
		}
	}
	
	function disableFields(){
		$(street).attr("disabled",true);
		$(city).attr("disabled",true);
	}
	
	function enableFields(){
		$(street).attr("disabled",false);
		$(city).attr("disabled",false);
	}
	
	function parseJsonToForm(obj, data ){
		if ( data.status == 'ok' ) {
			resultsFound = true;
			// remove the optional helptext
			if ( $(postcode).parent().html().indexOf(hintText) > 0 ) {
				$(postcode).parent().find('span').first().remove();
			}
			if ( data.results.length == 1 ) {
				// fill street and city with the result
				$(city).val(data.results[0].city);
				$(street).after('<input type="text" id="'+street.substring(1)+'" name="'+$(street).attr('name')+'" class="'+ $(street).attr('class')+'" />');
				$(street).remove();
				$(street).val(data.results[0].street);
			} else {
				// status = ok and results.length > 1: create a dropdrown
				// unlikely that a postcode exists in two cities
				$(city).val(data.results[0].city);
				$(city).removeClass('error');
				// dropdown for the streets
				var selectElement = '<select id="' + street.substring(1) + '" name="' + $(street).attr('name')+ '" class="'+ $(street).attr('class')+'" >';
				// remove the original element.Store it for restoring purposes
				for( var i=0; i < data.results.length ; i ++) {
					selectElement += '<option value="'+ data.results[i].street+'">'+ data.results[i].street +'</option>';
				}
				selectElement += '</select>';
				var elementWidth = $(street).css('width');
				$(street).after(selectElement);
				$(street).remove();
				$(street).css('width', elementWidth);
				$(street).removeClass('error');
			}
			// re-enable the fields
			enableFields();
		} else {
			resultsFound = false;
			// an error was received
			// add a hint to the form
			$(postcode).parent().find('.helptext').remove();
			
			if ( $(postcode).parent().html().indexOf(hintText) < 0 ) {
				$(postcode).after('<span class="' + hintClass+ '"><br />'+ hintText +'</span>');
			}
			// re-enable the fields
			enableFields();
		}
		
		// attach a callback function on the submit if no results were found!
		if ( resultsFound == false ) {
			$(obj).submit(function(){
				var postcodeRequest = $(obj).find(postcode).val();
				if (postcodeRequest.match(/[\d]{4}\s?[a-zA-Z]{2}/) ){
					var base = document.getElementsByTagName("base"); 
					var url = base[0].href + jsonscript;
					url += 'postcode='+escape(postcodeRequest);
					
					if ( $(street).val() != "" && $(street).val() != "undefined" ) {
						url += '&street=' + escape( $(street).val() );
					}
					
					if ( $(housenumber).val() != "" && $(housenumber).val() != "undefined" ) {
						url += '&housenumber=' + escape( $(housenumber).val() );
					}
					
					url += '&feedback=1';
					$.getJSON(url);
				}
				//return false;
			});
		}
	}

})(jQuery);

