/*
**	Extends the prototype Element class to add isVisible() 
**	to check if an item is displayed on the screen.
**
**	Prototype's own .visible() method will only check the inline
**	css property of element itself, isVisible() will check up the dom
**	tree to see if the user is actually able to see the object.
**
**	REQUIRED FOR: checkManditoryJsq()
*/
Element.addMethods({
	isVisible: function(element) {
		element = $(element);
		if(!element.visible()) {
			return false;
		}
		var visible = true;
		element.ancestors().each(function(a) {
			if(!a.visible()) {
				visible = false;
			}
		});
		return visible;
	}
});

/*
** Checks that all manditory JSQs have been answered
*/
function checkManditoryJsq() {
	var done_array = new Array(); // an array of the groups of elements we've checked
	var return_val = true; // because all our iterators are using anon funcs, we can't return directly from them
	// Loop through each input with class jsqIsManditory
	$$('input.jsqIsManditory').each(function(el) {
		// if the element is visible on the screen, it must be answered
		if(el.isVisible()) {
			
			// if it's a radio button
			if(el.type.toLowerCase() == 'radio') {
				if(done_array.indexOf(el.name) != -1) {
					// already checked this group of radios.
					return;
				}
				check = false;
				// check if any radios in the group are checked
				$$('input.jsqIsManditory[name="' + el.name + '"][type="radio"]').each(function(rad) {
					if(rad.checked) {
						check = true;
					}
				});
				// if none are checked, return false;
				if(!check) {
					return_val = false;
				}
				done_array.push(el.name);
			}
			// if it's a checkbox
			else if(el.type.toLowerCase() == 'checkbox') {
				// get the jsq_xxx prefex of the checkboxes name
				group = el.name.replace(/\-jsq_a\d+$/, '');
				if(done_array.indexOf(group) != -1) {
					// already checked this group of checks.
					return;
				}
				// check if at any in group are checked
				check = false;
				$$('input.jsqIsManditory[type="checkbox"]').each(function(box) {
					if(box.name.match(new RegExp("^" + group)) && box.checked) {
						check = true;
					}
				});
				// if none are checked, return false;
				if(!check) {
					return_val = false;
				}
				done_array.push(group);
			} else if(el.type.toLowerCase() == 'text') {
//				alert("checking el: " + el + ", (" + el.type.toLowerCase() + ")");
				if($F(el) == "") {
					return_val = false;
				}
			}
		}
	});
	// check all textarea manditory questions are answered.
	$$('textarea.jsqIsManditory').each(function(el) {
		if(el.isVisible()) {
			if($F(el) == "") {
				return_val = false;
			}
		}
	});
	return return_val;
}

