//function to ensure that the select list is populated
// lst obj ref
// msg error message to display
// char index to hold text(1) or numbers(0)
function validatelist(lst, msg, schar){	
		if ((lst.options[lst.selectedIndex].value == "-1") ||(lst.options[lst.selectedIndex].value == "")||(lst.options[lst.selectedIndex].value == "0")){
		alert (msg);
		lst.focus();
		return false; 
		}
	return true;
}
function validatelistmulti(lst, smsg){	
	var count = 0;
	for (var i = 0;  i < lst.length; i++) {
		if (lst.options[i].selected ){
			count += 1 }
	}
	if (count <= 0){
		alert (smsg);
		lst.focus();
		return false }
return true;
}

function parsedate(ctrlText,ctrlName){
	// parses a date 
	// the date should be on the form [d]d MON [yy]yy
	// [optional]
	
	var adate=ctrlText.value;
	adate2=new String(adate)
		
	//extract year, date and month
	index=adate2.search(" ");
	if(index==-1) {
		alert("The "+ctrlName+" must be populated");
		ctrlText.focus();
		return(false)
	}
	day=adate2.substring(0,index);
	adate2=adate2.slice(index+1);
	index2=adate2.search(" ");
	if(index2==-1)  {
		alert("The "+ctrlName+" must be populated correctly");
		ctrlText.focus();
		return(false)
	}
	month=adate2.substring(0,index2);
	year=adate2.slice(index2+1);
		
	// parse month
	teststring = "jan feb mar apr may jun jul aug sep oct nov dec"
	if(teststring.toUpperCase().search(month.toUpperCase())==-1) {
		alert("The "+ctrlName+" must have the month in 3 letters.");
		ctrlText.focus();
		return(false)
	}
				
	//parse date
	//this does not check for the 30th of feb etc,
	tmp=day + " > 31"
	if(eval(day + " > 31")){
		alert("The "+ctrlName+" must have the days less than 31 days.");
		ctrlText.focus();
		return(false);
		}

	var imonth
	if (month.toUpperCase() == "JAN"){
		imonth = 1
	}else if (month.toUpperCase() == "FEB"){
		imonth = 2
	}else if (month.toUpperCase() == "MAR"){
		imonth = 3
	}else if (month.toUpperCase() == "APR"){
		imonth = 4
	}else if (month.toUpperCase() == "MAY"){
		imonth = 5
	}else if (month.toUpperCase() == "JUN"){
		imonth = 6
	}else if (month.toUpperCase() == "JUL"){
		imonth = 7
	}else if (month.toUpperCase() == "AUG"){
		imonth = 8
	}else if (month.toUpperCase() == "SEP"){
		imonth = 9
	}else if (month.toUpperCase() == "OCT"){
		imonth = 10
	}else if (month.toUpperCase() == "NOV"){
		imonth = 11
	}else if (month.toUpperCase() == "DEC"){
		imonth = 12
	} else {
		imonth = 0
	}
		
	if (!datechk(day, imonth, year)) {
		alert("The "+ctrlName+" entered of \""+ adate +"\" is not a valid date.");
		ctrlText.focus();
		return(false);
		}
	
	return(true);		
	}

//function to validate Names
function Validate_Names(ctrlText,maxChar,minChar,ctrlName, funct){
  var val=ctrlText.value;
  var val_Length=ctrlText.value.length;
  var errMessage;
  var minChar;
  var maxChar;
	if(val_Length < minChar){ 
		alert("The "+ctrlName+" must be a minimum of "+minChar+" characters");
		ctrlText.focus();
	    return false; 
	}
	if  (val_Length > maxChar){
		alert("The "+ctrlName+" must be a maximum of "+maxChar+" characters");
		ctrlText.focus();
	    return false; 
	}
	if(val.charCodeAt(0)==32) {
		ctrlText.value= deleteStringOnce(ctrlText.value," ") }
	//loop looking for illeagal chars
	for(i=0;i<val_Length;i++)
	{ 	str=val.charCodeAt(i);
	//only allowed letters
		if (funct == 0) {//0 for firm name validation
			if((str>=9 && str<=31) || (str>=33 && str<=37) || (str>=42 && str<=43)||(str>=58 && str<=64) ||(str>=91 && str<=95) || (str>122 && str<=191))
			{	alert("Your "+ctrlName+" does not appear to be correctly entered. Please note the character '"+val.charAt(i)+"' is not allowed " );
				ctrlText.focus();
				return false; 
			}
		}else{ //standard varibles
			if((str>=9 && str<=31) || (str>=33 && str<=38) || (str>=40 && str<=44)||(str>=46 && str<=64) ||(str>=91 && str<=95) || (str>122 && str<=191))
			{	alert("Your "+ctrlName+" does not appear to be correctly entered. Please note the character '"+val.charAt(i)+"' is not allowed " );
				ctrlText.focus();
				return false; 
			}
		}
	}
return true
}



