
// Initialize Variables


var popup = null;					// Persistent pop-up window handler
var pop2  = null;


	// ******************************
	//      Menu/Button Handling
	// ******************************

function setButton(reqPage) {		// Deselects former menu buttons and highlights the menu button for a requested page.
									//		(The button will also highlight when the new page opens;
									//		but this provides instant user feedback while the new page loads.
									
									//		Also sets messy queryStrings back to "index.html" when opening a new page; to avoid
									//			unwanted redirects on reload
											
									//		reqPage : the page we're currently trying to open

									//		btnClass_h: full spelling of the new button's selected state class
									//		btnClass:   full spelling of the new button's deselected state class

	var buttonList = {
		'about.html'                : 'mb1', 
		'majorsDegreesCourses.html' : 'mb2', 
		'costFinancialAid.html'     : 'mb3', 
		'howDoIBegin.html'          : 'mb4'
	}; 

	var btnClass   = 'mainButton floatLeft';
	var btnClass_h = 'mainButton_h floatLeft';
	
	
			// Infer the menu button ID from the page name and selectively activate or deactivate menu buttons
			
	for (pageName in buttonList) {

		var btnID = buttonList[pageName];
		
		if( pageName == reqPage ) {
			top.getObjectByID(btnID).className = btnClass_h;		// highlight the menu button
		} else {
			top.getObjectByID(btnID).className = btnClass;			// deselect the menu button
		}
	}
}

function clearQueryString(currentPage, redirect) {		// Remove URL queryString: store a cookie and redirect to "index.html"

														//		currentPage: the cookie value to store
														//		redirect:    optional flag. If set opens currentPage after storing
	
	var queryStringExists = getQueryFromURL( top.location.href );

	if (queryStringExists) {							// Prototype: storePage(currentPage, cookieCallback, cookiePassVals);
	
		if (currentPage) {
			storePage(currentPage, 'top.resetURL', '');
			
			setTimeout("top.location.href='index.html'; ", 300);
		} else {
			top.resetURL();
			
			setTimeout("top.location.href='index.html'; ", 300);
		}
	}
	
	if (redirect) {								// (Optional:) Open currentPage after writing cookie
		
		getObjectByID('mainFrame').contentWindow.location.href = currentPage;
	}
}

function storePage(currentPage, cookieCallback, cookiePassVals) {		// Writes the currentPage to a cookie for later reference

		// * If cookieCallback = 'top.resetURL', the page will redirect to the parent frame after storing the cookie

	var cookieNames    = 'gpCurrentPage';
	var cookieValues   = currentPage;
	var cookieDur      = 12 * 60 * 60 * 1000;		// Remember this page for half a day
		
	if (currentPage) {
		top.phpCookie(cookieNames, cookieValues, cookieCallback, cookieDur, cookiePassVals);
	}
}

function resetURL() {												// Redirect to "index.html" (i.e., to clear queryStrings)
	top.location.href = "http://www.gpidea.org/index.html";
}


function resetButton() {						// Upon page load or refresh, highlight the current button

	var btnID = readCookie('gpBtnID');
	var hClass = readCookie('gpBtnClass_h');
	
	if (btnID ) {
		getObjectByID(btnID).className = hClass;			
	}
}


function toggleBtn(whichBtn, state) {					// State = '_h' (highlighted) or ''

	var currentPage = getValue('currentPage');

	if (currentPage !== whichBtn) {						// Ignore requests if hovering over current page button
	
		var newState = '../images/' + whichBtn + 'Bt' + state + '.gif';
		getObjectByID(whichBtn + 'Bt').src = newState;			// Change the button state
	}
}



// *************************
//      Common Routines
// *************************


function getFileFromURL(url) {		// Parses a URL and returns the name of the page without the full path

	var url           = url.toString();
	var urlPath       = url.split("?");			// Drop any query portion to get the root URL
	var urlRoot       = urlPath[0];
	var urlSegments   = urlRoot.split("/");
	var lastSegment   = urlSegments.length - 1;
	var file          = urlSegments[lastSegment];
	
	if (!file) {
		file = 'index.html';	
	}	
	return file;
}

function getQueryFromURL(url) {		// Parses a URL and returns the queryString from its path

	var url        = url.toString();

	var searchChar = new RegExp( escapeRegex("?") );
	var queryStart = url.search(searchChar);		// Does the redirect path include a query?
		
	if ( queryStart > -1 ) {						// 	Yes: extract query string and append to the default queryURL
		queryString = url.substr(queryStart + 1);
	} else {
		queryString = '';							// No:   no additional query parameters
	}
	
	return queryString;
}


function openURL(page, w, h) {		// Opens a resizable pop-up window

	if(popup) {
		popup.close();
	}
		popup = window.open(page, 'popup', 'height=' +h+ ',width=' +w+ ',scrollbars=yes,resizable=yes');
}


