function closeAddressOptions() {
   $('#addressoptions').hide();
   return false;
}

function selectAddressOption(address) {
   var split = address.split(',');
   if (split.length == 3) {
      $('#id_address1').val($.trim(split[0]));
      $('#id_address2').val($.trim(split[1]));
      $('input[name="city"]').val($.trim(split[2]));
   } else if (split.length == 2) {
      $('#id_address1').val($.trim(split[0]));
      $('input[name="city"]').val($.trim(split[1]));
   }
}

function __start_address_timeouter() {
   setTimeout(function() {
      if (_postcode_searching) {
   $('#please-wait:visible').hide();
         _postcode_searching = false;
         $('#addressoptions:visible').hide();
         $('#address-lookup-failed').show();
         $('#address_search_button:visible').hide();
         setTimeout(function() {
            $('#address-lookup-failed:visible').hide();
         }, 5*1000);
         
      }
   }, 10*1000);
}


function __find_address_options(postcode) {
   __start_address_timeouter();

   $.getJSON('FindUKAddress_json', {postcode:postcode}, function(res) {
      if (res.length) {
   $('#please-wait:visible').hide();
   $('#addressoptions').show();

   $('select', $('#addressoptions')).remove();

   var option_container = $('<select></select>').bind('change', function() {
      if (this.options[this.selectedIndex].value) {
         selectAddressOption(this.options[this.selectedIndex].value);
         $('#addressoptions').hide();
         $('#address_search_button').hide();
      }
   });
   $('#addressoptions').append(option_container);
   option_container.append($('<option></option>').attr('value', '').text("Select the best match:")
      );


   }
   for (var i=0,len=res.length; i<len; i++) {
      option_container.append($('<option></option>').attr('value', res[i]).text(res[i])
         );
   }

   _postcode_searching = false;
});
}


var _postcode_searching = false;

$(function() {
   $('input[name="postcode"]').bind('change', function() {
      if ($(this).val()) {
         // format the postcode
         $.getJSON('FormatUKPostcode_json', {postcode:$(this).val()}, function(res) {
            if (res.postcode && $('input[name="postcode"]').val() != res.postcode)
              $('input[name="postcode"]').val(res.postcode);
            
         });
      }
   }).bind('keyup', function() {
      $('#address_search_button:hidden').show().bind('click', function() {
         if (!_postcode_searching) {
            $('#please-wait:hidden').show();
            _postcode_searching = true;
            __find_address_options($('input[name="postcode"]').val());
            
         }
      });
      // commented out so you can search multiple times
      //$(this).unbind('keyup');
   });
});