//makes sure that max min stuff is ok.
function validate_presence(ctrlText,maxChar,minChar,ctrlName){
  var val=ctrlText.value;
  var val_Length=ctrlText.value.length;
  var errMessage;
  var minChar;
  var maxChar;
	if(val.charCodeAt(0)==32) {
		ctrlText.value= deleteStringOnce(ctrlText.value," ") }
	
	if((val_Length < minChar) || (val_Length > maxChar)){ 
		alert("Please enter your "+ctrlName);
		ctrlText.focus();
	    return false; 
	   }

return true;

}

function validate_UName(ctrlText, ctrlname)
{
  // Does Not Allow Special Characters
  // allows Numbers Alphabets and _ and . and -
    val=ctrlText.value;
    val_Length = val.length;
    if(val != "") {
		if(val.charCodeAt(0)==32) {
			ctrlText.value= deleteStringOnce(ctrlText.value," ") 
			val=ctrlText.value;
			val_Length = val.length;		
		}
		if(val.charCodeAt(val.length)==32) {
			ctrlText.value= deleteStringOnce(ctrlText.value," ") 
			val=ctrlText.value;
			val_Length = val.length;		
		}
	    
	    for(i=0;i<val_Length;i++) { 
		  str=val.charCodeAt(i);
		  if((str>=9 && str<=44)||(str==47)|| (str>=58 && str<=64) ||(str>=91 && str<=94)||(str == 96) || (str>122 && str<=255)) {	  
			if (str == 32){//space
				ctrlText.value= deleteStringOnce(ctrlText.value," ") 
				alert("Spaces are not allowed in " + ctrlname + " and have been removed for you")
				bokay = 1
			}else{
				bokay = 0
				alert("The character \"" + val.charAt(i) + "\" in "+ ctrlname + " is not allowed\nOnly Numbers, text, underscore, dashes and full stops are allowed");
				//Only numbers , text , underscore,'-','.' are allowed in user name");
			}
			
			if (bokay == 0){
				ctrlText.focus();
				return false;
			}
		  }
		}
	  } else  {
	     alert(ctrlname + " cannot be blank");
	     ctrlText.focus();
	     return false;
	  }	
	return true;
}

//validate password. 
function password_check(fld1, fld2){
	if (fld1.value == fld2.value){
		return true;
	}else{
		alert("Your Passwords do not match")
		fld2.value = ""
		fld2.focus()
		return false;
	}
	
}



//validates the telephone codes
function validatetelephone(ctrlText,maxChar,minChar,ctrlName,schar){
  var val=ctrlText.value;
  var val_Length=ctrlText.value.length;
  var errMessage;
  var minChar;
  var maxChar;
  var schar;
  var ctrlreplace = "";
  
  //char = 1 check for blank string char=0 do not check the string
  
	if (schar == 1){
		//is the filed blank?
		if((val_Length < minChar) || (val_Length > maxChar)){ 
			alert("Please enter your "+ctrlName);
			ctrlText.focus();
			return false; 
		 }
	}
	//remove non number characters
  	for(i=0;i<val_Length;i++)
  	{
		str=val.charCodeAt(i);
		if ((str>=48 && str<=57)) { //remove the affected char.
			ctrlreplace = ctrlreplace + val.charAt(i);
		}
	}	
	ctrlText.value = ctrlreplace
	
	if (schar == 1){
		//is the string still blank.,..
		val_Length=ctrlText.value.length;
		if((val_Length < minChar) || (val_Length > maxChar)){ 
			alert("Please enter your "+ctrlName+" as numbers only please");
			ctrlText.focus();
		   return false; 
		 }
	}
return true;
}
 
 function gfb_EmailCheck (ctrlText){
	//check and remove the leading space
	if (ctrlText.value.charCodeAt(0)==32){
		ctrlText.value = deleteStringOnce(ctrlText.value," ") }
	if (ctrlText.value.charCodeAt(ctrlText.value.length-1) == 32){
		ctrlText.value = deleteStringOnce(ctrlText.value," ") }
	
	 var xCtrl=ctrlText.value
	/* 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
	   from 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. */

	   emailStr=xCtrl;
	var matchArray=emailStr.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("Enter your Email Address")
	ctrlText.focus();
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    alert("The email address entered '" + ctrlText.value + "' appears to be invalid because the bit before this '@' sign is invalid .\nWe must have your correct email address as this is used as a point of \nreference for you to be able to submit your articles and is your first point \nof contact")
    ctrlText.focus();
    return false
}

