// returns TRUE if a button in the group is checked
function ae_checked(name) {
	var btns = $A($("ae_form")[name]);
	var checked = false;
	btns.each(function(r) { checked = checked || r.checked; });
	return checked;
}

// returns TRUE if all fields and text areas are filled
function ae_fields_entered() {
	var not_filled = false;
	
	// inputs
	$$("#ae_form input[type=text]").each(function(f) {
		if (f.id != "other_industry") not_filled = not_filled || f.value.empty();
	});
	
	// other industry
	if ($("industry_other").checked) not_filled = not_filled || $("other_industry").value.empty();
	
	// text areas
	$$("#ae_form textarea").each(function(f) { not_filled = not_filled || f.value.empty() });
	
	return !not_filled;
}

// returns TRUE if all fields are entered and valid
function ae_all_fields_valid() {
	return ae_checked("industry[]") && ae_checked("division") && ae_checked("category") &&
				ae_checked("size") && ae_checked("region") && ae_fields_entered();
}

// validates the form upon submission
function ae_validate() {
	var complete = ae_all_fields_valid();

	if (!complete) alert("Please fill all fields (except for supplementary documentation) to submit the form!");
	
	return complete;
}

// ----------------------------------------------------------------------------

var individual_fields = new Hash();
var fields = [ "name", "title", "organization", "mail", "phone", "email" ];

function ae_init_address_autocomplete() {
	// save initial state of the fields
	fields.each(function(field) {
		field = "ind_" + field;
		individual_fields[field] = $F(field);
		new Form.Element.Observer($(field), 0.2, ae_on_address_field_change.bind($(field)));
	});
}

// invoked when a certain field changes its value
function ae_on_address_field_change() {
	var new_value = this.getValue();
	var id = this.id;
	var dest = id.sub("ind_", "org_");
	var old_value = individual_fields[id];
	
	individual_fields[id] = new_value;
	
	if ($F(dest) == old_value) {
		$(dest).value = new_value;
	}
}

var ae_valid = false;
function ae_check_form() {
	var btn = $("commit");
	var msg = $("incomplete");
	if (ae_all_fields_valid()) {
	  if (!ae_valid) {
  	  ae_valid = true;
  		btn.enable();
  		msg.hide();
		}
	} else if (ae_valid) {
	  ae_valid = false;
		btn.disable();
		msg.show();
	}	
}

function ae_init_form_watcher() {
	ae_check_form();
	new Form.Observer("ae_form", 0.2, ae_check_form);
}