//file java2,js
//created 15/1/5
//MJ Solomon
//default background & form focus colors
var formbg = "#ffffff";
var formfocusbg = "#CCCCFF";
//MJS
//check required variables then submit
//amended 12/02/2007 - MJS amajor rewrite
function checkSubmit(formObj,arrRequired,extramsg,debug){
   	var message = "";
	var first = "";
	var ffocus = "";
	for (var strCurrentKey in arrRequired) {
		if (debug == 'Y') {
			alert(strCurrentKey);
		}
		
		var otype; //set type
			
		var test = formObj[strCurrentKey];
		var reqname = strCurrentKey + '_req';
		var req = document.getElementById(reqname);
			
	  	//set req to hidden if exists
		if (String(req) != 'null') {
			req.style.visibility='hidden';
		}	
		
		if (! test.type ) {
			otype = 'MULTI';
						
			if (test[0].style.visibility == "hidden" || test[0].style.display == "none" ) {
				continue;
			}
			
		} else {
			if (test.disabled === true && test.type == 'select-one'){
				continue;
			}
			if (test.style.visibility == "hidden" || test.style.display == "none" ) {
				continue;
			}
			if (test.type == 'checkbox') {
				otype = test.type;
			} else { 
				otype = 'OTHER';
			}
		}
		
		var addtomessage = 'N';
		
		switch (otype) {
			case "MULTI":
				var check = "n";
				for ( var y = 0; y < test.length; y++) {
					if (test[y].checked === true) {
						check = "y";
					}
				}
			
				if (check == "n") {
					addtomessage = "Y";
				}
				break;
		
			case "checkbox":
				if (test.checked === false && test.disabled === false) {
					addtomessage = "Y";
				}
				break;
		
			case "OTHER":
				if (test.value === "" ) {
					addtomessage = "Y";
				} 
				break;
		} //end switch
		
		
		if (addtomessage == "Y") {
		
			if (String(req) != 'null') {
				req.style.visibility='visible';
				req.style.display='';
			}
						
			message = message + "\n" + arrRequired[strCurrentKey];
							
			if (first === "") {
				ffocus = strCurrentKey;
				ftype = otype;
				first = "y";
			}
		}
		
	} //end for
	
	//alert('END')
	
	//This code will prevent a submit if data is incorrect - display message or submit
	if (message !== "") { 
		checkSubmitMsg(formObj,message,debug,extramsg,ffocus);
	} else {
		checkSubmitEnd(formObj,debug);
	}
}
//---------------------------------------------------------------------------------
function checkSubmitMsg(formObj,message,debug,extramsg,ffocus){
	if (debug == 'Y') {
		alert('HIDE SUBMIT START');
	}
	hideSubmit(formObj,'N');
	if (debug == 'Y') {
		alert('HIDE SUBMIT END');
	}
		
	var mainmsg = "The following form field(s) were incomplete or incorrect:\n\n";
		
	if (extramsg) {
		mainmsg = extramsg + "\n\n" + mainmsg;
	}
		
	alert(mainmsg + message + "\n\n Please complete or correct the form and submit again.");
		
	var newfocus = formObj[ffocus].type;
	
	if( newfocus == "[object]" || ! newfocus || newfocus == "select-one"){
		location.hash=ffocus;
	} else {
		formObj[ffocus].focus();
	}
		
	return;
}
//----------------------------------------------------------------------------------------------
function checkSubmitEnd(formObj,debug){
	// mandatory fields have been filled in
	if (debug == 'Y') {
		alert('HIDE SUBMIT START');
	}
	hideSubmit(formObj,'Y');
			
	if (debug == 'Y') {
		alert('HIDE SUBMIT END SUBMITTING');
	}
			
	formObj.submit();
	
} //END function checkSubmitEnd
//----------------------------------------------------------------------------------------------
//hide save cancel buttons
function hideSubmit(formObj,hide){
	//alert('hs1')
	if(hide == "Y"){
		formObj.button1.style.display = "none";
		
		if (formObj.button2) {
			formObj.button2.style.display = "none";
		}
		formObj.submitting.style.display = "inline";
		formObj.submitting.disabled="true";
	} else {
		formObj.button1.style.display = "inline";
		if (formObj.button2) {
			formObj.button2.style.display = "inline";
		}
		if (formObj.submitting) {
			formObj.submitting.style.display = "none";
		}
		initialiseArrays();
	}
} //end hideSubmit
//----------------------------------------------------------------------------------------------
//MJS 18/1/5
//SUBMITS & CHANGES FORM ACTION AND ADDS HIDDEN VARIABLES
function submitAction(form,newaction,hiddenName,hiddenValue) {
	form.action=newaction;
	if (hiddenName) {
		for (i=0; i<hiddenName.length; i++) { 
			var x = form[hiddenName[i]];
			x.value = hiddenValue[i];
		}
	}
	form.submit();
}
//--------------------------------------------------------------------------------
// general function to format a field based on formattype property
function formatfield(fld,ftype,spaces) {
	var RetVal=fld.value;
	
	if (String(spaces) == 'undefined') {
		RetVal=trim(RetVal);
	}
			
	switch (ftype) {
		case "lower":
			RetVal=RetVal.toLowerCase();
			break;
		case "upper":
			RetVal=RetVal.toUpperCase();
			break;
		case "title":
			RetVal=titlecase(RetVal);
			break;
		case "name":
			RetVal=namecase(RetVal);
			break;
		case "alpha":
			RetVal=RetVal.toUpperCase();
			RetVal=alphaformat(RetVal,fld);
			break;
		case "number":
			RetVal=numberformat(RetVal,fld);
			break;
		case "money":
			RetVal=currencyformat(RetVal,fld);
			break;
		case "date":
			RetVal=dateformat(RetVal,fld);
			break;
		case "email":
			RetVal=emailCheck(fld,RetVal);
			break;
		case "nhs":
			RetVal=nhsCheck(RetVal,fld);
			break;
		case "emailUser":
			RetVal=emailCheckUser(fld,RetVal);
			break;
		case "pcode":
			RetVal=pcodeformat(RetVal);
			break;
		case "firstname":
			RetVal=firstnameformat(RetVal,fld);
			break;
		case "lastname":
			RetVal=lastnameformat(RetVal,fld);
			break;
		case "promo":
			RetVal = RetVal.replace(/[^A-Za-z0-9]/g , "");
			RetVal=RetVal.toUpperCase();
			break;
		case "jobtitle":
			RetVal=jtformat(RetVal,fld);
			break;
		case "datetime":
			RetVal=datetimeformat(RetVal,fld);
			break;
		case "date":
			RetVal=dateformat(RetVal,fld);
			break;
		case "yesno":
			RetVal=yesnoformat(RetVal,fld);
			break;
		case "datemysql":
			RetVal=datemysqlformat(RetVal,fld);
			break;
		case "url":
			RetVal=urlformat(RetVal,fld);
			break;
		case "day":
			RetVal=dayformat(RetVal,fld);
			break;
	}
	return RetVal;
}
//--------------------------------------------------------------------------------
// Checks for numbers only
function numberformat(myRetVal,myfld){
	var mytest =/[^0-9]/;
	if (myfld.value.match(mytest)){
		alert("This field can contain numbers only.\n Please re-enter using the correct format." );
   		setTimeout(function(){myfld.focus();}, 10);
	}
	return myRetVal;
}
//----------------------------------------------------------------------------------------------------------
// Checks for numbers only
// amended 15/02/2007
function currencyformat(myRetVal,myfld){
	if (myfld.value==='') {return myRetVal;}
	var mytest =/^[0-9]{0,6}[.]{0,1}[0-9]{0,2}$/;
	if (!(myfld.value.match(mytest))){
		alert("This field must be in the format 00.00\n Please re-enter using the correct format." );
		setTimeout(function(){myfld.focus();}, 10);
	}
	return myRetVal;
}
//----------------------------------------------------------------------------------------------------------
// Checks for numbers only
// amended 15/02/2007
function nhsCheck(myRetVal,myfld){
	if (myfld.value==='') {return myRetVal;}
	var mytest =/^[0-9]{3}\/[0-9]{3}\/[0-9]{4}$/;
	if (!(myfld.value.match(mytest))){
		alert("This field must be in the format ___/___/____ (10 numbers)\n Please re-enter using the correct format." );
		setTimeout(function(){myfld.focus();}, 10);
	}
	return myRetVal;
}
//----------------------------------------------------------------------------------------------------------