/* 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 (var icount=1;icount<=4;icount++) {
	    if (IPArray[icount]>255) {
	        alert("The email address entered '" + ctrlText.value + "' appears to be invalid because destination IP address is invalid!.\nWe must have your correct email address as this is used as a point of \nreference for you to be able to submit your articles and is your first point \nof contact.")
	        ctrlText.focus();
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("The email address entered '" + ctrlText.value + "' appears to be invalid because the domain name doesn't seem to be valid.\nWe must have your correct email address as this is used as a point of \nreference for you to be able to submit your articles and is your first point \nof contact.")
	ctrlText.focus();
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>4) {
   // the address must end in a two letter or three letter word.
   alert("The email address entered '" + ctrlText.value + "' appears to be invalid because the address must end in a three/four letter domain, or two letter country.\nWe must have your correct email address as this is used as a point of \nreference for you to be able to submit your articles and is your first point \nof contact.")
   ctrlText.focus();
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="this address is missing a hostname!"
   alert("The email address entered '" + ctrlText.value + "' appears to be invalid because "+errStr+".\nWe must have your correct email address as this is used as a point of \nreference for you to be able to submit your articles and is your first point \nof contact.")
   ctrlText.focus();
   return false
}

// If we've gotten this far, everything's valid!
return true;
}

// extract front part of string prior to searchString
function getFront(mainStr, searchStr) {
	foundOffset = mainStr.indexOf(searchStr)
		if (foundOffset == -1 ) { 
			return null
			}
		return mainStr.substring(0,foundOffset)
		}

//extract back end of string after search string
function getEnd(mainStr, searchStr) {	
	foundOffset = mainStr.indexOf(searchStr) 
	if (foundOffset == -1) {
		return null
		}
	return mainStr.substring(foundOffset+searchStr.length,mainStr.length)
	}

//insert insertStringimmediatly before searchString
function insertString(mainStr,searchStr,insertStr) 
	{
	var front = getFront(mainStr,searchStr) 
	var end = getEnd(mainStr,searchStr)
	if (front != null && end != null) 
		{
		return front+ insertStr + searchStr + end
		}
		return null
	}
//remove deleteString
function deleteString(mainStr,deleteStr) {
	return replaceStringOnce(mainStr,deleteStr,"")
}

function deleteStringOnce(mainStr,deleteStr) {
	return replaceString(mainStr,deleteStr,"")
}

//replace searchString with replaceString
function replaceString(mainStr,searchStr,replaceStr) 
	
	{ 
	var test = mainStr.indexOf(searchStr)
	var count = 0
	while ( test != -1)
		{
		var front = getFront(mainStr,searchStr) 
		var end = getEnd(mainStr,searchStr)
		
		if (front != null && end != null) 
			{
			mainStr = front + replaceStr + end 
			}
		
		test = mainStr.indexOf(searchStr)
		count = count + 1
		}
	//alert (""+searchStr+  " has been replaced by " +replaceStr+ "  " +count+ " times") 
	return mainStr
	}

//replace searchString with replaceString once
function replaceStringonce(mainStr,searchStr,replaceStr) 
	{ 
	var front = getFront(mainStr,searchStr) 
	var end = getEnd(mainStr,searchStr)
		
	if (front != null && end != null) 
		{
		mainStr = front + replaceStr + end }
		else {
		alert(""+searchStr+ "not found!")
		}
	return mainStr
	}

/*
return true; if date is valud
return false; if date not valid
*/
function datechk(day, month, year){
   leap = 0;
   /* Validation leap-year / february / day */
   if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
      leap = 1;
   }
   if ((month == 2) && (leap == 1) && (day > 29)) {
      	//alert("29 dayus.")
      	return false ;
   }
   if ((month == 2) && (leap != 1) && (day > 28)) {
      	//alert("28 dayus.")
      	return false ;
   }
   /* Validation of other months */
   if ((day > 31) && ((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12))) {
      	//alert("31 day have...")
      	return false ;
   }
   if ((day > 30) && ((month == 4) || (month == 6) || (month == 9) || (month == 11))) {
		//alert("30 day have...")
      	return false;
   }

   /* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
   	return true ; 
   
}
