var checkflag = false;

function init() {
	if(!document.getElementById) {return;}
	var tables = getElementsByAttribute('class', 'highlight');
	// after you get the tables then get the body of it and find all inputs inside that
	for (var j=0; j<tables.length; j++) {
		var tbody = tables[j].getElementsByTagName('tbody')[0];
		var inputs = tbody.getElementsByTagName('input');
		for (var i=0; i<inputs.length; i++) {
			if (inputs[i].type == 'checkbox' || inputs[i].type == 'radio') {
				// if their type is a checkbox then add the event listener
				addEvent(inputs[i], 'click', highlightRow, false);
			}
		}
	}
	return true;
}

function highlightRow(e) {
	var target = window.event ? window.event.srcElement : e ? e.target : null;
	// once clicked make sure that the box is a 'remove' one
	if (target == null) {
		return false;	
	} else {
		var targetRow = getEventTarget(e);
		// get the current target and keep moving up until you find its parent tr
		targetRow = ascendDOM(targetRow, 'tr');
		// if the checkbox is checked then add the remove class to it's parent row
		if (target.checked == true) {
			targetRow.className += ' hi';
			// if the input is a radio button
			if (target.type == 'radio') {
				// get the parent table and find all inputs and unhighlight all but the current one
				var targetTable = ascendDOM(targetRow, 'table');	
				var inputs = targetTable.getElementsByTagName('input');
				for (var i=0; i<inputs.length; i++) {
					var tr = ascendDOM(inputs[i], 'tr');
					if (inputs[i].value != target.value) {
						tr.className = tr.className.replace(/\b ?hi\b/, '');
					}
				}
			}
		// otherwise wipe the toremove class
		} else {
		  targetRow.className = targetRow.className.replace(/\b ?hi\b/, '');
		}
	}
	return true;
}

// takes a checkbox's field name and checks all from that group 
function check(field) {
	if (checkflag == false) {
		if (field.length == null) {
			field.checked = true;
			field = ascendDOM(field, 'tr');
			field.className += ' hi';
		}		
		for (var i = 0; i < field.length; i++) {
			var fi = field[i];
			fi.checked = true;
			fi = ascendDOM(fi, 'tr');
			fi.className += ' hi';			
		}
		checkflag = true;
		return 'Uncheck All'; 
	} else {
		if (field.length == null) {
			field.checked = false;
			field = ascendDOM(field, 'tr');
			field.className = field.className.replace(/\b ?hi\b/, '');
		}		
		for (var i = 0; i < field.length; i++) {
			var fi = field[i];
			fi.checked = false;
			fi = ascendDOM(fi, 'tr');
			fi.className = fi.className.replace(/\b ?hi\b/, '');		
		}
		checkflag = false;
		return 'Check All'; 
	}
}

addLoadListener(init);