
function trim(str) { return str.replace(/(^\s+)([^\s]*)(\s+$)/, '$2'); }
function endsWith(str, pattern) {
  var a=str.substring(str.length - pattern.length);
  return (a == pattern);
}
function startsWith(str, pattern) {
  var a=str.substring(0, pattern.length);
  return (a == pattern);
}
function rightMouseClick() {
  if (document.all && event.button != 1) {
    alert('For more information please contact ITS, Inc. http://javaschool.com');
    return false;
  }
}
//document.onmousedown = rightMouseClick
function countCharacters(c, content) {
	var i=0; // starting character in the content
	var n=0; // number of 'c' characters 
	while(i <= content.length) {

		if (content.substring(i,i+1) == c) {
			n++; 
		}
		i++;
	}
	return n;
}
function resendPassword(form) {
	var email = form.email;
	if(!validateEmailAddress(email)) {
		return;
	}
	form.psw.value=' i';
	if(form.title.value == '') {
		form.title.value=' ';
	}
	if(form.content.value == '') {
		form.content.value=' ';
	}
	setAction(form, '/its.web/ContentAction.do?action=resendPassword');
	form.msg.value = 'Your access has been restored. Please check your email for instructions';
	form.submit();
}
function countWords(content){
	var i=0;
	var numberofwords=1;

	while(i <= content.length) {
		if (content.substring(i,i+1) == ", ") {
			numberofwords++;
			i +=2; 
			// extra i++ makes it skip double spaces, or space/return
		}
		if (content.substring(i,i+1) == " ") {
			numberofwords++;
			i++; 
			// extra i++ makes it skip double spaces, or space/return
		}
		if (content.substring(i,i+1) == ",") {
			numberofwords++;
			i++; 
			// extra i++ makes it skip double spaces, or space/return
		}		
		if (content.substring(i,i+1) == "\n") {
			numberofwords++;
			i++;
			// extra i++ makes it skip double spaces, or space/return
		}
		i++;
	}
	return numberofwords;
}
function inputFocus() {
	var forms = document.getElementsByTagName('form');
	for(var i=0; i < forms.length; i++) {
		var form = forms[i];
		if(form.inputField != null && form.inputField.type == 'text') {
			form.inputField.focus();
			//alert('Done!');
			return;
		}
	}
}
function setAction(form, actionName) {
	if(actionName != '') {
		if(form.action.type == 'hidden') {
			form.action.value = actionName;
		} else {
			form.action = actionName;
		}
	}
}
function setActionAndField(form, actionName, fieldName, value) {
//alert('action='+form.action.value);
	setAction(form, actionName);
	
	for (var i=0; i < form.elements.length; i++)
	{
		var e = form.elements[i];
		var name = e.name;	
		if(name == fieldName) {
			e.value = value;
			break;
		}
	}
//alert('setActionAndField (before submit):actionName='+actionName + ' fieldName='+fieldName+' form.action='+form.action);	
	form.submit();
}
function setActionKey(form, actionName, key) {
//alert('setActionKey:actionName='+actionName + ' key='+key);
	if(actionName != '') {
		form.action.value = actionName;
	}
	form.key.value = key;
	form.submit();
}
function checkRelatedTopic(form) {
	var topic = form.relatedTopic.value;
	var description = form.inputField.value;
	if(topic == 'Select Related Business Process') {
		alert('Select Related Business Process');
		return false;
	}
	if(description == '') {
		alert('Describe relationships between the processes');
		return false;
	}
	return true;
}
function checkKeyFields(form) {
	if(!checkEmptyTextFields(form)) {
		return false;
	}
	var description = form.description.value;
	var keys = form.keywords.value;
	return checkKeyDescription(description, keys);
}
function checkScenarioFields(form) {
	if(!checkEmptyTextFields(form)) {
		return false;
	}
	var xml = form.scenario.value;
	var nOfstartingTags = countCharacters('<', xml);
	var nOfClosingTags = countCharacters('>', xml);
	if(nOfstartingTags == 0 || nOfstartingTags != nOfClosingTags) {
		alert('Not a valid XML scenario. Please correct');
		return false;
	}
	var descriptionObject = form.scenarioDescription;
	if(descriptionObject == null) {
		return true;
	}
	var description = form.scenarioDescription.value;
	var keys = form.scenarioKeywords.value;
	return checkKeyDescription(description, keys);
}
function checkKeyDescription(description, keys) {			
	var nDescriptionWords = countWords(description);
	if(nDescriptionWords < 2) {
		alert('It does not look like a good complete description. Please improve:-)');
		return false;
	}	
	nDescriptionWords = countWords(keys);
	if(nDescriptionWords < 2) {
		alert('Please provide more keywords describing this scenario');
		return false;
	}
	return true;
}
function setActionAndCheckEmptyFields(form, actionName) {
	if(!checkEmptyTextFields(form)) {
	    return;
	}
	form.action.value = actionName;
	doubleClick();
	form.submit();
}
function startsWith(str, pattern) {
	var a=str.substring(0, pattern.length);
	return (a == pattern);
}
function init(msg) {
	if(msg == null || msg == 'noAlert' || msg == 'null') {
		return;
	}
	if(msg != null && msg != 'noAlert' && msg != 'null') {
		alert(msg);
	}
}
// allow ONLY numeric keys, no symbols or punctuation
var numbers = "0123456789";
// this can be altered for any "alphabet" string you desire
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
function isValidSet(field, checkOK) {
	if(!isValidString(field, checkOK) ) {
		if(field.value == '') {
		    return false;
		}
		var fieldName = field.name;
		alert('Only following characters allowed in the '+fieldName + ': '+checkOK);
		field.focus();
		return false;
	}
	return true;
}
function isValidNumber(field) {
	if(!isValidString(field, numbers) ) {
		if(field.value == '') {
		    return false;
		}
		var fieldName = field.name;
		alert('Only number is allowed in the '+fieldName);
		field.focus();
		return false;
	}
	return true;
}
function isValidString(field, checkOK) {
	var checkStr = field.value;	
	var fieldName = field.name;
//alert('fieldName='+fieldName+' value='+checkStr);	
	if(checkStr == '') {
		alert('Please enter the '+fieldName);
		return false;
	}	
	var allValid = true;
	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		if (ch == checkOK.charAt(j))
			break;
		if (j == checkOK.length)
		{
			allValid = false;
			break;
		}
	}
	if (!allValid)
	{
		return (false);
	}
	return true;
}