// Checks for day
function dayformat(myRetVal,myfld){ 
	var mytest =/[^0-9]/;
	if (myfld.value.match(mytest)){
		alert("This field can contain numbers only.\n Please re-enter using the correct format." );
		setTimeout(function(){myfld.focus();}, 10);
	}
	
	if (myfld.value === 0 || myfld.value > 31 ) {
		alert("This field must be a number between 1 and 31.\n Please re-enter using the correct format." );
    	setTimeout(function(){myfld.focus();}, 10);
	}
	return myRetVal;
}
//--------------------------------------------------------------------------------
function urlformat(myRetVal,myfld){
	if (myfld.value==='') {return myRetVal;}
	if (myfld.value=='http://') {return '';}
	
	urlStr=myRetVal;
	
	if (urlStr.indexOf(" ")!=-1){
		alert("Spaces are not allowed in a URL");
		setTimeout(function(){myfld.focus();}, 10);
		return urlStr;
	}
		
	urlStr=urlStr.toLowerCase();
	
	var urlPat=/^(ftp|http|https):\/\/(\w*)\.([\-\+a-z0-9]*)\.(\w*)/;
	var matchArray=urlStr.match(urlPat);
	if (matchArray===null){
		alert("The URL seems incorrect \ncheck it begins with http:// or http://\n and it has 2 .'s");
		setTimeout(function(){myfld.focus();}, 10);
		return urlStr;
	}
	
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var atom=validChars + '+';
		
	var user=matchArray[3];
	var domain=matchArray[4];
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("This domain contains invalid characters.");
			setTimeout(function(){myfld.focus();}, 10);
			return urlStr;
		}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("This domain name contains invalid characters.");
			setTimeout(function(){myfld.focus();}, 10);
			return urlStr;
		}
	}
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			alert("The domain name does not seem to be valid.");
			setTimeout(function(){myfld.focus();}, 10);
			return urlStr;
		}
	}
	
	var knownDomsPat=/\.(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|[a-z]{2})$/;
		if (! urlStr.match(knownDomsPat)) {
			alert("The address must end in a well-known domain or two letter " + "country.");
			setTimeout(function(){myfld.focus();}, 10);
			return urlStr;
		}
	return urlStr;
}
//--------------------------------------------------------------------------------
function alphaformat(myRetVal,myfld){
	var mytest =/[^A-Z]/;
	if (myRetVal.match(mytest) ) {
		alert("This field can contain alpha characters only.\n Please re-enter using the correct format." );
   		setTimeout(function(){myfld.focus();}, 10);
	}
	return myRetVal;
}
//---------------------------------------------------------------------------
//Mike Solomon 29/7/4 
function firstnameformat(myRetVal,myfld) {
	//var cLeft="", cRight=""
	if (myRetVal.length===0) {
		return myRetVal;
	
	}
	//strip non alpha
	var mytest = myRetVal;
	var msg = 'N';
	
	//test for alpha
	mytest = mytest.replace(/[^A-z]/g , "");
	if (mytest.length === 0) {msg = 'Y';}
	
	//make "and" invalid
	var invalidchars = myRetVal.replace(/ and /gi, ",,,");
	
	//test for invalid   
	invalidchars = invalidchars.replace(/[A-Za-z "'\-.,]/g, "");
	//var invalidchars = myRetVal.replace(/[A-z "'\-.]/g, "");
	invalidchars = invalidchars.replace(/[\xc0-\xff]/g, "");
	
	if (invalidchars.length > 0) {msg = 'Y';}
	if (msg == 'Y') {
		alert("The name entered must contain at least 1 alpha character.\nOnly Alpha characters and \" ' - are allowed\nThe word and is not allowed\n Please re-enter using the correct format." );
   //		
		setTimeout(function(){myfld.focus();}, 10);
	} else {
		myRetVal=namecase(myRetVal);
	}
	//strip .
	myRetVal= myRetVal.replace(/\./g, " ");
	myRetVal = myRetVal.replace(/ +/g, " ");
	return myRetVal;
			
} //end firstnameformat
//---------------------------------------------------------------------------
function lastnameformat(myRetVal,myfld) {
	//var cLeft="", cRight=""
	var msg = 'N';
	var testVal = myRetVal.toLowerCase();
	//alert(testVal);	
	if (myRetVal.length===0) {
		return myRetVal;
	}
	
	dupletter = new Array();
	var mytest = '';	
	for (var i=0; i<testVal.length; i++) {
		//alert(myRetVal.substr(i,1));
		if (dupletter[testVal.substr(i,1)] != testVal.substr(i,1)) {
		mytest = mytest + testVal.substr(i,1);
		dupletter[testVal.substr(i,1)] = testVal.substr(i,1);
		}
		
	}
	//strip non alpha
	mytest = mytest.replace(/[^A-z]/g , "");
	if (mytest.length < 2) { msg = 'Y';}
	
	//make and invalid
	var invalidchars = myRetVal.replace(/ and /gi, ",,,");
	
	//test for invalid
	invalidchars = invalidchars.replace(/[A-Za-z "'\-.]/g, "");
	//var invalidchars = myRetVal.replace(/[A-z "'\-.]/g, "");
	invalidchars = invalidchars.replace(/[\xc0-\xff]/g, "");
	if (invalidchars.length > 0) {msg = 'Y';}
	
	if (msg == 'Y') {
		alert("The name entered must contain at least 2 different alpha character.\nOnly Alpha characters and \" ' - are allowed\nThe word and is not allowed\n Please re-enter using the correct format." );
   //		
			setTimeout(function(){myfld.focus();}, 10);
	
	} else {
		myRetVal=namecase(myRetVal);
		
	}
	myRetVal= myRetVal.replace(/\./g, " ");
	myRetVal = myRetVal.replace(/ +/g, " ");
	return myRetVal;
			
} //end lastnameformat
//---------------------------------------------------------------------------
// Name case - respect function words in a name, such as de; la; ...
function namecase(s) {
	
	//array for name case
	namex = ["de", "de la", "la", "l'", "le", "du", "des", "van", "von", "der", "van der", "von der", "van den", "von den", "vder"];
	
	var temp;
	s=titlecase(s);
	for (var i=0; i < namex.length; i++) {
		temp=s.substr(0,namex[i].length+1);
		if (temp.toUpperCase()==namex[i].toUpperCase()+" ") {
			s=namex[i]+s.substr(namex[i].length);
		}
	}
	return s;
}
//---------------------------------------------------------------------------
// Turn string into titlecase. Respect McX.
// amended BK 22 july 2004
// copied from HKGBOS04
function titlecase(s) {
	var temp1, temp2, temp3, cWord="", cNew="";
	s=s+".";
	for (var i=0; i < s.length; i++) {
		if (isAlpha(s.charAt(i))) {
			cWord=cWord+s.charAt(i);
		} else if (cWord.length > 0 ) {
			if (cWord.length == 1) {
				if(cWord.toLowerCase()=="s" && (s.charAt(i-2)=="'")){
					cWord = cWord.toLowerCase();
				} else{
					cWord = cWord.toUpperCase();
				}
			}else {
				if((cWord=="st" || cWord=="nd" ||cWord=="rd" || cWord=="th")&& isDigit(s.charAt(i-3))){
				} else{
					temp1 = cWord.charAt(0);
					temp2 = cWord.substr(1);
					cWord = temp1.toUpperCase()+temp2.toLowerCase();
					temp1 = cWord.substr(0,2);
					if (temp1.toUpperCase() == "MC" && cWord.length>3) {
						temp2=cWord.charAt(2);
						temp3=cWord.substr(3);
						cWord=temp1+temp2.toUpperCase()+temp3;
					}
				}	
			}
			cNew=cNew+cWord;
			cWord="";
			cNew=cNew+s.charAt(i);
		} else {
			cNew=cNew+s.charAt(i);
		}
	}
	return cNew.substr(0,cNew.length-1);
}
//---------------------------------------------------------------------------
function isAlpha(s) {
	var temp;
	if (s.length === 0) {
		return false;
	}
	temp=s.toUpperCase();
	temp=temp.charCodeAt(0);
	if (temp > 64  && temp < 91) { 
		return true;
	}
	if (temp > 191 && temp < 256 ) { 
		return true;
	}
	return false;
}
//---------------------------------------------------------------------------
// BK 29 July 2004
// checks for dup entries
// MJS - modified 19/1/5
function checkadd(formObj,first_name,last_name,reqfld) {
	// arrflds[1] should equal the firstname
	//arrflds[2] should equal the lastname
	var fname = formObj.db_FIRST_NAME.value; 
	var sname = formObj.db_LAST_NAME.value; 
	var checkname= fname + "" + sname;
	var i;
	var namefound = false;
	for (i=0;i < dupname.length;i++) {
		if(dupname[i]==checkname){
			//alert("same name found");
			namefound = true;
			break;
		}
	}
	//alert("checkname33="+checkname);
	if(checkForDodgyNames(checkname)){
		alert("Please enter a valid name");
	} else {
	//alert("isNameDodgy2="+isNameDodgy)
		if(namefound === false){
			checkSubmit(formObj ,reqfld);
		} else {
			if(confirm(fname + " " + sname +" already exists \n\n Click OK if you wish to add them anyway?")){
				checkSubmit(formObj ,reqfld);
			}
		}
	}
}//end checkadd
//---------------------------------------------------------------------------
// BK 30 July 2004
// returns false if the name is a dodgy name
// see array below for current list
function checkForDodgyNames (checkthisname) {
	var checkFor = new Array("MickeyMouse","LordLucan","TestPerson","DonaldDuck","TestTest","TestBadge","AAnother","NoName","ABc","FirstLast","FirstnameLastname","FirstLastname","FirstnameLast","GuestGuest");
	var isNameDodgy = false;
	for (i=0;i < checkFor.length;i++) {
		if(checkFor[i]==checkthisname){
			isNameDodgy = true;
			break;
		}
	}
	return isNameDodgy;
}
//---------------------------------------------------------------------------
//format a number to 2 decimal places - MJS 29/9/4
function fixed2(val) {
	val = String(val);
	var reg = /\./;
	if ( reg.test(val)) {
		reg = /\.[0-9]$/;
		if ( reg.test(val)) {
			val = val.replace(/$/, "0");
		}
	} else {
		val = val.replace(/$/, ".00");
	}
	return val;
}
//---------------------------------------------------------------------------
function emailCheck (fld,RetVal) {
	/*checks email format
	added by MJS 11/3/5
	got from internet & amended
	*/
	
	//return if empty
	if (RetVal.length===0) {
		return RetVal;
	}
	//put to lower case
	RetVal=RetVal.toLowerCase();
	
	myfld = fld;
	
/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */
	var checkTLD=1;
	/* The following is the list of known TLDs that an e-mail address must end with. */
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|travel)$/;
	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
f	rom the domain. */
	var emailPat=/^(.+)@(.+)$/;
	/* The following string represents the pattern for matching all special
	characters.  We don't want to allow special characters in the address.
	These characters include ( ) < > @ , ; : \ " . [ ] */
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	/* The following string represents the range of characters allowed in a
	username or domainname.  It really states which chars aren't allowed.*/
	var validChars="\[^\\s" + specialChars + "\]";
	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")";
	/* The following pattern applies for domains that are IP addresses,
	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	/* The following string represents an atom (basically a series of non-special characters.) */
	var atom=validChars + '+';
	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")";
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	/* The following pattern describes the structure of a normal symbolic
	domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	/* Finally, let's start trying to figure out if the supplied address is valid. */
	/* Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */
	var matchArray=RetVal.match(emailPat);
	if (matchArray===null) {
	/* Too many/few @'s or something; basically, this address doesn't
	even fit the general mould of a valid e-mail address. */
		alert("Email address seems incorrect (check @ and .'s)");
		setTimeout(function(){myfld.focus();}, 10);
		return RetVal;
	}
	
	var user=matchArray[1];
	var domain=matchArray[2];
	// Start by checking that only basic ASCII characters are in the strings (0-127).
	for (var i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("The "+fld.id+ " field contains invalid characters.");
			setTimeout(function(){myfld.focus();}, 10);
			return RetVal;
   		}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("The "+fld.id+ " field contains invalid characters.");
			setTimeout(function(){myfld.focus();}, 10);	
			return RetVal;
   		}
	}
	// See if "user" is valid
	if (user.match(userPat)===null) {
	// user is not valid
		alert("The email address doesn't seem to be valid.\nPlease check the details");
		setTimeout(function(){myfld.focus();}, 10);
		return RetVal;
	}
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!==null) {
		// this is an IP address
		for (i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Destination IP address is invalid!");
				setTimeout(function(){myfld.focus();}, 10);
				return RetVal;
		   }
		}
		return RetVal;
	}
	// Domain is symbolic name.  Check if it's valid.
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			alert("The domain name does not seem to be valid.");
			setTimeout(function(){myfld.focus();}, 10);
			return RetVal;
   		}
	}
	/* domain name seems valid, but now make sure that it ends in a
	known top-level domain (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding
	the domain or country. */
	if (checkTLD && domArr[domArr.length-1].length!=2 &&
			domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("The address must end in a well-known domain or two letter " + "country.");
		setTimeout(function(){myfld.focus();}, 10);
		return RetVal;
	}
	// Make sure there's a host name preceding the domain.
	if (len<2) {
		alert("This address is missing a hostname!");
		setTimeout(function(){myfld.focus();}, 10);
		return RetVal;
	}
	// If we've gotten this far, everything's valid!
	return RetVal;
} //  End emailCheck-->
//--------------------------------------------------------------------------------------
// standard function to translate a character string - LOOK AT
function chrtran(s,a,b) {
	var RetVal="";
	for (var i=0; i<s.length; i++) {
		if (s.substr(i,1) == a) {
			RetVal=RetVal+b;
		} else {
			RetVal=RetVal+s.substr(i,1);
		}
	}
	return RetVal;
}
// return true if 0-9
//---------------------------------------------------------------------------
function isDigit(s) {
	var temp=s;
	if (s.length === 0) {
		return false;
	}
	temp=temp.charAt(0);
	if (temp < "0" ) {
		return false;
	}
	if (temp > "9" ) {
		return false;
	}
	return true;
}
//---------------------------------------------------------------------------
// format UK postcode with spaces. Correct O to 0. LOOK AT
function pcodeformat(s) {
	s=s.toUpperCase();
	var temp1=chrtran(chrtran(s,".","")," ","");
	
	//alert(temp1);
	var temp2="";
	if (temp1.substr((temp1.length)-3,1)=="O") {
		temp1=temp1.substr(0,(temp1.length)-3)+"0"+temp1.substr((temp1.length)-2,2);
	}
	for (var i=0; i<temp1.length; i++) {
		if (isAlpha(temp1.substr(i,1))) {
			temp2=temp2+"X";
		} else if (isDigit(temp1.substr(i,1))) {
			temp2=temp2+"9";
		} else {
			temp2=temp2+"?";
		}
	}
	switch (temp2) {
		case "XX99XX":
		case "X9X9XX":
		case "X999XX":
			s=temp1.substr(0,3)+" "+temp1.substr(3);
			break;
		case "XX999XX":
		case "XX9X9XX":
			s=temp1.substr(0,4)+" "+temp1.substr(4);
			break;
		case "X99XX":
			s=temp1.substr(0,2)+" "+temp1.substr(2);
			break;
		default:
			break;
	}
	return s;
}
//---------------------------------------------------------------------------
// format a UK phone number with spaces and brackets
function formatPhone(retVal,country) {
	
	if (country != "UK") {
		return retVal;
	}
	var nDigCount=0, nStrCount=0, cNewStr="", cFormatType="", temp1, temp2;
	retVal=trim(retVal);
	while (nStrCount < retVal.length ) {
		temp1=retVal.substr(nStrCount,1);
		if (isAlpha(temp1) || temp1 == "+") {
			cNewStr=cNewStr+retVal.substr(nStrCount);
			nStrCount=retVal.length-1;
		} else {
			if (isDigit(temp1)) {
				cNewStr=cNewStr+temp1;
				nDigCount=nDigCount+1;
			}
		}
		++nStrCount;
	}
	
		if((nDigCount==9 || nDigCount==10) && (retVal.substr(0,1) != "0" )){
	 		cNewStr = "0" + cNewStr;
			nDigCount=nDigCount+1;
		}
	
	retVal=cNewStr;
	if (nDigCount==10 && (retVal.substr(0,2)=="08" || retVal.substr(0,2)=="09" || retVal.substr(0,2)=="03" || retVal.substr(0,2)=="05")) {
		cFormatType="46";
	} else if (nDigCount==11 &&(retVal.substr(0,2)=="08" || retVal.substr(0,2)=="09" || retVal.substr(0,2)=="03" || retVal.substr(0,2)=="05") ) {
		cFormatType="434";
	} else if (nDigCount==11 && retVal.substr(0,2)=="07") {
		cFormatType="56";
	} else if (nDigCount==11 && retVal.substr(0,2)=="02") {
		cFormatType="344";
	} else if (nDigCount==11 && (retVal.substr(0,3)=="011" || (retVal.substr(0,2)=="01" && retVal.substr(3,1)=="1"))) {
		cFormatType="434";
	} else if (nDigCount==11 && retVal.substr(0,2)=="01") {
		cFormatType="56";
	}
	switch (cFormatType) {
		case "46":
			retVal="0"+cNewStr.substr(1,3)+" "+cNewStr.substr(4,6);
			if (cNewStr.length > nDigCount) {
				retVal=retVal+" "+cNewStr.substr(nDigCount);
			}
			break;
		case "434":
			retVal="0"+cNewStr.substr(1,3)+" "+cNewStr.substr(4,3)+" "+cNewStr.substr(7,4);
			if (cNewStr.length > nDigCount) {
				retVal=retVal+" "+cNewStr.substr(nDigCount);
			}
			break;
		case "344":
			retVal="0"+cNewStr.substr(1,2)+" "+cNewStr.substr(3,4)+" "+cNewStr.substr(7,4);
			if (cNewStr.length > nDigCount) { 
				retVal=retVal+" "+cNewStr.substr(nDigCount);
			}
			break;
		case "56":
			retVal="0"+cNewStr.substr(1,4)+" "+cNewStr.substr(5,6);
			if (cNewStr.length > nDigCount) {
				retVal=retVal+" "+cNewStr.substr(nDigCount);
			}
			break;
	}
	return retVal;
}
//---------------------------------------------------------------------------
// strip off leading & trailing spaces
function trim(str) { 
    str.replace(/^\s*/, '').replace(/\s*$/, '')

   return str;
} 

