$(document).ready(function() {

    var $pc     =  $('#postal_code');
    var $house  =  $('#house');
    var $street =  $('#street');
    var $city   =  $('#city');
    var $address=  $('#address');
    
    $pc.attr('autocomplete', 'off');
    $house.attr('autocomplete', 'off');

    function getAddress() {
      $.blockUI();
      $address.show();

      var postal_code = $pc.val();
      var house = $house.val();
      $.ajax({
        type: "POST",
        url: "../Includes/autocomplete_address/address.php",
        dataType: "html",
        data: "postal_code="+postal_code+"&house="+house,
        success: 
        function(response){
          var adres=response.split("|");

          $street.val(adres[0]);
          $city.val(adres[1]);
          
          $.unblockUI();
        },
        error:
          function() {
            $.unblockUI();
          }
      });
    }

    function validPostalCode() {
      var postal_code  = /^\d{4}[\s-]?[a-zA-Z]{2}$/;
      return $pc.val().match(postal_code);
    }

    $.fn.pcAction = function() {
      if ($house.val() && validPostalCode()) {
        getAddress();
      }
    };

    $house.bind('keyup', function() {
      if ($house.val().match(/^[a-zA-Z].*$/)) {
        alert('Vul in dit veld alleen uw postbus- of huisnummer in.');
        $house.val('');
      }
    });

    $('#country').bind('change', function() {
      $('#address').show();
    });

    $house.bind('change', function() {
      if ($(this).val() && validPostalCode()) { getAddress(); }
    });

    $pc.bind('keyup', function() {
      if ($(this).val().length > 5) {
        $(this).pcAction();
      }
    });

  //  return this;
  });

  function disableAutoPC(pc, house, address) {
    $(pc).unbind();
    $(house).unbind();
    $(address).show();
  }