// Compare Listings
/*

author: scott lenger
last updated: February 2008

instructions:
1. add <head> link to this file
2. add "compareVehicles();" to onload script in document head
3. make form id="compare"
4. ensure submit inputs (type="submit") are contained in the form tag

todo: allow for more than 3 vehicles
improve php error handling on resulting page

*/

function compareSelected(element) {
	var inputType = element.type; // get the input type
	var vehiclesSelected = 0; // reset vehicle counter

	// find all inputs inside the form
	var inputs = document.getElementById("compare");
	inputs.getElementsByTagName("input");

	for (var i=0; i<inputs.length; i++) {
		// count the number of vehicles selected
		if ((inputs[i].type == 'checkbox') && (inputs[i].checked == '1')) {
			vehiclesSelected++;
		}	
	}
	
	if ((vehiclesSelected < 2) && (inputType == "submit")) {
		// if only one car is selected
		alert("Select 2 or more cars to compare at a time.");
		// do not submit the form
		return false;
	} else if (vehiclesSelected > 4) {
		// if more than 3 vehicles are selected
		alert("A Maximum of 4 vehicles can be compared at a time");
		// uncheck the current checkbox
		element.checked = false;
	} else if (inputType == "submit") {
		// submit the form
		document.getElementById("compare").submit(); // input name="" cannot be "submit"
	}
}


// this adds javascript to the form elements
function compareVehicles() {
	if (!document.getElementById("compare")) {return;} // stop the script if the form id isn't found
	
	// find all inputs inside of the form
	var inputs = document.getElementById("compare"); // must use id of form tag
		inputs.getElementsByTagName("input");
	
	for (var i=0; i<inputs.length; i++) {
		// set the action for checkbox inputs
		if(inputs[i].type == 'checkbox') {
			inputs[i].onclick = function() { // use onclick for checkboxes
				compareSelected(this);
			}
		}
		// set the action for submit inputs
		else if (inputs[i].type == 'submit') {
			inputs[i].onclick = function() {
				return compareSelected(this); // return prevents the form from automatically running
			}
		}
	}
}