// ----------------------------------------------------------------------------------
// functions.js contains generic functions that are commonly used throughout the site
//    other functions are included using more specific function libraries
// ----------------------------------------------------------------------------------

// -- PURPOSE: to check/uncheck all checkboxes in a form
// -- Usage: checkAll(checkbox that checks/unchecks all, string limiting checkboxes to those whose name or id begins with it)

function checkAll(checkallbox, beginsWith) {
	var myForm = checkallbox.form;
	for (var i=0;i<myForm.elements.length;i++) {
		var myElement = myForm.elements[i];
		if (myElement != checkallbox && myElement.type == "checkbox") {
			if ((beginsWith && (myElement.id.indexOf(beginsWith) == 0 || myElement.name.indexOf(beginsWith) == 0)) || (!beginsWith)) { 
				myElement.checked = checkallbox.checked;
			}
		}
	}
}

// -- PURPOSE: to validate a field to only contain email addresses
// -- Usage: checkEmail(field to check)

function checkEmail(myField) {
	// we only pattern match email addresses, checking a domain registrar would take too long
	if (myField.value.search(/[\w\-\.\_]+\@[\w\-\.\_]+\.[\w\-\.\_]+/) == -1 && myField.value != "") {
		messageAlert("email");
		myField.focus();
		myField.select();
    return false;
	}
  return true;
}

// -- PURPOSE: to validate all required fields have been filled in on a form
// -- Usage: checkRequired(the form to check)

var missingRequired = new Array();
var missingOptional = new Array();

function checkRequired(myForm) {
	if (myForm.required && myForm.required.value) {

		missingRequired = resetRequiredFields(missingRequired);
		missingOptional = resetRequiredFields(missingOptional);

		var requiredFields = myForm.required.value.split(",");
		for (var i=0; i<requiredFields.length; i++) {
			var fieldName = requiredFields[i];
			if (fieldName.indexOf("|") != -1) {
				var optionalFields = fieldName.split("|");
				var noneFilled = true;
				
				for (var j=0; j<optionalFields.length; j++) {
					if (checkValue(optionalFields[j])) {
						noneFilled = false;
						break;
					}
				}
				if (noneFilled) {
					for (var j=0; j<optionalFields.length; j++) {
						
						missingOptional.push(optionalFields[j]);
					}
				}
			}
			else if (! checkValue(fieldName)) {
				missingRequired.push(fieldName);
			}
		}

		if (missingRequired.length > 0 || missingOptional.length > 0) {
			setRequiredFields(missingRequired, "required");
			setRequiredFields(missingOptional, "optional");

			var errorMessage = document.getElementById("missing_required");
			if (errorMessage) {
				errorMessage.style.display = "block";
				errorMessage.scrollIntoView(true);
			}
			return false;
		}
		else {
			return true;
		}
	}
	else {
		return true;
	}
}

function resetRequiredFields(fields) {
	// used only inside checkForm, do not call this function
	if (fields.length > 0) {
		for (var i=0; i<fields.length; i++) {
			var myLabel = getLabelFor(fields[i]);
			if (myLabel) {
				myLabel.className = myLabel.className.replace(/\s*(required|optional)/, "");
			}
			var myField = document.getElementById(fields[i]);
			if (myField) {
				myField.className = myField.className.replace(/\s*(required|optional)/, "");
			}
		}
	}

	fields = new Array();
	return fields;
}

function setRequiredFields(fields, className) {
	// used only inside checkForm, do not call this function
	for (var i=0; i<fields.length; i++) {
		var myLabel = getLabelFor(fields[i]);
		if (myLabel) {
			myLabel.className += " " + className;
		}
		var myField = document.getElementById(fields[i]);
		if (myField) {
			myField.className += " " + className;
		}
	}
}

function checkValue(fieldName) {
	// used only inside checkForm, do not call this function
	var myElement = document.getElementById(fieldName);
	if (myElement && myElement.style.display != "none") {
		if (myElement.type == "select-one" || myElement.type == "select-multiple") {
			for (var i=0; i<myElement.options.length; i++) {
				if (myElement.options[i].selected && myElement.options[i].value != '') {
					return true;
				}
			}
			return false;
		}
		else if (myElement.value == null || myElement.value.search(/\S/) == -1) {
			return false;
		}
	}
	return true;
}

// -- NOTE: The message functions are used in conjunction with messages.js which can be customized per skin.
//          Useful for customizeable errors, confirmations, and help text.

// -- PURPOSE: to ask for confirmation using an error message instead of just alerting
// -- Usage: messageConfirm(id of message to print)

function messageConfirm(messageType) {
	return window.confirm(eMsg[messageType]);
}

// -- PURPOSE: to print out an alert message to the screen
// -- Usage: messageAlert(id of message to print)

function messageAlert(messageName) {
	var output = eMsg[messageName];
	if (messageAlert.arguments[1]) {
		output += messageAlert.arguments[1];
	}
	window.alert(output);
}	

// -- PURPOSE: to get a label for a form input with the id provided
// -- Usage: getLabelFor(id of form element)

var myLabels = new Array();
function getLabelFor(elementId) {
	// this is needed by checkForm() but can be used elsewhere as desired
	if (myLabels.length == 0) {
		myLabels = document.getElementsByTagName("LABEL");
	}
	for (var i=0; i<myLabels.length; i++) {
		if (myLabels[i].htmlFor == elementId) {
			return myLabels[i];
		}
	}
}

function helpPopup(helpText) {
	var myDiv = document.getElementById("help");
	if (myDiv) {
		myDiv.innerHTML = helpText;
		var element = window.event.toElement;
		if (element) {
	alert(element);
//			myDiv.style.top = element.clientTop;
//			myDiv.style.left = element.clientLeft + element.clientWidth;
		}
		myDiv.style.visibility = "visible";
	}
}

function helpPopupClose() {
	var myDiv = document.getElementById("help");
	if (myDiv) {
		myDiv.style.visibility = "hidden";
	}
}

// -- PURPOSE: to open a new window or focus on it if it is opened
// -- Usage: openWindow(url to open, name of window object, width of window - number of pixels or "max" for maximum available, height of window - number of pixels or "max" for maximum available)

var myWindows = new Array();
function openWindow(windowURL, windowName, width, height, startX, startY) {
	var change = false;
	if (myWindows[windowName]){
		if (myWindows[windowName].closed) {
			change = true;
		}
		else if (myWindows[windowName].document.location.href.indexOf(windowURL) == -1) {
			change = true;
		}
	}
	else {
		change = true;
	}
	
	if (change) {
		if (width == "max") {
			width = screen.availWidth;
		}
		if (height == "max") {
			height = screen.availHeight - 50;
		}
		if (!startX) {
			startX = 0;
		}
		if (!startY) {
			startY = 0;
		}
		var args = "scrollbars=yes,toolbar=no,directories=no,menubar=no,resizable=yes,status=yes,width=" + width + ",height=" + height + ",top=" + startY + ",left=" + startX;
		myWindows[windowName] = window.open(windowURL, windowName, args);
	}
	myWindows[windowName].focus();
}
