$j(function(){

  $j("input#edit-postalCode, input#edit-step2-postalCode").blur(function(){

    if ( $j("select#edit-townSelect, select#edit-step2-townSelect").val() == 0
        && $j("input#edit-postalCode, input#edit-step2-postalCode").val().length == 5
        && $j("select#edit-townSelect, select#edit-step2-townSelect").children().length == 1
        ){
      getTownList();
    }
  })

  $j("input#edit-postalCode, input#edit-step2-postalCode").keyup(function(){
      if ($j(this).val().length == 5){
            getTownList();
      }
  })

  $j("select#edit-country").change(function(){
    $j.get("/jquery/hasPostalReference/"+$(this).val(),{}, function(j){
      if (j==1) {
        getTownList();
        $j("select#edit-townSelect, select#edit-step2-townSelect").removeAttr("disabled");
        $j("select#edit-townSelect, select#edit-step2-townSelect").show();
        $j("input#edit-town, input#edit-step2-town").hide();
        $j("input#edit-town, input#edit-step2-town").attr("disabled", "disabled");
      } else {
        $j("input#edit-town, input#edit-step2-town").removeAttr("disabled");
        $j("input#edit-town, input#edit-step2-town").show();
        $j("select#edit-townSelect, select#edit-step2-townSelect").hide();
        $j("select#edit-townSelect, select#edit-step2-townSelect").attr("disabled", "disabled");
      }
    })
  })

  $j("select#edit-townSelect, select#edit-step2-townSelect").change(function(){
    if ($(this).val() != 0){
      $j("input#edit-town, input#edit-step2-town").val($(this).val());
    }
  })
})

function getTownList() {
  $j("img#loadingTown").show();
  // Ajax GET request for autocompletion
  var postalcode = $j("input#edit-postalCode, input#edit-step2-postalCode").val();
  if (postalcode == "") {
    postalcode = "-";
  }
  $.ajax({
    type: "GET",
    dataType: "json",
    url: "/jquery/getTown/"+postalcode+"/"+$j("#edit-country, #edit-step2-country").val(),
    success: function (j) {
      // Parse back result
      if (j.length>0) {
        var options = '';
        for (var i = 0; i < j.length; i++) {
          options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
        }
        $j("select#edit-townSelect, select#edit-step2-townSelect").html(options);
      } else {
      }
      $j("img#loadingTown").hide();
    }
  })
}


