$(
function()
{
	$('.ac_postcode').keyup
	(
	function(e)
	{
		$.ajax
		(
		{
			type: 'POST',
			url: '/js/adres.php',
			data: 'postcode='+$(this).attr('value'),
			success: function(data, status)
			{
				if( data )
				{
					var o = JSON.parse( data );
					if( o.result )
					{
						var i = 0;
						for( var j=0; j<$.find(".ac_postcode").length; j++ )
						{
							if( $.find(".ac_postcode")[j] == e.currentTarget )
							{
								i = j;
							}
						}

						if( o.result.length == 1)
						{
							$.find(".ac_plaats")[i].value = o.result[0]['city'];
							//$.find(".straat")[i].value = o.result[0]['street'];

							var textField = document.createElement('input');
							textField.type = 'text';
							textField.name = $.find(".ac_straat")[i].name;
							textField.id = $.find(".ac_straat")[i].id;
							textField.className = $.find(".ac_straat")[i].className;
							textField.value = o.result[0]['street'];

							var inputID = $.find(".ac_straat")[i].id;
							$('#'+inputID).replaceWith(textField);
						}
						else if( o.result.length > 1)
						{
							$.find(".ac_plaats")[i].value = o.result[0]['city'];
							var sel = document.createElement('select');
							sel.name = $.find(".ac_straat")[i].name;
							sel.id = $.find(".ac_straat")[i].id;
							sel.className = $.find(".ac_straat")[i].className;

							for( var p = 0; p<o.result.length; p++ )
							{
								sel.options[p] = new Option(o.result[p]['street'], o.result[p]['street']);
							}

							var inputID = $.find(".ac_straat")[i].id;
							$('#'+inputID).replaceWith(sel);
						}
					}
				}
			}
		}
		);
	}
	)
}
)