function embedFlash(thisFile, w, h) {	// Shows the activeX control without an annoying 'activate' prompt

	var embedCode = "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' " 
		+ "codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0' width='" + w + "' height='" + h + "'> " 
		+ "<param name='allowScriptAccess' value='sameDomain' /> "
		+ "<param name='movie' value='" + thisFile + "' /> " 
		+ "<param name='quality' value='high' /> " 
		+ "<param name='wmode' value='transparent' /> " 
		+ "<embed src='" + thisFile + "' width='" + w + "' height='" + h + "' quality='high' " 
		+ "pluginspage='http://www.macromedia.com/go/getflashplayer' allowScriptAccess='sameDomain' type='application/x-shockwave-flash' wmode='transparent'> " 
		+ "</embed></object>";

	document.write(embedCode);
}

function embedFLV(w, h, vars) {	// Embeds an FLV in a custom player applet. Requires mediaplayer.swf and uses this protocol:
								// embedFlash(320, 240, "width=320&height=240&file=video1.flv");

	var embedCode = "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' " 
		+ "codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0' width='" + w + "' height='" + h + "'> " 
		+ "<param name='allowScriptAccess' value='sameDomain' /> "
		+ "<param name='movie' value='mediaplayer.swf' /> " 
		+ "<param name='quality' value='high' /> " 
		+ "<param name='wmode' value='transparent' /> " 
		+ "<param name='allowfullscreen' value='true' /> " 
		+ "<param name='flashvars' value='" + vars + "' /> " 
		+ "<embed src='mediaplayer.swf' width='" + w + "' height='" + h + "' quality='high' allowfullscreen='true' flashvars='" + vars + "' " 
		+ "pluginspage='http://www.macromedia.com/go/getflashplayer' allowScriptAccess='sameDomain' type='application/x-shockwave-flash' wmode='transparent'> " 
		+ "</embed></object>";

	document.write(embedCode);
}