//---------------------------------------------------------------------------
//format phone
	//MJS 13/5/5
	function formatTel(countryval,fld,town){
		var retVal = trim(fld.value);
				
		//test if numeric exists
		var mytest =/[^0-9+ ]/;
		if (mytest.test(retVal)){
			alert("This field can contain numbers spaces and + only.\n Please re-enter using the correct format." );
			setTimeout(function(){myfld.focus();}, 10);
			return fld.value;
		}
	
		var telVal = dialcode[countryval];
		
		if (telVal) {
		} else {
			telVal = '';
		}
		
		//return value = country code
		if (retVal == telVal || retVal === "") {
			return '';
		}
		
		//strip non mumeric except spaces
		retVal = retVal.replace(/[^0-9 ]/g , "");
		//check if has valid country code
		
		//check for ital or moscow
		var stripZero = 'Y';
		if (telVal == "+39") {stripZero = 'N'; }
		if (telVal == "+7" && town.toLowerCase() == "moscow") {stripZero = 'N'; }
		
		var telValstrip = telVal.replace(/[^0-9]/,'');
		
		//first check if country code = current country
		var countryPat=new RegExp("^" + telValstrip);
				
		if (retVal.match(countryPat)) {
			//strip country code
			retVal = retVal.replace(countryPat , "");
			
			//strip leading 0  if not italy or moscow
			if (stripZero == "Y") {
				retVal = retVal.replace(/^0/, "");
			}
			
			//uk tel format
			if (countryval == 'UK') {
				retVal = ukTel(retVal);
			}
			
			retVal = telVal + " " + retVal;
			
			return retVal;
		} 
		
		//check for other country
		//if fld.value starts with plus
		if (fld.value.match(/^\+/)) {
			//if matches another country leave it
			return fld.value;
		}
		
		//if (NO COUNTRY) {	
		if (stripZero == "Y") {
			retVal = retVal.replace(/^0/, "");
		}
		
		//uk tel format
		if (countryval == 'UK') {
			retVal = ukTel(retVal);
		}
			
		retVal = telVal + " " + retVal;
		return retVal;
				
}
//---------------------------------------------------------------------------
//put cursor at end of field
//got from internet
//MJS 13/5/3
function positionCursorAtEnd(input) {
	
	var browserName=navigator.appName; 
	var platformtype=navigator.platform;
 	if (browserName=="Microsoft Internet Explorer" && platformtype != "MacPPC" ) {
 		var range = input.createTextRange();
		range.collapse(false);
		range.select();
	}
}
//---------------------------------------------------------------------------
//MJS 13/5/3
function ukTel(retVal) {
//alert("k")
	retVal = retVal.replace(/\s*/g, "");
	retVal = retVal.replace(/^([0-9]{3})([0-9]{6})$/,"$1 $2");
	retVal = retVal.replace(/^([8935][0-9]{2})([0-9]{3})([0-9]{3})$/,"$1 $2 $3");
	retVal = retVal.replace(/^(7[0-9]{3})([0-9]{6})$/,"$1 $2");
	retVal = retVal.replace(/^(2[0-9])([0-9]{4})([0-9]{4})$/,"$1 $2 $3");
	retVal = retVal.replace(/^(11[0-9])([0-9]{3})([0-9]{4})$/,"$1 $2 $3");
	retVal = retVal.replace(/^([0-9]{4})([0-9]{6})$/,"$1 $2");
	return retVal;
	
}
//---------------------------------------------------------------------------
function dateformat(retval, field){
	
	//return if empty
	if (retval.length===0) {
		return retval;
	}

	
	var checkstr = "0123456789";
	var DateField = field;
	var Datevalue = "";
	var seperator = "-";
	var day;
	var month;
	var year;
	var leap = 0;
	var err = 0;
	var i;
   	err = 0;
	
   	var myretval = retval;
   /* Delete all chars except 0..9 */
	myretval = myretval.replace(/[^0-9]/g, "");   
   
   //DateValue = DateTemp;
   /* Always change date to 8 digits - string*/
   /* if year is entered as 2-digit / always assume 19xx */
   if (myretval.length == 6) {
      myretval = myretval.substr(0,4) + '19' + myretval.substr(4,2); }
   if (myretval.length != 8) {
      err = 19;}
   /* year is wrong if year = 0000 */
   year = myretval.substr(4,4);
   if (year === 0) {
      err = 20;
   }
   /* Validation of month*/
   month = myretval.substr(2,2);
   if ((month < 1) || (month > 12)) {
      err = 21;
   }
   /* Validation of day*/
   day = myretval.substr(0,2);
   if (day < 1) {
     err = 22;
   }
   /* Validation leap-year / february / day */
   if ((year % 4 === 0) || (year % 100 === 0) || (year % 400 === 0)) {
      leap = 1;
   }
   if ((month == 2) && (leap == 1) && (day > 29)) {
      err = 23;
   }
   if ((month == 2) && (leap != 1) && (day > 28)) {
      err = 24;
   }
   /* Validation of other months */
   if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
      err = 25;
   }
   if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
      err = 26;
   }
   /* if 00 ist entered, no error, deleting the entry */
   if ((day === 0) && (month === 0) && (year === 0)) {
      err = 0; day = ""; month = ""; year = ""; seperator = "";
   }
   /* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
   if (err === 0) {
      myretval = day + seperator + month + seperator + year;
	  return myretval;
   }
   
   /* Error-message if err != 0 */
   else {
      alert("Date Format is incorrect! DD-MM-YYYY");
      //DateField.select();
	  setTimeout(function(){field.focus();}, 10);
	   return retval;
   }
}
//---------------------------------------------------------------------------
function jtformat(myRetVal,myfld){
//Job title case conversion
 
//Apply proper case under following circumstances, otherwise leave unchanged.
 
//- field all lower case
//- field all uppercase and longer then 5 chars.
	var mytest =/[A-Z]/;
	if (myRetVal.match(mytest) ) {
		//alert("contains uppercase" );
		
		//check if all uppercase & longer than 5
		if (myRetVal.match(/[^A-Z]/) ) {
			
		} else {
			if (myRetVal.length > 5 ) {
				myRetVal=titlecase(myRetVal);
			}
		}
		
		//
   		//myfld.focus();
	} else {
		myRetVal=titlecase(myRetVal);
	}
	
	 
	return myRetVal;
	
}
//---------------------------------------------------------------------------
function emailCheckUser (fld,RetVal) {
	/*checks email format User part only
	added by MJS 29/06/2006
	amended emailCheck
	*/
	
	//return if empty
	if (RetVal.length===0) {
		return RetVal;
	}
	//put to lower case
	RetVal=RetVal.toLowerCase();
	
	/* The following pattern is used to check if the entered e-mail address
	fits the user */
	var emailPat=/^(.+)$/;
	/* The following string represents the pattern for matching all special
	characters.  We don't want to allow special characters in the address.
	These characters include ( ) < > @ , ; : \ " . [ ] */
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	/* The following string represents the range of characters allowed in a
	username or domainname.  It really states which chars aren't allowed.*/
	var validChars="\[^\\s" + specialChars + "\]";
	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")";
	/* The following string represents an atom (basically a series of non-special characters.) */
	var atom=validChars + '+';
	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")";
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	/* Finally, let's start trying to figure out if the supplied address is valid. */
	/* Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */
	var matchArray=RetVal.match(emailPat);
	if (matchArray===null) {
	/* Too many/few @'s or something; basically, this address doesn't
	even fit the general mould of a valid e-mail address. */
		alert("Email address seems incorrect (check @ and .'s)");
		setTimeout(function(){myfld.focus();}, 10);
		return RetVal;
	}
	
	var user=matchArray[1];
	
	// Start by checking that only basic ASCII characters are in the strings (0-127).
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("The "+fld.id+ " field contains invalid characters.");
			setTimeout(function(){myfld.focus();}, 10);
			return RetVal;
   		}
	}
	
	// See if "user" is valid
	if (user.match(userPat)===null) {
	// user is not valid
		alert("The email address doesn't seem to be valid.\nPlease check the details");
		setTimeout(function(){myfld.focus();}, 10);
		return RetVal;
	}
	
	// If we've gotten this far, everything's valid!
	return RetVal;
}
//  End emailCheck-->
//---------------------------------------------------------------------------------
function pemail(fld,RetVal,prefix) {
	/*checks email format
	added by MJS 11/3/5
	got from internet & amended
	*/
	
	//return if empty
	if (RetVal.length===0) {
		return RetVal;
	}
	
	
	//put to lower case
	RetVal=RetVal.toLowerCase()+prefix;
	
	myfld = fld;
	
/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */
	var checkTLD=1;
	/* The following is the list of known TLDs that an e-mail address must end with. */
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|travel)$/;
	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
