$(function(){
  $("#clubAssociation, #clubName").addValidation(function () {
    if (!(this.form["clubName"].valid = !(this.form["clubName"].value + this.form["clubAssociation"].value == ""))) {
      if ($("#clubSport").length != 0) {
        this.form["clubName"].error = "Either an association, a club or both must be entered.";
      } else {
        this.form["clubName"].error = "Either a league/association, club or both must be entered.";
      }
    } else {
      $("#clubName").clearError();
    }
    this.form["clubName"].validated = false;
  });

  //this is used for non-JS users so get rid of it
  $("#loadState").remove();

  var sport = $("#clubSport").change(function() {
    var supported = !(this.value == "AFL" || this.value == "KINEC" || this.value == "CRICK");
    if (supported) {//load states for that sport
      $.get("../ap.svc/LoadStateBySport", {s: $(this).val()}, function(data){
        var s = $("#propertyState");
        var oldValue = s.val();
        s.attr({length: 1});
        $("StateSport", data).each(function(){
          s[0].options[s[0].length] = new Option($("Name", this).text(), $("StateCode", this).text());
        });
        s.val(oldValue);
      });
    }
    //disable/enable fields for (un)supported sports
    $("fieldset:not(.submit) input, fieldset fieldset select").attr({disabled: !supported}).toggleClass("disabled", !supported).each(function() {
        if (!supported) {
          $(this).clearError();
        } else {
          this.validated = false;
        }
    });
  });
  if (sport.length > 0 && sport.val() != "") {
    sport.change();
  }

  $("#propertyState").change(function() {
    this.validated = false;
  });
  $("#propertyPostcode").predictOzState($("#propertyState"));

  $("#propertyState, #propertyPostcode").addServerValidation({
    path: JLTA.Site.siteRoot + "/validation.svc/IsValidPostcode?postcode=",
    getValue: function() {
      return $("#propertyPostcode").val() + "&state=" + $("#propertyState").val();
    },
    handler: function(data) {
      var el = $("#propertyPostcode");
      if (($("#propertyState").val() != "") && el.val() != "" && !(el[0].valid = !((el[0].error = data.Message) != ""))) {//if an error has been returned
        el.displayError();
      } else {
        el.clearError();
      }
    }
  });
});

