//################################################################################################################################			
// form_functions_<version>.js
//
// This is the script of controlling routines called by the form_validation script.
// Each modification needs to be commented in the history below.
// Each modification requires this file be saved as a new version (incremental filename), and should be referenced in the 
// includes/html/javascripts.asp include file.
//
//################################################################################################################################			
// Modification History:
// Version	Date		Initials	Comments
// v1.01	16/09/2004	SBH			Found fundamental flaw in setFieldValue routine - cannot work for readio groups. Created
//									seperate routine for radio groups.
// v1.02	28/11/2006	SBH			Added containsProhibitedCharacters routine and older checkValidCharacterList routine.
// v1.03	16/06/2007	SBH			Added isValidDate routine (taken from InCase).
//################################################################################################################################			


//#####################################################################################################			
function setFieldValue(thisFormName) {
	var setStr;
	var thisElementType;
	setStr = "document." + thisFormName + "." + thisFieldName + ".type";
	thisElementType = eval(setStr);
	
	if (thisElementType == "checkbox") {
		setStr = eval("document." + thisFormName + "." + thisFieldName + ".checked");
		if (setStr == true) {
			setStr = "document." + thisFormName + "." + thisFieldName + ".value";
		}
		else {
			setStr = "";
		}
	}
	else {
		setStr = "document." + thisFormName + "." + thisFieldName + ".value";
	}
	if (setStr != "") {
		thisFieldValue = eval(setStr);
	}
	else {
		thisFieldValue = "";
	}
}
//#####################################################################################################			


//#####################################################################################################			
function setRadioFieldValue(thisFormName) {
	var setStr = "";
	var objRadioGroup = eval("document." + thisFormName + "." + thisFieldName);

	for (var i = 0; i < objRadioGroup.length;i++) {
		if (objRadioGroup[i].checked) {
			//set return field as value for this button in the group and break:
			setStr = objRadioGroup[i].value;
			break;
		}
	}
	thisFieldValue = setStr;
}
//#####################################################################################################			


//#####################################################################################################			
function updateFieldValue(thisFormName, thisFieldName, thisFieldValue) {
	var objField;
	var updateStr;
	objField = eval("document." + thisFormName + "." + thisFieldName);
	objField.value = thisFieldValue;
}
//#####################################################################################################			


//#####################################################################################################			
//function providing the equivalent of a maxlength constraint, but for pesky textarea fields:
function checkMaxLength(thisFormName, thisFieldName, thisMaxLength) {
	var objField, strCurrentFieldValue, iCurrentLength;
	objField = eval("document." + thisFormName + "." + thisFieldName);
	strCurrentFieldValue = objField.value;
	iCurrentLength = strCurrentFieldValue.length;

	if (iCurrentLength > thisMaxLength) {
		alert("Maximum field size reached.");
		objField.value = strCurrentFieldValue.substr(0,100);
		return false;
	}
}
//#####################################################################################################			


//#####################################################################################################			
function y2k(number) { 
	return (number < 1000) ? number + 1900 : number; 
}
//#####################################################################################################			

//#####################################################################################################			
function isDate (day,month,year) {
// checks if date passed is valid
// will accept dates in following format:
// isDate(dd,mm,ccyy), or
// isDate(dd,mm) - which defaults to the current year, or
// isDate(dd) - which defaults to the current month and year.
// Note, if passed the month must be between 1 and 12, and the
// year in ccyy format.
	
	//alert("day: " + day + ", month: " + month + ", year: " + year);
    var today = new Date();
    year = ((!year) ? y2k(today.getYear()):year);
    month = ((!month) ? today.getMonth():month-1);
    if (!day) return false
    var test = new Date(year,month,day);
    if ( (y2k(test.getYear()) == year) &&
         (month == test.getMonth()) &&
         (day == test.getDate()) )
        return true;
    else
        return false
}
//#####################################################################################################			


//#####################################################################################################			
function focusField(focusState, formname, fieldname, defaultvalue) {
//if (defaultvalue) {alert("not null")}
//else {alert("null")}
	var jsString;
	switch (focusState) {
	case 0:
		if ( defaultvalue && eval("document." + formname + "." + fieldname + ".value") == "") {
			eval("document." + formname + "." + fieldname + ".value = '" + defaultvalue + "'")
		}
		break;
	case 1:
		if (defaultvalue && eval("document." + formname + "." + fieldname + ".value") == defaultvalue) {
			eval("document." + formname + "." + fieldname + ".value = '' ")
		}
		break;
	}

}
//#####################################################################################################			


//#####################################################################################################			
function selectAll(paramFormName, paramFieldName) {
	var jsStr;
	jsStr = "document." + paramFormName + "." + paramFieldName + ".select();";
	eval(jsStr);
}
//#####################################################################################################			