function checkBid(form) {
	var betField = form.bet;
	var cashField = form.totalCash;
	var bid = form.bet.value;	
	var cash = form.totalCash.value;
//alert('form='+form);
//alert('cash='+cash+' bet='+bid);
	if(!isValidNumber(betField)) {
		return false;
	}	
	if(bid == 0) {
		alert('Please enter 1 or a greater number in the bet field');
		return false;
	}
	//return checkCash(form);
	return true;
}
function checkCash(form) {
	var betField = form.bet;
	var cashField = form.totalCash;
	var bid = form.bet.value;	
	var cash = form.totalCash.value;
	if(!isValidNumber(cashField)) {
		return false;
	}
	
	if(cash == 0 || cash < bid*9) {
		alert('Please enter at least ' + bid*9 + 
		' or a greater number in the Total Cash field');
		return false;
	}		
	return true;
}
function beGuest(form) {
    form.username.value = 'guest';
    form.password.value = 'guest';
}
function setLogin(form, username, psw) {
    form.username.value = username;
    form.password.value = psw;
    form.submit();
}
function hideCells(id) {
  cells = document.getElementsByName(id);
  for(j = 0; j < cells.length; j++) cells[j].style.display = 'none';
}
function showCells(id) {
  cells = document.getElementsByName(id);
  for(j = 0; j < cells.length; j++) cells[j].style.display = 'block';
}
function configureLog(action) {
	var html = "<html><body><b>Configure File Location and Processing Patterns</b>"+
	"<form name=configureLogForm action="+action+" method=post>\n"+
	"<table border=1><tr><th>Hostname</th><th>Path to the file</th></tr>\n"+
	"<tr><td><input type=text name=hostname size=10></td>"+
	"<td><input type=text name=filename size=30></td></tr>\n<tr>"+
	"<td colspan=2><b>List important patterns with a coma separator</b></td>"+
	"</tr><tr><td colspan=2><textarea name=patterns cols=40 rows=3></textarea>"
	"</td></tr><tr><td><input type=submit name=submit value=Submit></td"+
	"<td><input type=button value=Cancel onclick=window.close()></td></tr>"+
	"</table></form></body></html>";
	var win = launchNewWindow("", 300, 300);
	win.document.write(html);
}
// copy values from the form to parent form and submit
function parentSubmit(form, action) {
	var pform = document.forms[0];
	pform.action = action;
	
	for (var i=0; i < form.elements.length;i++)	{
		var e = form.elements[i];
		var name = e.name;	
		var type = e.type;
		var value = e.value;
		if(type == 'text' || type == 'textarea' || type == 'hidden' || type == 'password') {
			for (var j=0; j < pform.elements.length; j++)	{
				var pe = pform.elements[j];
				var pname = pe.name;
				var ptype = pe.type;
				if(pname == name) {
				    if(type == 'textarea' && ptype == 'text') {
				    	value = value.replace(/\r\n/, " ");
				    	value = value.replace(/\n/, " ");
				    }
					pe.value = value;
				}	
			}
		}
	}
	pform.submit();				
}
// stringOfArgs: "/its.web/ServiceAction.do?action=actionName&edit=edit2&predicate=p&etc"
// this function will launch the window with the textarea for editing
function editTextWindow(label, stringOfArgs, fieldName, form) {
	var html = "<html><head><title>Edit Text and Submit Changes</title></head>"+
	"<body><b>"+label+"</b><br>\n"+
	"<form name=inputForm>\n";
//alert('fieldName='+fieldName + ' args='+stringOfArgs);	
	var textFieldValue = '';
	for (var j=0; j < form.elements.length; j++)
	{
		var e = form.elements[j];
		var name = e.name;	
		if(name == fieldName) {
			textFieldValue = e.value;
			break;
		}
	}
//alert('textFieldValue='+textFieldValue);
	html += "\n<table border=1><tr><td><input type=hidden name=edit"+
	" value='"+textFieldValue+"'></td></tr>\n"+
	"<tr><td><textarea name=inputField cols=60 rows=5>"+
	textFieldValue+"</textarea>"+
	"</td></tr>\n<tr><td><input type=button name=submit value=Submit "+
	"onclick=opener.parentSubmit(document.inputForm,'"+stringOfArgs+
	"');self.close()> "+
	"<input type=button value=Cancel onclick=window.close()></td></tr>"+
	"</table></form></body></html>";
	var win = launchNewWindow("", 600, 300);
	win.document.write(html);
}
function printButton() {
document.write('<form><input type="button" value="Print" onClick="parent.frames[1].focus();parent.frames[1].print()"><\/form>');
}
function launchNewWindow(location, width, height) {
    var x = Math.round((screen.width - width)/2);
    var y = Math.round((screen.height - height)/2);
    var windowFeatures = 'menubar=no,toolbar=no,location=no,status=no,scrollbars=auto,resizable=yes,maximize=no';
    var myWin = open(location,'_blank','left='+x+',top='+y+',width='+width+',innerWidth='+width+',height='+height+',innerHeight='+height+','+windowFeatures);
    return myWin;
}
function getDate() {
	var dateString = new Date();
	var day = dateString.getDate();
	var month = dateString.getMonth()+1;
	var hour = dateString.getHours();
	var min = dateString.getMinutes();
	if(min <=9 ) {
	    min = '0'+min;
	}
	var year = dateString.getYear();
	return (month+'/'+day+"/"+year+' '+hour+':'+min);
}
function writeNameAndDate(name) {
	var date = getDate();
	document.write('<u>' + name + '</u> ' + date);
}
// disable all buttons
function doubleClick() {
	for(var n=0; ; n++) {
		var aForm = document.forms[n];
		if(aForm == null) {
		    return;
		}
		for (var i=0; i < aForm.elements.length;i++)
		{
			var e = aForm.elements[i];
			if(e.type == "button" || e.type == "submit") {
				e.disabled = true;
			}
		}
	}
	return true;
}
function checkPassword(aForm) {
//alert('aForm.username.value='+aForm.username.value);
	if(aForm.username.value == '' || aForm.username.value != aForm.password.value ||
	  aForm.password.value.length < 6) {
		alert('Please enter and confirm your password with at least 6 characters');
		return false;
	}
	return true;
}

