var criteriaHTML;
var numCriteria = 1;
var criteriaSaved = new Array(1);

// Save the HTML that constitutes the default search form.
function setupCriteria() {
	criteriaHTML = document.getElementById("criteria").innerHTML;
	criteriaHTML = replaceCriterionNum(criteriaHTML);
	document.getElementById("criteria").innerHTML = criteriaHTML;
}

// Add a criterion to the list currently showing.
function addCriterion() {
	currCriteria = document.getElementById("criteria").innerHTML;
	saveFormValues(numCriteria);
	numCriteria++;
	currCriteria += replaceCriterionNum(criteriaHTML);
	document.getElementById("criteria").innerHTML = currCriteria;
	restoreFormValues(numCriteria - 1);
}

// Save the current values of all variables in the current form
function saveFormValues(numCriteria) {
	for (i = 1; i <= numCriteria; i++) {
		o = {};
		element = document.getElementById("type" + i);
		o.type = element.value;
		element = document.getElementById("value" + i);
		o.value = element.value;
		criteriaSaved[i] = o;
	}
}

// Restore saved values to the form, after it has been rebuilt 
// in addCriterion();
function restoreFormValues(numCriteria) {
	for (i = 1; i <= numCriteria; i++) {
		o = criteriaSaved[i];
		element = document.getElementById("type" + i);
		element.value = o.type;
		element = document.getElementById("value" + i);
		element.value = o.value;
	}	
}

// Wherever we find the string %%% in the criteria HTML, replace
// it with the current number of the criterion we're adding.
function replaceCriterionNum(criterion) {
	return criterion.replace(/%%%/, new String(numCriteria));
}

// When the form is submitted, save the current value of the numCriteria
// variable in the form's variables
function setNumCriteria() {
	document.getElementById("num-criteria").value = numCriteria;
	return true;
}