f	rom the domain. */
	var emailPat=/^(.+)@(.+)$/;
	/* The following string represents the pattern for matching all special
	characters.  We don't want to allow special characters in the address.
	These characters include ( ) < > @ , ; : \ " . [ ] */
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	/* The following string represents the range of characters allowed in a
	username or domainname.  It really states which chars aren't allowed.*/
	var validChars="\[^\\s" + specialChars + "\]";
	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")";
	/* The following pattern applies for domains that are IP addresses,
	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	/* The following string represents an atom (basically a series of non-special characters.) */
	var atom=validChars + '+';
	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")";
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	/* The following pattern describes the structure of a normal symbolic
	domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	/* Finally, let's start trying to figure out if the supplied address is valid. */
	/* Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */
	var matchArray=RetVal.match(emailPat);
	if (matchArray===null) {
	/* Too many/few @'s or something; basically, this address doesn't
	even fit the general mould of a valid e-mail address. */
		alert("Email address seems incorrect (check @ and .'s)");
		setTimeout(function(){myfld.focus();}, 10);
		return RetVal;
	}
	
	var user=matchArray[1];
	var domain=matchArray[2];
	// Start by checking that only basic ASCII characters are in the strings (0-127).
	for (var i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("The "+fld.id+ " field contains invalid characters.");
			setTimeout(function(){myfld.focus();}, 10);
			return RetVal;
   		}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("The "+fld.id+ " field contains invalid characters.");
			setTimeout(function(){myfld.focus();}, 10);	
			return RetVal;
   		}
	}
	// See if "user" is valid
	if (user.match(userPat)===null) {
	// user is not valid
		alert("The email address doesn't seem to be valid.\nPlease check the details\n"+RetVal);
		setTimeout(function(){myfld.focus();}, 10);
		return RetVal;
	}
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!==null) {
		// this is an IP address
		for (i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Destination IP address is invalid!");
				setTimeout(function(){myfld.focus();}, 10);
				return RetVal;
		   }
		}
		return RetVal;
	}
	// Domain is symbolic name.  Check if it's valid.
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			alert("The domain name does not seem to be valid.");
			setTimeout(function(){myfld.focus();}, 10);
			return RetVal;
   		}
	}
	/* domain name seems valid, but now make sure that it ends in a
	known top-level domain (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding
	the domain or country. */
	if (checkTLD && domArr[domArr.length-1].length!=2 &&
			domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("The address must end in a well-known domain or two letter " + "country.");
		setTimeout(function(){myfld.focus();}, 10);
		return RetVal;
	}
	// Make sure there's a host name preceding the domain.
	if (len<2) {
		alert("This address is missing a hostname!");
		setTimeout(function(){myfld.focus();}, 10);
		return RetVal;
	}
	// If we've gotten this far, everything's valid!
	return RetVal;
} //  End emailCheck-->
//--------------------------------------------------------------------------------------