function checkRegForm(aForm) {
	var psw = aForm.confirmed;
//alert('checkRegForm:psw='+psw);
	if(psw != null && !checkConfirmedPassword(aForm)) {
//alert('confirmed and password are not the same');
		return false;
	}
	return checkEmptyFields(aForm);
}
function checkTitleAndContent(aForm) {
	if(aForm.title.value == '' || aForm.content.value == '') {
		alert('Fill in Title and Content');
		return;
	}
	aForm.submit();
}
function validateEmailAddress(email) {	
	if(email != null) {
		var address = email.value;
		if(address.length < 5 || address.indexOf('@') < 2 || address.indexOf('.') < 3) {
			alert('Please provide valid email address');
			return false;
		}
	}
	return true;
}
function checkConfirmedPassword(aForm) {
	var psw = aForm.password.value;
	var confirmed = aForm.confirmed.value;
//alert('checkConfirmedPassword:psw='+psw+' confirmed='+confirmed);
	if(psw != confirmed) {
		alert('Please confirm password value');
		return false;
	}
	return true;
}

function validateNumberOfChecked(aForm, expectedNumber) {
//alert('aForm='+aForm + ' expectedNumber='+expectedNumber);
//alert('aForm.type='+aForm.type + ' aForm.elements='+aForm.elements);
	var numberOfChecked = 0;
	for (var i=0; i < aForm.elements.length;i++)
	{
		var e = aForm.elements[i];
		var name = e.name;
//alert('i='+i + ' e='+name + ' type='+e.type + ' checked='+e.checked);
		if(e.type == "checkbox" && e.checked) {
			numberOfChecked++;
		}
	}
	if(numberOfChecked != expectedNumber) {
		alert('You selected '+numberOfChecked + '. Please select '+ expectedNumber + ' required choices');
		return false;
	}
	doubleClick();
	return true;
}
// this function is usually called onsubmit
// to check for empty fields and guaranty a single submission
function checkEmptyTextFields(aForm) {
	// look for all elements/fields of the form
	for (var i=0; i < aForm.elements.length;i++) {
		var e = aForm.elements[i];
		var name = e.name;
		var value = e.value;
            var type = e.type;
		// specifically check two types of fields: text and password types
		if((type == 'text' || type == 'password') && 
               (value == null || value == '')) {
			var msg = 'Please fill in required fields: '+name+ ', etc.';
			alert(msg);
			return false; // will not allow submission
		}
		if(name == 'email') {
			if(!validateEmailAddress(e)) {
				return false;
			}
		}
	}
	// all fields are not empty!
	// prevent multiple submissions by disabling all buttons 
	return true; // will allow submission
}

