var num_options = 1; // The number of "Other" commitments fields
function add_commitment_option() {
	var option_num = num_options++;
	var input_el_name = 'commitment_other_' + option_num;
	var li_el_name = 'commitment_' + option_num;
		
	new Insertion.Bottom('other_commitments',
		('<li id="' + li_el_name +'"><label for="' + input_el_name + '">Other</label>:&nbsp;I will&nbsp;<input id="' + input_el_name + '" name="commitment_other_' + option_num + '" type="text" value="" size="65" maxlength="200" onblur="tally_commitments();" />&nbsp;<a href="#" class="small_button" title="Add a commitment." onclick="add_commitment_option(); return false;">+</a>&nbsp;<a href="#" class="small_button" title="Remove this commitment." onclick="remove_commitment_option(\'' + li_el_name +'\'); tally_commitments(); return false;">&ndash;</a></li>')
		);
		new Effect.Highlight(input_el_name);
		$(input_el_name).focus();
}


function remove_commitment_option( el_id ) {
  $(el_id).parentNode.removeChild($(el_id));
}



var total_commitments = 0;
function tally_commitments() {
	var num_commitments = 0;
	var list_items = $('commitments').getElementsByTagName('input');
	var items = $A(list_items);
	items.each(function(item) {
		if (item.type == 'checkbox') {
			if (item.checked) {
				num_commitments++;
			}
		} else if (item.type == 'text') {
			num_commitments += parseInt($F(item));
		}
	});
	
	var other_items = $('other_commitments');
	if (other_items) {
		var list_items = other_items.getElementsByTagName('input');
		var items = $A(list_items);
		items.each(function(item) {
			if (item.type == 'text') {
				if ($F(item) != '') {
					num_commitments++;
				}
			}
		});
	}
	
	
	if (num_commitments != total_commitments) {
		var displayEl = $('totalCommitments');
		displayEl.innerHTML = num_commitments;
		var displayLineEl = $('totals')
		new Effect.Highlight(displayLineEl, {queue: {position:'end', scope: 'total_commitments_scope', limit:2}});
	}
	
	total_commitments = num_commitments;
}




function validate_form() {
	clear_error_messages();
	
	var has_errors = false;
	
	var list_items = $('commitments').getElementsByTagName('input');
	var items = $A(list_items);
	items.each(function(item) {
		if (item.type == 'text') {
			if (!check_is_integer(item)) {
				item.addClassName('error');
				has_errors = true;
			} else {
				item.removeClassName('error');
			}
		}
	});
	
	if (has_errors) {
		add_error_message("<p>Please enter only numbers in the quantity fields (e.g., 3).</p>");
		new Effect.ScrollTo('form_errors', {offset: -24});
		return false;
	}
	
	if (total_commitments == 0) {
		has_errors = true;
		add_error_message("<p>You did not choose any GEM commitments.  Please choose at least one commitment before submitting the form.</p>");
	}
	
	if (has_errors) {
		new Effect.ScrollTo('form_errors', {offset: -24});
		return false;
	}
	return true;
}