//#####################################################################################################			
function resetForm(formname) {
   var jsString;
   jsString = "document." + formname + ".reset();";
   eval(jsString);    
}
//#####################################################################################################			


//#################################################			
function submitForm(formname) {
	//alert("form: " + formname)
	if (validateForm(formname)) {
   		//alert("form validated");
		var jsString;
   		jsString = "document." + formname + ".submit();";
		//alert(jsString); return false;
		eval(jsString);    
	}
	//alert("done");
}
//#####################################################################################################			


//#################################################
function isValidDate (wholedate, bBlankOK) {
	// checks if date passed is valid
	// a single date is passed in, with a boolean value
	// which is set to true (can be blank) or 
	// false (must be populated with a date), 
	// which is then validated.
	// Date is split by / divider
	
	if (bBlankOK && wholedate == "") {
		return true;
	}
	else {
		var dateParts = wholedate.split("/");
		//alert(dateParts.length);
	
		if (dateParts.length < 3){
			return false;	
		}
		if (dateParts[0].length < 1 || dateParts[0].length > 2) {
			return false;
		}
		if (dateParts[1].length < 1 || dateParts[1].length > 2) {
			return false;
		}
		if (dateParts[2].length < 4 || dateParts[2].length > 4) {
			return false;
		}	
	
		var isDateResult = isDate(dateParts[0],dateParts[1],dateParts[2]);
		//alert(dateParts[0] + "/" + dateParts[1] + "/" + dateParts[2] + " - isDateResult=" + isDateResult);
		if (isDateResult == true) {
			return true;
		}
		else
		{
			return false;
		}
		//alert(isDateResult);
	}
}
//#################################################		

//#####################################################################################################			
function isValidPostCode(thisPostCode) {
	//modify to postcode pattern
	thisPostCode = thisPostCode.toUpperCase();
			
	//split into outcode and incode (outcode = TR22;	incode = 4PY)
	var codelength = thisPostCode.length;
	var outcode, incode;
	outcode = thisPostCode.substr(0, codelength-3);
	if (outcode.indexOf(" ") > -1) {
		outcode = outcode.substr(0, outcode.length-1)
	}
	incode = thisPostCode.substr(codelength - 3);
	
	//alert("orig=(" + thisPostCode + ")");
	//alert("new=(" + outcode + ")(" + incode + ")");

	var postCodeRegExp;
	var postCodeOK = false;
				
	//validate incode
	postCodeRegExp = /^\d[A-Z]{2}$/;
	if (postCodeRegExp.test(incode)) {postCodeOK = true}
	//alert("postCodeOK=" + postCodeOK);

	if (postCodeOK) {
		//reset flag for incode checks:
		postCodeOK = false;
		//validate mainstream outcode permutations
		postCodeRegExp = /^[A-Z]{1,2}\d{1,2}$/;
		if (postCodeRegExp.test(outcode)) {
			postCodeOK = true;
			//alert("mainstream ok");
		}
		else {
			//alert("mainstream failed...");
			//validate exception outcode permutations
			postCodeRegExp = /^[A-Z]{1,2}\d[A-Z]$/;
			if (postCodeRegExp.test(outcode)) {
				postCodeOK = true;
				//alert("exception okay.");
			}
			//else {
			//	alert("exception failed");
			//}
		}
	}
		
	/////////////////////////////////
	//alert("(" + outcode + ")(" + incode + ")");
	//re-insert postcode components with space
	if (postCodeOK) {
		thisPostCode = outcode + " " + incode;
	}
	else {
		thisPostCode = false;
	}
	return thisPostCode;
}
//#####################################################################################################			