function checkEmptyFields(aForm) {
//alert('checkEmptyFields:aForm='+aForm);

	var examTypeObject = aForm.examType;
//alert('checkEmptyFields:form.name='+aForm.name + ' examTypeObject='+examTypeObject);
//if(examTypeObject == null) {
// alert('examTypeObject == null');
//}
	for (var i=0; i < aForm.elements.length;i++)
	{
		var e = aForm.elements[i];
		var name = e.name;
		if(startsWith(name, 'optional')) {
//alert('startsWith.optional:name='+name);
			continue;
		}
		var value = e.value;
		if(examTypeObject != null) {
		  var examType = getCheckedValue(examTypeObject);
//alert('examType='+examType + ' name='+name + ' e.type='+e.type +' e.value='+e.value+'!');
          if(value != null) {
		      value = trim(value);
		  }
//alert('examType='+examType +'!');

		  if(examType != 'Team' && endsWith(name,'3')) {
		    continue;
		  }
//alert('name='+name);

		  if(examType != 'Team' && !endsWith(examType,'2') &&
		  	endsWith(name,'2')) {
		    continue;
		  }
		}
//alert('before email name='+name);
		if(examTypeObject == null && (endsWith(name,'2') || endsWith(name,'3'))) {
			continue;
		}
		if(startsWith(name,'email')) {
			if(!validateEmailAddress(e)) {
				return false;
			}
		}
		if((e.type == 'text' || e.type == 'password') && (value == null || value == '')) {
			var msg = 'Please fill in required fields: '+name+ ', etc.';
			if(examTypeObject != null) {
				var examType = getCheckedValue(examTypeObject);
				msg = 'For ' + examType + ' registration ' + msg;
			}
			alert(msg);
			return false;
		}
	}
	doubleClick();
//alert('finished checkEmptyFields');
	return true;
}
// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
//alert('radioObj='+radioObj);
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
//alert('radioLength='+radioLength);
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}
