/**
*	common_forms.js	$Revision: 8 $  $JustDate: 2009-11-18 $
* a generic library of client-side JavaScript functions for processing and validating Web forms
* Created by Clark Christensen, TAIS CSD;
* Copyright (C) 2005, Toshiba America Information Systems, Inc.
* All rights reserved.
* Please see common_forms_doc.html in this directory for documentation of these functions.
* $NoKeywords: $
**/

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// reOrderList(list_to_reorder, direction)
//	Moves selected item up or down within a listbox
//		object:list_to_reorder a SELECT object
//		integer:direction -1=up; 1=down
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function reOrderList(loList, liOp) {
	var si = loList.selectedIndex;											// source or selected index
	if (si == -1) {														// make sure an item is selected
		alert("\\nPlease select an item to move!\\n");
		return;
	}											
	var ti = si + liOp;														// target index
	if (ti == loList.options.length || ti == -1) {
		return;																// do nothing if ti is out of range
	}
	var loReplacedOption = {text:loList.options[ti].text, value:loList.options[ti].value};
	var loMovedOption = {text:loList.options[si].text, value:loList.options[si].value};
	loList.options[ti].text = loMovedOption.text;
	loList.options[ti].value = loMovedOption.value;
	loList.selectedIndex = ti;
	loList.options[si].text = loReplacedOption.text;
	loList.options[si].value = loReplacedOption.value;
}  // end function
	

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//	select_list_value(target_list, value_to_match[, 'value'|'text'])
//	Select the target_list option where the value == value_to_match
// 	target_list is a list object reference for the list you want to search/set
//		value_to_match is the search text or number
//		mode is a string representing whetner you want to match against the option value
//			or option text.  Default is 'value'.
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function select_list_value(loList, inVal, lsMode) {
	lsMode = (lsMode || 'value');
	for (var i=0; i<loList.options.length; i++) {
		loList.options[i].selected = (loList.options[i][lsMode] == inVal);
	}
}

// =====================================
// notify user of failed form validation
// =====================================
function notifyUser(t) {
	var lsAppendText = '';
	var message = "\n" + t.text + lsAppendText + "\n\n";
	alert(message);
	return;
}

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ++ FORM VALIDATION SECTION
// in this function 'i' contains the name of the field being tested
// the SWITCH statement requires IE4+ or Netscape 4+
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function validateForm(it, fieldList) {
	if (! fieldList) {
		alert('DATA ERROR!\n\nvalidateForm()\n\nfieldList not specified.\n\nNo fields to test in form: ' + it.name + '\n');
		return false;
	} 
	var cfr, lsFieldValue, lbIsInRange, ckd, expr, s, reZipCode, reNumber, reText, zz, lsltValue, lbLocalTest, lsSuccessMessage;
	for (var i in fieldList) {
		switch (fieldList[i].datatype) {
			case 'custom' :	// Custom function
				expr = 'var cfr = ' + fieldList[i].text + '(it)';	// build an expression
				eval(expr);		// execute the expression
				if (! cfr) {
					return false;
				}
				break;

			case 'email' :		// email address
//				if (emailCheck(it.elements[i], fieldList[i].text) == 0) {
				if (!/^[-a-z0-9._]+\@[-a-z0-9._]+\.([a-z]{2,4}|museum)$/i.test(it.elements[i].value)) {
					if (fieldList[i].text === '') {
						fieldList[i].text = 'The email address you provided is incomplete or contains illegal characters.\nPlease provide only one email address and verify that it\'s correct.';
					}
					notifyUser(fieldList[i]);
					it.elements[i].focus();
					it.elements[i].select();
					return false;
				}
				break;

			case 'float' :		// floating-point type
				lsFieldValue = parseFloat(it.elements[i].value);
				lbIsInRange = (lsFieldValue >= fieldList[i].mlen && lsFieldValue <= fieldList[i].xlen);
				if (isNaN(lsFieldValue) ||  ! lbIsInRange) {
					notifyUser(fieldList[i]);
					it.elements[i].focus();
					it.elements[i].select();
					return false;
				}
				break;

			case 'integer' :		// integer type
				lsFieldValue = parseInt(it.elements[i].value, 10);
				lbIsInRange = (lsFieldValue >= fieldList[i].mlen && lsFieldValue <= fieldList[i].xlen);
				if (isNaN(lsFieldValue) ||  ! lbIsInRange) {
					notifyUser(fieldList[i]);
					it.elements[i].focus();
					it.elements[i].select();
					return false;
				}
				break;

			case 'radio' :		// Radio button array
//				eval('var s = it.' + i);
				s = it[i];
				ckd = true;
				if (s.checked) {ckd = false;}		//added to handle radio types with only one entry (not an array)
				for (var r=0; r < s.length; r++) {
					if (s[r].checked == "1") {
						ckd = false;
					}
				}
				if (ckd) {
					notifyUser(fieldList[i]);
					return false;
				}
				break;

			case 'select':		// SELECT list type
				if (it.elements[i].selectedIndex === 0 ) {
					notifyUser(fieldList[i]);
					it.elements[i].focus();
					return false;
				} else {
					zz = it.elements[i].selectedIndex;
					if (! it.elements[i].options[zz].value) {
						it.elements[i].options[zz].value = it.elements[i].options[zz].text;
					}
				}
				break;

			case 'text' :		// Text string
				reText = new RegExp("^[-a-zA-Z0-9_, ]{" + fieldList[i].mlen + ",}$");
				if (!reText.test(it.elements[i].value)) {
					notifyUser(fieldList[i]);
					it.elements[i].focus();
					it.elements[i].select();
					return false;
				}
				break;

			case 'numstring' :		// numeric string
				reNumber = new RegExp("^[0-9]{" + fieldList[i].mlen + "}$");
				if (!reNumber.test(it.elements[i].value)) {
					notifyUser(fieldList[i]);
					it.elements[i].focus();
					it.elements[i].select();
					return false;
				}
				break;

			case 'zip' :		// Zip code
				// make sure the first 5 chars are all integer digits
				reZipCode = /^[0-9]{5}(-[0-9]{4})*$/;
				if (!reZipCode.test(it.elements[i].value)) { // any criteria not met, message the user
					notifyUser(fieldList[i]);
					it.elements[i].focus();
					it.elements[i].select();
					return false;
				}
				break;
				
			default :		// default is text type
				alert('LIST ERROR!\n\nvalidateForm()\n\nField: ' + i + '\n\n\"' + fieldList[i].datatype + '\" is not a supported data type.\n');
				return false;
		}	// end switch
	}	// end for
	if (it.local_test) {	// added support for hidden field local_test to control submission to server
		lsltValue = it.local_test.value;
		if (lsltValue == 'true' || lsltValue == '1') {
			lbLocalTest = true;
		} else {
			lbLocalTest = false;
		}
	} else {
		lbLocalTest = false;
	}
	if (lbLocalTest) {
		lsSuccessMessage = 'SUCCESS!\n\nvalidateForm()\n\nAll tested fields in Form: \"' + it.name + '\" tested valid.\nThis form would have been submitted to the server.' ;
		alert(lsSuccessMessage);
		return false;
	} else {
		it.submit();
		return false;
	}
}  // End dataCheck


// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Prompt for value of "Other"
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function askOther(it) {
	var other = 'other';
	var si = it.selectedIndex;
	if (it.options[si].value == other || it.options[si].value.substr(0,6) == "Other:" ) {
		var entry = prompt("You selected \"Other\". Please specify:", "");
		if (entry) {
			it.options[si].value = "Other: " + entry;
			it.options[si].text = "Other: " + entry;
			it.selectedIndex = si;
			it.focus();
		} 
	}
	return;
}

// ==============================================
// Check for illegal characters in Email address
// ==============================================
function emailCheck(it, st) {
//	(st == null) ? st = '' : st = st;
	st = (st || '');
	var usrtxt = it.value;
	var badchars = false;
	var reqchars = (usrtxt.indexOf("@") == -1 || usrtxt.indexOf(".") == -1);
	var badlist = ['\\', '/', ',', ' ', '<', '>', '`', '|'];
	for (var bc=0; bc < badlist.length; bc++) {
		if (usrtxt.indexOf(badlist[bc]) > -1) {
			badchars = true;
			break;
		}
	}
	if (usrtxt.length < 7 || badchars || reqchars) {
      var message = 'The email address you provided is incomplete or contains illegal characters.\nPlease provide only one email address and verify that it\'s correct.';
      alert( ((st)?st + '\n\n':'') + message);
		it.focus();
		it.select();
      return 0;
  } // end if 
} // end e-mail check

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Constructor function for data check text
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function fieldTest(t, dt, nm, nx) {
	this.text = t;			// Display text for error message
	this.datatype = dt;	// Data type
	this.mlen = nm;		// Minimum length (for text) or minimum value (for integer) or custom function name (for custom)
	this.xlen = nx;		// Maximum value for integer
}


// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Tool function for listing fields in a form
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function showElements(it, opt) {
//	(opt == '' || opt == null) ? opt = 1 : opt = opt;
	var lastindex, message, ecount, infoWin;
	message = '';
	ecount = 0;
	for (var i = 0; i < it.elements.length; i++) {
		lastindex = (i)?i-1:1;
//		(i === 0) ? lastindex = 1 : lastindex = i - 1;
		if (it.elements[i].name != it.elements[lastindex].name) {
			ecount++;
			switch (opt) {
				case 1 :			// List the field names and types (tab-delimited plain text)
					message += String(ecount) + ':\t' + it.elements[i].name + '\t' + it.elements[i].type + '\n';
				break;
				case 2 :			// List the field names comma separated and surrounded by single quotes (for building an array in Perl or JavaScript)
					message += "\'" + it.elements[i].name + "\', ";
				break;
				case 3 :			// create checkWhat() function body
					message += "item['" + it.elements[i].name + "'] = new fieldTest(\"" + it.elements[i].name + " is required\", " + it.elements[i].type + ");\n";
				break;
				default :		// HTML list of elements in a name-value pair format
					message += String(ecount) + ': name=' + it.elements[i].name + '&nbsp;&nbsp;type=' + it.elements[i].type + '<br>\n';
			}
		}
	}
	infoWin = window.open('', 'infoWin');
	infoWin.document.write(message);
	return;
}	