function MM_CheckFlashVersion(reqVerStr,msg){
  with(navigator){
    var isIE  = (appVersion.indexOf("MSIE") != -1 && userAgent.indexOf("Opera") == -1);
    var isWin = (appVersion.toLowerCase().indexOf("win") != -1);
    if (!isIE || !isWin){  
      var flashVer = -1;
      if (plugins && plugins.length > 0){
        var desc = plugins["Shockwave Flash"] ? plugins["Shockwave Flash"].description : "";
        desc = plugins["Shockwave Flash 2.0"] ? plugins["Shockwave Flash 2.0"].description : desc;
        if (desc == "") flashVer = -1;
        else{
          var descArr = desc.split(" ");
          var tempArrMajor = descArr[2].split(".");
          var verMajor = tempArrMajor[0];
          var tempArrMinor = (descArr[3] != "") ? descArr[3].split("r") : descArr[4].split("r");
          var verMinor = (tempArrMinor[1] > 0) ? tempArrMinor[1] : 0;
          flashVer =  parseFloat(verMajor + "." + verMinor);
        }
      }
      // WebTV has Flash Player 4 or lower -- too low for video
      else if (userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 4.0;

      var verArr = reqVerStr.split(",");
      var reqVer = parseFloat(verArr[0] + "." + verArr[2]);
  
      if (flashVer < reqVer){
        if (confirm(msg))
          window.location = "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash";
      }
    }
  } 
}


function getThisID(name) {				//  Get an object's ID tag for easy referencing

	if (document.getElementById) {				// Firefox and Safari
		return document.getElementById(name);
	} else if (document.all) {					// IE
		return document.all[name]; 
	} else if (document.layers) {
		return document.layers[name];
	} else {
		return document.getElementById(name);		// Default for unknown browsers
	}
}

function getObjectByID(id) {				// Get an object's ID tag for easy referencing

	var frameList = new Array('mainFrame', 'sidebarFrame');		// Frames within the page where the object might exist

	if ( getThisID(id) != null && getThisID(id) ) {
		return getThisID(id);

	} else {									// Object not found on the immediate page: try looking in other frames
		for ( var n in frameList ) {			// Cycle through frames in the array

			var thisFrame = frameList[n];

			if ( top.getThisID(thisFrame) != null ) {		// If this frame has an open document, look there
			
				if (typeof top.getThisID(thisFrame).contentWindow.getThisID == 'function') {
			
					if (top.getThisID(thisFrame).contentWindow.getThisID(id) ) {
						return top.getThisID(thisFrame).contentWindow.getThisID(id);
					}
				}
			}														// No open document: try the next frame...
		}
	} 
	
		// Tried all frames, and there's nothing: return empty result
		
	return '';
}


function setValue() {				// Sets the value property of a specified field or control

	var lastObj = (setValue.arguments.length);
	for(n=0; n<lastObj; n++) {
		thisID = setValue.arguments[n]
		thisObj = getObjectByID(thisID);
		thisVal = setValue.arguments[++n];

		thisObj.value = thisVal;
	}
}


function getValue(id) {			// Returns the value property of the specified object

	var obj = getObjectByID(id);
	return obj.value;
}

function updateCheckbox(type, id, field) {						// Simple Ajax call to update the database when a checkbox is checked via updateForm

	setValue('updateType', type);
	setValue('updateID', id);

	var checkedVal;
	
	if ( getObjectByID(field).checked ) {								// Get the value of this box if checked
		checkedVal = getValue(field);
	} else {
		checkedVal = '';
	}

	setValue('updateV', checkedVal);
	sendReq('updateForm', ''); 
}


function emCode(prefix, suffix, text, loc, offset, mode, stClass) {	// E-mail obfuscator

								//	offset specifies how many garbage chars precede both prefix & text

								// 	mode 'a': pairs mailto href with text
								//		Example: emCode('zdn', 'p', 'zDavid Pedergnana', '', 1, 'a');

								//	mode 'n': shows e-mail only (as text)
								//		Example: emCode('zdn', 'p', '', '', 1, 'n');

								//	mode 'm': shows e-mail address as clickable mailto text
								//		Example: emCode('zdn', 'p', '', '', 1, 'm');
	var xString = prefix + suffix;
	var h = '<a href=\"mai';
	
	if (stClass) {
		h =  '<a class=\"' + stClass + '\" href=\"mai';	
	}
	
	var nom = xString.substr(offset);
	h += 'lto:';
	text = text.substr(offset);
	var end = '\">';
	text += "<" + String.fromCharCode(47);
	var z = '@';

	if (!loc) {
		var n = 101;
		loc = 'ksu.' + String.fromCharCode(n) + 'du';
	}

	if (mode == 'n') {
		document.write(nom + z + loc);
	} else if (mode == 'm') {
		document.write(h + nom + z + loc + end);
		document.write(nom + z + loc + text + 'a>');
		
	} else {
		document.write(h + nom + z + loc + end);
		document.write(text + 'a>');
	}
}



function parseURL(param, queryURL) {	// Parses a URL queryString into components and returns the requested parameter

									// queryURL: If specified, parses the given parameterList; otherwise parses location.href
	var result = null;
	var paremeterList;

	if (queryURL) {
		parameterList = queryURL.split("?");		// GET Parameters
	} else {
		parameterList = location.href.split("?");		// GET Parameters
	}

	if (parameterList.length > 1) {

				// Split list into name.value pairs

		var parameterPairs = parameterList[1].split("&");
		var nameAndValue = new Array();
		var paramValue;
		var paramKey;

		for (p=0; p < parameterPairs.length; p++) {	// Cycle through name/value pairs & store values

			nameAndValue = parameterPairs[p].split("=");
			paramKey = nameAndValue[0];
			paramValue = nameAndValue[1];

			if (paramKey == param) {		// Is this the target key?
				result = paramValue;
				break;
			}
		}
	}
	return result;
}


function escapeRegex(inputString) {			// Prevents invalid quantifier errors when searching for special characters in Regex
	
	return inputString.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
}


function getScreenSpecs(defaultW, defaultH) {		// Accepts default width and height as input and returns 
							// either actual screen width and height or the defaults
	screenH = defaultH
	screenW = defaultW;

	if (parseInt(navigator.appVersion)>3) {
		 screenH = screen.height;
		 screenW = screen.width;
	}
	else if (navigator.appName == "Netscape" 
	    && parseInt(navigator.appVersion)==3
	    && navigator.javaEnabled()
	) 
	{
	 var jToolkit = java.awt.Toolkit.getDefaultToolkit();
	 var jScreenSize = jToolkit.getScreenSize();
	 screenH = jScreenSize.height;
	 screenW = jScreenSize.width;
	}

	return [screenW, screenH];
}



function openDoc(file, w, h, resizable, hOffset) {		// Opens a document of specified dimensions in a separate pop-up window
														//		Resizable is a boolean value ("yes" or "no") or "fixedSizeScroll"
														// 	hOffset is an optional parameter for offsetting the position from center screen 
	if(popup) {
		popup.close();
	}
	
	if (!hOffset) {
		hOffset = 0;
	}

	if (!resizable) {
		var resizable = 'yes';
		var scrollbars = 'yes';
	} else if (resizable == 'fixedSizeScroll') {
		var resizable = 'no';
		var scrollbars = 'yes';
	} else {
		var resizable = 'no';
		var scrollbars = 'no';
	}
	
	var screenWH = getScreenSpecs(1024, 768);
	screenW = screenWH[0];
	screenH = screenWH[1];

	popup = window.open(file, 'popUpWindow', 'height=' +h+ ', width=' +w+ ', scrollbars=' + scrollbars +', resizable=' + resizable + ',left=' + Math.round((screenW/2)-(w/2)-hOffset)+ ',top=' + Math.round((screenH/3)-(h/2)) );
}


function openDefault(page) {		// Opens a document in a default window that includes the location bar and is resizable

	pop2 = window.open(page, 'fullWin', 'scrollbars=yes, status=yes, menubar=yes, toolbar=yes, location=yes, resizable=yes, width=999, height=680');
}


function centerH(id, offset) {

	if (!offset) {
		offset = 0;
	}

	var w = getWidth(id);

	var windowW = getClientWidth();
	var leftPos = parseInt( (windowW / 2) - (w/2) + offset );

	getObjectByID(id).style.marginLeft = leftPos + 'px';
	
}

function centerV(id, offset) {

	if (!offset) {
		offset = 0;
	}

	var h = getHeight(id);
	var windowH = getClientHeight();
	var topPos = (windowH / 2) - (h/2) + offset;

	getObjectByID(id).style.marginTop = topPos + 'px';
}

function fillHeight(id, offset) {		// Checks Window Height then adjusts the height of a specified object.
						//	Offset can be specified to reduce height, in case of headers, etc.
						//	Returns the value h to the calling function
	if (!offset) {
		offset = 0;
	}

	var windowH = getWindowHeight();
	var h = parseInt(windowH) - offset;

	if (!h) {
		h = 420;
	}

	getObjectByID(id).style.height = h + 'px';
	return h;
}


function setFrame(whichPage) {					// Change the page within the mainFrame
	var frameObj = getObjectByID('mainFrame');
	frameObj.src = whichPage;
}

							
function getWindowHeight() {			
							
	if (window.innerHeight) {				// Firefox and Safari
		return window.innerHeight;
	} else {								// IE
		return document.body.clientHeight; 
	}
}
	

function getWindowWidth() {
   if (window.innerWidth) {
	return window.innerWidth;
   } else {
	return document.body.clientWidth;
   }	   	   	
}

function getClientWidth() {
	return filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function getClientHeight() {
	return filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function getScrollLeft() {
	return filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function getScrollTop() {
	return filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


function getWidth(id) {			// Returns the width of the specified object
	var obj = getObjectByID(id);

	if (obj.style.width) {
		return obj.style.width;
	} else if (obj.style.pixelWidth) {
		return obj.style.pixelWidth;
	} else {
		return obj.offsetWidth;
	}
}


function getHeight(id) {		// Returns the height of the specified object
	var obj = getObjectByID(id);

	if (obj.style.height) {
		return obj.style.height;
	} else if (obj.style.pixelHeight) {
		return obj.style.pixelHeight;
	} else {
		return obj.offsetHeight;
	}
}


function showObject() {				// Show a dynamic form field or menu
										// Iterates through argument list if an array is input
										
	var lastObj = showObject.arguments.length;
	for(n=0; n<lastObj; n++) {
		thisObj = getObjectByID(showObject.arguments[n]);
		thisObj.style.display = "";
	}
}



function hideObject() {					// Show a dynamic form field or menu
											// Iterates through argument list if an array is input
	var lastObj = hideObject.arguments.length;
	for(n=0; n<lastObj; n++) {
		
		thisObj = getObjectByID(hideObject.arguments[n]);
		thisObj.style.display = "none";
	}
}


function isShown(id) {

	if ( getObjectByID(id).style.display == 'none') {
		return 0;
	} else {
		return 1;
	}
}

function focusOn(targetID, msDelay) {		// Gives focus to the named field or form object
											// msDelay is how long to pause before giving focus

	if (msDelay) {
		var cmd = "getObjectByID('" + targetID + "').focus();" ;
		setTimeout(cmd, msDelay);
	} else {
		getObjectByID(targetID).focus();
	}
}


function showDiv(whichDiv) {			// Changes the background color of the link to match the specified div; then
										// shows the div
	var divID = whichDiv + 'Div';
	var tabID = whichDiv + 'Link';
	var hrefID = whichDiv + 'href';

	getObjectByID(divID).className = 'infoBlockOpen';		// Show the div
	getObjectByID(tabID).className = 'tabOpen';				// Change the link background color
	getObjectByID(hrefID).className = 'tabLinkOpen';		// Change the link background color
}


function hideDiv(whichDiv) {			// Changes the background color of the link to white; then
										// shows the div
	var divID = whichDiv + 'Div';
	var tabID = whichDiv + 'Link';
	var hrefID = whichDiv + 'href';

	getObjectByID(divID).className = 'hidden';				// Hide the div
	getObjectByID(tabID).className = 'tabClosed';			// Change the link background color
	getObjectByID(hrefID).className = 'tabLinkClosed';		// Change the link background color
}


function toggleInfoBlock(whichDiv) {	// Either hides or shows a specified div, depending on its current state

	var divID = whichDiv + 'Div';

	if (getObjectByID(divID).className == 'hidden') {		// Div is hidden: show it

		showDiv(whichDiv);
	} else {															// Div is visible: hide it
		hideDiv(whichDiv);
	}
}


function toggleObject(id) {	// Alternately show or hide content found in the specified programDiv

	if ( isShown(id) ) {
		hideObject(id);
	} else {
		showObject(id);
	}
}


function validateField(fieldID, legalChars, feedback) {		// Returns 1 if field contents are legal; else 0
																// feedback:   An optional alert message to send when contents are illegal
	var inputString = getValue(fieldID);
	var thisChar;
	
	for (var n=0; n<inputString.length; n++) {
	
		thisChar = inputString.charAt(n);
		var matchItem = new RegExp(thisChar);
		
		if ( legalChars.search(thisChar) == -1) {					// Invalid character
			if (feedback) {
				alert(feedback);
				getObjectByID(fieldID).className = 'invalid';		// Change its color
				focusOn(fieldID);
			}
			return 0;
		}
	}

	getObjectByID(fieldID).className = 'valid';						// OK: It's valid. Clear the field (if highlighted previously)
	return 1;
}

function padLeft(inputString, padChar, n) {		// Accepts a string and character(s) to pad with (i.e., space, 
								//     zero, etc.) and returns a revised string of length n

								//     Works with multiple padChars, too! Feed it an empty 
								//     input string to generate a pattern string of specified
								//     length. Currently doesn't truncate, though...
	while (inputString.length < n) {
		inputString = padChar + inputString;
	}
	return inputString;
}

function padRight(inputString, padChar, n) {		// Accepts a string and character(s) to pad with (i.e., space, 
								//     zero, etc.) and returns a revised string of length n

								//     Works with multiple padChars, too! Feed it an empty 
								//     input string to generate a pattern string of specified
								//     length. Currently doesn't truncate, though...
	while (inputString.length < n) {
		inputString = inputString + padChar;
	}
	return inputString;
}


function validateEmailField(id) {				// Checks to see if the field named 'email' has @ and . chars
												// Returns 1 if invalid
	var email = getObjectByID(id).value;

	var emailRegEx = /^[^@]+@[^@]+.[a-z]{2,}$/i;

	if(email.search(emailRegEx) == -1){
		return 1;
	} else {
		return 0;
	}
}

function requireFields() {				// Accepts a list of field ids that must be not be empty, followed by an error prompt and a highlight class.
							// If any fields are empty, returns the specified error mesage and highlights them.
							// If no error message is specified, the alert is surpressed.
							// Returns an array list of invalid field ids
	var idList = requireFields.arguments;
	var badFields = new Array();

	var lastItem = (idList.length)-1;

	var hClass = idList[lastItem];
	var msg = idList[lastItem-1];
	
	lastItem = lastItem - 3;

	for (var n=0; n < lastItem; n++) {		// Cycle through the fields and check their contents

		var thisV = getValue( idList[n] );

		if (!thisV) {											// This field's empty:
			getObjectByID( idList[n] ).className = hClass;		// Change its color
			badFields.push( idList[n] );
		} else {
			getObjectByID( idList[n] ).className = 'valid';
		}
	}

	var badFieldsExist = badFields.length;
	if (badFieldsExist) {
		if (msg) {
			alert(msg);
		}
		focusOn( badFields[0] );
		return badFields;
	} else {
		return 0;
	}
}


// Phone number validation scripts (origin: SmartWebby.com)

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";

	if(!s) {
		return "";
	}

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone) {
	s = stripCharsInBag(strPhone, "()- +.");			// Valid non-integers in a phone number
	return (isInteger(s) && s.length >= 10);			// Minimum digits in an international phone number
}

function checkLocalPhone(strPhone) {
	s = stripCharsInBag(strPhone, "()- +." );			// Valid non-integers in a phone number
	return (isInteger(s) && s.length == 7);				// Minimum digits in an international phone number
}

function validatePhone(id){		// Accepts phone field id and error prompt as input and returns 1 if invalid
					// If msg is empty, it surpresses the prompt
	var Phone = getValue(id);
	var msg = '';

	if (!checkInternationalPhone(Phone)) {
		if (checkLocalPhone(Phone)) {		// Is it only missing the prefix?

			msg = 'Please include a full phone number with area code';

		} else {				// It's just wrong

			msg = 'Please use a valid phone number';
		}
	} else {
		msg = '';
	}
	return msg;
 }



function HideContent(d) {
if(d.length < 1) { return; }
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
if(d.length < 1) { return; }
document.getElementById(d).style.display = "block";
}
function ReverseContentDisplay(d) {
if(d.length < 1) { return; }
if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
else { document.getElementById(d).style.display = "none"; }
}


function statusAlert(msg) {				// Send a stylized prompt to the statusDiv

	msg = "<img src='../images/icon-exclaim.gif'>" + msg;
	setText('statusHead', msg);
}


function recoverLostPwd(fieldID, formID, formField) {		// Retrieve a forgotten password (if it exists)

	var email = getValue(fieldID);						// Ensure that e-mail field is filled correctly
	var alertMsg = '';

	if (email == '') { 											// E-mail field is blank

		alertMsg = 'Type your e-mail address first.';
	}

	var invalidEmail = validateEmailField(fieldID);				// Validate e-mail field before submitting request

	if(invalidEmail) {
		alertMsg = "Please type a valid e-mail address.";
	}

	if (alertMsg) {
		statusAlert(alertMsg);
	} else {											// No warnings: e-mail address is OK
					
		setValue(formField, email);				// Update recoverPwd form with e-mail address & send request
		sendReq(formID, 'js');
	}
}


function setText() {					// Sets the innerHTML of specified objects to desired text.

	var lastObj = (setText.arguments.length);
	for(n=0; n<lastObj; n++) {
		thisID = setText.arguments[n]
		thisObj = getObjectByID(thisID);

		if(!thisObj) {
			alert("Error: " + thisID + " doesn't exist");
			++n;
		} else {
			thisText = setText.arguments[++n];
			thisObj.innerHTML = thisText;
		}
	}
}

function getText(ID) {						// Returns the innerHTML of a specified <span> field

	var textSpanObj = getObjectByID(ID);
	var text = textSpanObj.innerHTML;

	return(text);
}


function setClass(prefix, newClass, itemCount, setBtnID, altClass) {		// Sets all IDs beginning with a certain prefix (as in a button group) to a specified class
										//		prefix:      the characters with which each button ID starts, i.e. "pButton"
										//		newClass:    the new className for each button
										//		itemCount:   the number of buttons in the set. If itemCount = 5, buttons are numbered 0, 1, 2, 3, & 4 (first button is "pButton0" in this example)
										//		setBtnID:    optional button number. If specified, this button will be set to altClass

	if (setBtnID == 'get') {
		setBtnID = readCookie('gpBtnID');					// setBtn = 'get': retrieve the current button ID
	} else {
		makeCookie('gpBtnID', setBtnID);					// Store the current button ID
	}

	for (var n=1; n<=itemCount; n++) {
	
		id = prefix + n;
		
		if (n == setBtnID) {
			getObjectByID(id).className = altClass;
		} else {
			getObjectByID(id).className = newClass;
		}
	}
}

function getMenu(whichMenu) {

	alert(whichMenu);
}


function makeDialog(header, msg, buttonLabel, action) {		// Configures and shows the standard alert dialog, which 
															// includes an optional button click action

	if (!action) {													// Alert action is optional; dialogue always hides upon click
		setValue('alertAction', '');
		hideObject('alertCancelButton');
	} else {
		setValue('alertAction', action);
		showObject('alertCancelButton');							// Show a [Cancel] button when there is an action
	}
	
	setAlert('alertHead', header);
	setText('alertPrompt', msg);
	
	if (!buttonLabel) {												// The default button label is 'OK' if unspecified
		setValue('alertButton', 'OK');
		hideObject('alertCancelButton');							// When defaulting to [OK], hide the [Cancel] button
	} else {
		setValue('alertButton', buttonLabel);
	}
	
	showObject('alertDialog');
}


function setAlert(nodeID, msg) {			// Send alert text to the specified node
	
	msg = "<img src='../images/icon-exclaim.gif'>" + msg;
	setText(nodeID, msg);
}


function doAlertAction() {

	var action = getValue('alertAction');
	hideObject('alertDialog');
	
	if (action) {
		eval(action);
	}
}

function askInput(askInputHead, askPrompt, id, inputW, buttonLabel, jsAction, defaultValue, hideCancel) {		
								// Configures and shows a standard text input dialog with an optional custom action button

								//	askPrompt:      question to display along with the text entry field
								//	id:             optional ID or other value to store that can be referenced by the JS action
								//	inputW:         width of the text field in pixels
								//	buttonLabel:    text description for the optional action button (i.e., [OK] )
								//	jsAction:       custom script to run if the action button is clicked
								//	defaultValue:   current value of askInputText (if any)
								//	showCancel:     if set, the [Cancel] button is not shown

	if(defaultValue) {
		setValue('askInputText', defaultValue);
	} else {
		setValue('askInputText', '');					// Clear askInputText of possible former entry
	}

	if (jsAction) {									// askInput action is optional... dialogue always hides upon click
		setValue('askInputAction', jsAction);
	} else {
		setValue('askInputAction', '');
	}
	
	if (id) {
		setValue('askInputID', id);
	} else {
		setValue('askInputID', '');
	}

	setText('askInputHead', askInputHead);
	setText('askInputPrompt', askPrompt);
	
	if (!buttonLabel) {															// The default button label is 'OK'
		setValue('askInputButton', 'OK');
		hideObject('askInputCancelButton');										// Hide [Cancel] button when defaulting to [OK]
	} else {
		setValue('askInputButton', buttonLabel);
		showObject('askInputCancelButton');										// Show a [Cancel] button when there is an action
	}
	
		
	if (inputW) {
		getObjectByID('askInputText').style.width = '' + inputW + 'px';				// Set the dimensions of the input field
	}

	if (hideCancel) {
		hideObject('askInputCancelButton');	
	} else {
		showObject('askInputCancelButton');	
	}
	
	showObject('askInputDialog');
	focusOn('askInputText', 500);
}

function doAskInputAction() {				// Do the specified action when the askInputDialog confirm button is clicked

	var action = getValue('askInputAction');
	hideObject('askInputDialog');
	
	if (action) {
		eval(action);
	}
}

	// AJAX Requests


function joinValues(fields) {		// Accepts a string of comma-separated field names as input (with spaces) and returns a string of values
									// Delimiter = |
	var fieldList = fields.split(", ");
	var lastItem = fieldList.length;
	var v = '';
	var valList = new Array();
	
	for (n=0; n<lastItem; n++) {
		v = getValue( fieldList[n] );
		valList.push(v);
	}
	
	return valList.join("|");
}


function fetch(type, id, dialog, focusField, targetID, param1, param2) {	// Ajax call to retrieve data for a form or display
														// 	dialog:   optional dialog to show after populating form fields
														// 	focusField: optional field to place cursor in after populating
														//	targetID:   optional div or span to populate with returned text 
														//	param1:     optional custom parameter to send additional data
														//	param2:     optional custom parameter #2
	var url          = 'subs-fetch.php';
	var callbackFunc = '';
	var syncReqFlag  = '';
	var oData = {
		fetchID     : id,
		fetchType   : type,
		fetchDialog : dialog,
		fetchFocus  : focusField,
		param1      : param1,
		param2      : param2
	};

	sendData(url, targetID, callbackFunc, oData, syncReqFlag);
}


function fetchList( listType, parentID, selected, focusOn, targetID, listContext, param1, param2  ) {	// Generates a (cascading) listBox

						// type:        Identifies which control to fetch
						// parentID:    With cascading menus, optional value of the parent (preceding) list
						// selected:    The currently selected ID of this control (if any)
						// focusOn:     If specified, gives focus to the specified control after fetching
						// listContext: distinguishes similar calls from different pages, in case onChange handlers must differ
						// param1:      Optional parameter #1
						// param2:      Optional parameter #2

	var url          = 'subs-fetchList.php';
	var callbackFunc = '';
	var syncReqFlag  = '';
	var oData = {
		listType    : listType, 
		parentID    : parentID,
		selected    : selected,
		focusOn     : focusOn,
		listContext : listContext, 
		param1      : param1,
		param2      : param2
	};

	sendData(url, targetID, callbackFunc, oData, syncReqFlag);			
}


function fetchCheckbox(fetchType, checkboxID, targetID, lookupID, lookupID2, tabIndex) {	// Call to retrieve checkbox status

													// fetchType:  identifies which table to search (not the actual table name)
													// checkboxID: the retrieved checkbox label
													// targetID:   the span or div to update
													// lookupID:   ID of the record to search for checkbox status
													// lookupID2:  Optional second ID used for cross-references
													// tabIndex:   Optional tabIndex value for the checkbox
	var url          = 'subs-fetchCheckbox.php';
	var callbackFunc = '';
	var syncReqFlag  = '';
	var oData = {
		fetchType    : fetchType,
		checkboxID   : checkboxID,
		targetID     : targetID,
		lookupID     : lookupID,
		lookupID2    : lookupID2,
		tabIndex     : tabIndex
	};

	sendData(url, targetID, callbackFunc, oData, syncReqFlag);
}


function fetchRadio(type, radioSet, id) {			// Ajax call to retrieve radio button status
													// Note: radioSetForm must be named as radioSetName + 'Form'
	var url          = 'subs-fetchRadio.php';
	var targetID     = '';
	var callbackFunc = '';
	var syncReqFlag  = '';
	var oData = {
		fetchRadioID     : id,
		fetchRadioType   : type,
		radioForm        : radioSet + 'Form',		// radioForm ID is always the radioSet ID + "Form"
		fetchRadioSet    : radioSet
	};

	sendData(url, targetID, callbackFunc, oData, syncReqFlag);
}


function fetchTable(type, targetID, param1, param2, param3) {	// Ajax call to retrieve a table given optional input parameters
												//	targetID:   				div or span to populate with returned html table 
												//	param1, param2, param3:     custom matching parameters
	var url          = 'subs-fetchTable.php';
	var callbackFunc = '';
	var syncReqFlag  = '';
	var oData = {
		fetchType   : type,
		param1      : param1,
		param2      : param2,
		param3      : param3
	};

	sendData(url, targetID, callbackFunc, oData, syncReqFlag);
}


function showIfChecked(hiddenObj, radioID) {		// If the radioID is checked, the named object (usually a span or div) is made visible

	if (getObjectByID(radioID).checked) {
		showObject(hiddenObj);
	} else {
		hideObject(hiddenObj);	
	}
}


function update(type, id, fieldList, dialog, param1, param2) {		// Ajax call to update the database
									// 	type:      identifies which table and columns to update on the server
									// 	id:        id of the row to update
									// 	fieldList: a series of field ids to send for updating
									//	dialog:    optional dialog to hide after updating
									//	param1:     optional custom parameter to send additional data
									//	param2:     optional custom parameter #2

	if (fieldList.indexOf("|") == -1) {				// Get field values and convert them to a pipe-delineated string
		var valueList = joinValues(fieldList);
	} else {										// Function received a pipe-delineated string; don't convert
		var valueList = fieldList;
	}
	
	var url          = 'subs-Update.php';
	var targetID     = '';
	var callbackFunc = '';
	var syncReqFlag  = '';
	var oData = {
		updateType : type,
		updateID   : id,
		updateV    : valueList,
		param1     : param1,
		param2     : param2
	};
	sendData(url, targetID, callbackFunc, oData, syncReqFlag);
	
	if (dialog) {
		hideObject(dialog);
	}
}

function updateV(type, id, valueList, dialog) {		// Ajax call to update the database via updateForm
									// Unlike update(): Instead of a fieldList, this function accepts a valueList
									
									// 	type:      identifies which table and columns to update on the server
									// 	id:        id of the row to update
									// 	valueList: a pipe-delineated (|) string of values
									//	dialog:    optional dialog to hide after updating

	var url          = 'subs-Update.php';
	var targetID     = '';
	var callbackFunc = '';
	var syncReqFlag  = '';
	var oData = {
		updateType : type,
		updateID   : id,
		updateV    : valueList
	};
	sendData(url, targetID, callbackFunc, oData, syncReqFlag);
	
	if (dialog) {
		hideObject(dialog);
	}
}

function updateCheck(updateType, checkboxID, updateID, updateID2, targetID, tabIndex) {		// Update d-base when checkbox is set

														// updateType:     identifies the update category for case selection
														// checkboxID:     id of the checkbox object to refresh
														// updateID:       id of the database record to update
														// updateID2:      optional second id for cross-references
														// targetID:       span or div that holds the checkbox object
														// tabIndex:       optional tabIndex #											
	var checkedVal;
	
	if ( getObjectByID(checkboxID).checked ) {							// Get the value of this box if checked
		checkedVal = getValue(checkboxID);
	} else {
		checkedVal = '0';
	}

	var url          = 'subs-UpdateCheckbox.php';
	var callbackFunc = '';
	var syncReqFlag  = '';
	var oData = {
		updateType  : updateType, 
		checkboxID  : checkboxID, 
		updateID    : updateID, 
		updateID2   : updateID2, 
		updateValue : checkedVal, 
		targetID    : targetID, 
		tabIndex    : tabIndex
	};

	sendData(url, targetID, callbackFunc, oData, syncReqFlag);
}

function updateCheckbox(type, id, checkboxID, targetID, valueList) {		// * * Deprecated: use updateCheck() instead * *

														// Update the database when a checkbox is checked via updateForm
														//	type:       unique identifier for this request; passed to server
														//	id:         ID of the record to be updated
														//	checkboxID: ID of the checkbox
														//  targetID:   if HTML is returned, what div or span will be updated?
														//	valueList: optional pipe-delineated values to send along with the data
	var checkedVal;
	
	if ( getObjectByID(checkboxID).checked ) {							// Get the value of this box if checked
		checkedVal = getValue(checkboxID);
	} else {
		checkedVal = '';
	}
	
	if (valueList) {													// include valueList
		checkedVal += "|" + valueList;
	}
	
	var url          = 'subs-Update.php';
	var callbackFunc = '';
	var syncReqFlag  = '';
	var oData = {
		updateType : type,
		updateID   : id,
		updateV    : checkedVal
	};
	sendData(url, targetID, callbackFunc, oData, syncReqFlag);
}


function sortRecord(sortType, recordID, parentRecID, currentPos, sortDirection) {	// Change record's position in a table

									// 	sortType:       identifies which table and columns to update on the server
									// 	recordID:       id of the row to update
									//	parentRecID:    (optional) parent category id for this record
									// 	currentPos:     the current position of the item to move
									//	sortDirection:  'up', 'down', or 'top'
	
	var url          = 'subs-sortRecord.php';
	var targetID     = '';
	var callbackFunc = '';
	var syncReqFlag  = '';
	var oData = {
		sortType      : sortType,
		recordID      : recordID,
		parentRecID   : parentRecID, 
		currentPos    : currentPos,
		sortDirection : sortDirection
	};
	sendData(url, targetID, callbackFunc, oData, syncReqFlag);
}