//#####################################################################################################			
function containsProhibitedCharacters(paramStringContext, paramString) {
	//paramStringContext: "document"
	//paramFieldDescription: the user friendly label used in the error message, e.g. "document name"
	//paramString: the user's specified entity name, e.g. "Motivational Skills for Tutors v1.00" (which would be disallowed of course)

	var strProhibitedCharacterList;
	var strEntityDescriptor;
	var strCorrectiveActionText;
	var strErrorText;
	
	strProhibitedCharacterList = "";
	strEntityDescriptor = "[unspecified entity type]";
	strCorrectiveActionText = "Please replace this character and re-try.";
	strErrorText = "";
	
	//determine the prohibition list based on the type of entity being named/edited:
	switch (paramStringContext) {
	case "document":
		strProhibitedCharacterList = "/\.!%^&*?:;#";
		strEntityDescriptor = "document name";
		strCorrectiveActionText = "Please specify the " + strEntityDescriptor + " without use of this character.";
		break;
	case "poll_question":
		strProhibitedCharacterList = "#";
		strEntityDescriptor = "question";
		break;

	case "search":
		strProhibitedCharacterList = "/\.!%^&*?:;#";
		strEntityDescriptor = "search text";
		strCorrectiveActionText = "Please specify the " + strEntityDescriptor + " using words and numbers only.";
		break;

	case "upload":
		strProhibitedCharacterList = "/\!%^&*?;#";
		strEntityDescriptor = "upload URL";
		strCorrectiveActionText = "Please specify the " + strEntityDescriptor + " without this character.";
		break;

	case "vacancy_description":
		strProhibitedCharacterList = "#";
		strEntityDescriptor = "vacancy description";
		break;

	case "webform":
		strProhibitedCharacterList = "#";
		strEntityDescriptor = "web form";
		strCorrectiveActionText = "Please specify the " + strEntityDescriptor + " without this character.";
		break;

	}
	
	//look for prohibited characters in the incoming name:
	for (var iCharPos = 0; iCharPos < paramString.length; iCharPos++) {
		if (strProhibitedCharacterList.indexOf(paramString.charAt(iCharPos)) >  -1)  {
			strErrorText 	= "You have used an illegal character  (" + paramString.charAt(iCharPos) + ") in the " + strEntityDescriptor + ".\n\n"
							+ strCorrectiveActionText + "\n\n"
		  	        		+ " [Error code:" + paramString.charCodeAt(iCharPos) + "]";
			alert(strErrorText);
			//  alert("At position " + iCharPos + ": " + elementValue.charCodeAt(iCharPos));
			return true;
		}
	}

	return false;
}
//#####################################################################################################			


//#####################################################################################################			
function allFormCharactersValid(formname) {
	//Run through all fields in the form, checking for invalid characters
	var validList, extraValidList;
	var arrApostropheSubstitutionList;
	var arrHyphenSubstitutionList;
	
	validList = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,._?@£$&%!-/:;=<>()'" + '"';
	extraValidList = new Array(9,10,13,92);
	arrApostropheSubstitutionList = new Array(0,8217);
	arrHyphenSubstitutionList = new Array(0,8211);
	
	var bExtraValidValueFound;
	var elementLoop, elementvalue, elementName, elementType, numberOfElements;
	numberOfElements = eval("document." + formname + ".elements.length");
	for (elementLoop=0; elementLoop<numberOfElements; elementLoop++) {
		elementValue = eval("document." + formname + ".elements[" + elementLoop + "].value");
		elementName = eval("document." + formname + ".elements[" + elementLoop + "].name");
		elementType = eval("document." + formname + ".elements[" + elementLoop + "].type");

		//alert(elementLoop + "/" + elementName + "/" + elementType + "/" + elementValue + "(" + elementType.indexOf("text") + ")");
		if (elementType.indexOf("text") > -1) {
			for (var charPos = 0; charPos < elementValue.length; charPos++) {

				//weird apostrophe substitution:
				for (var iApostropheLoop=0; iApostropheLoop < arrApostropheSubstitutionList.length; iApostropheLoop++) {
					//alert(iApostropheLoop + " = " + arrApostropheSubstitutionList[iApostropheLoop]);
					if(elementValue.charCodeAt(charPos) == arrApostropheSubstitutionList[iApostropheLoop]) {
						elementValue = elementValue.substr(0,charPos) + "'" + elementValue.substr(charPos+1);
					}
				}
				
				//weird hyphen substitution:
				for (var iHyphenLoop=0; iHyphenLoop < arrHyphenSubstitutionList.length; iHyphenLoop++) {
					//alert(iHyphenLoop + " = " + arrHyphenSubstitutionList[iHyphenLoop]);
					if(elementValue.charCodeAt(charPos) == arrHyphenSubstitutionList[iHyphenLoop]) {
						elementValue = elementValue.substr(0,charPos) + "-" + elementValue.substr(charPos+1);
					}
				}
				
				//see if character is in the extended list fist (quicker to check):
				bExtraValidValueFound = false;
				for (var iValidLoop=0; iValidLoop < extraValidList.length; iValidLoop++) {
					if(elementValue.charCodeAt(charPos) == extraValidList[iValidLoop]) {
						bExtraValidValueFound = true;
						break;
					}
				}
			
				//if still not validated, check the mainstream list of valid characters:
				if (bExtraValidValueFound == false) {
					if (validList.indexOf(elementValue.charAt(charPos)) == -1)  {
		    	      alert("A non-valid character (" + elementValue.charAt(charPos) + ") has been entered on this form, within the entry:\n\n'..." 
					  + elementValue.substring(charPos-10, charPos+10) + "...',\n\nPlease amend and submit the form again.\n\n"
				      + " [Error code:" + elementValue.charCodeAt(charPos) + "]");
					//  alert("At position " + charPos + ": " + elementValue.charCodeAt(charPos));
					  return false;
					}
				}
			}
    	}
	}
	//alert("all done");
	return true;
}
//#####################################################################################################			

