/* file containing various functions 

	VALIDATION FUNCTIONS
	isLeapYear (Year) - checks if passed parameter is a leap year
	isDate (Day, Month, Year) - checks if passed parameters create a valid date
	isDateFormat	(string) - checks if passed string is dd/mm/yyyy
	isEmail (Email) - checks if passed string forms a valid email address
	isInteger (number) - checks if passed parameter is an integer
	isDigit (character) - checks if the passed character is a digit 0-9
	isPhoneNum (std, number) - checks if passed parameters form a valid telephone number
	
	STRING FUNCTIONS
	trimFormElements(form) - trims all elements in passed form
	trim(string) - trims passed string of leading and trailing spaces
	removePunctuation(form) - removes all punctuation that can cause problems ie " <> 
	
	FORM FUNCTIONS
	getElementIndex(obj) - returns the index number of the passed form field
	autoTab(obj) - automatically tabs to next form field if maxlength of passed field is reached
	setSelectedItem(listobj, value) - sets the selected item in the passed list to the passed value
*/

function isLeapYear(iYear) {
//determines if the passed year is a leap year
	if (iYear % 100 == 0) {
		if (iYear % 400 == 0) { return true; }
	} else {
		if ((iYear % 4) == 0) { return true; }
	}
	return false;
}
function isLongDate(iDay, sMon, iYear){
//checks that the passed numeric date is valid
// Day: 1-31
// Month: 1-12
// Year: 0-9999
	var iMon = 0;
	var arrMonths = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
	for(var i = 0; i < arrMonths.length; i++) {
		if(arrMonths[i] == sMon) {
			iMon = i + 1;
			break;
		}
	}
	// range checks
	if( iDay < 1 || iDay > 31 || iMon < 1 || iMon > 12 || iYear < 0 || iYear > 9999){
		return false;
	}
	
	// 31 day months already checked
	/*
	if ((iMon == 1 || iMon == 3 || iMon == 5 || iMon == 7 || iMon == 8 || iMon == 10 || iMon == 12) && (iDay > 31 || iDay < 1)) { return false; } */

	// 30 day months
	if ((iMon == 4 || iMon == 6 || iMon == 9 || iMon == 11) && (iDay > 30 || iDay < 1)) { return false;}

	// february
	if (iMon == 2) {
		if (iDay < 1) { return false; }
		if (isLeapYear(iYear) == true) {
			if (iDay > 29) { return false; }
		} else {
			if (iDay > 28) { return false; }
		}
	}
	return true;
}
function isDate(iDay, iMon, iYear){
//checks that the passed numeric date is valid
// Day: 1-31
// Month: 1-12
// Year: 0-9999

	// range checks
	if( iDay < 1 || iDay > 31 || iMon < 1 || iMon > 12 || iYear < 0 || iYear > 9999){
		return false;
	}
	
	// 31 day months already checked
	/*
	if ((iMon == 1 || iMon == 3 || iMon == 5 || iMon == 7 || iMon == 8 || iMon == 10 || iMon == 12) && (iDay > 31 || iDay < 1)) { return false; } */

	// 30 day months
	if ((iMon == 4 || iMon == 6 || iMon == 9 || iMon == 11) && (iDay > 30 || iDay < 1)) { return false;}

	// february
	if (iMon == 2) {
		if (iDay < 1) { return false; }
		if (isLeapYear(iYear) == true) {
			if (iDay > 29) { return false; }
		} else {
			if (iDay > 28) { return false; }
		}
	}
	return true;
}
function isDateFormat(sDate){
// checks the passed string is in the date format dd/mm/yyyy
//00-39/00-19/1000-2199
  var re  = /[0-3][0-9]\/[0-1][0-9]\/[1-2][0-1][0-9][0-9]/;
  
  if (! re.test(sDate)) return false;
	return true;
}

function isEmailRE(sEmail){
//using a regular expression to validate email address
	//var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9])+$/;
	var filter = /[ |\t|\r|\n]*\"?([^\"]+\"?@[^ <>\t]+\.[^ <>\t][^ <>\t]+)[ |\t|\r|\n]*/; 

	if (filter.test(sEmail)) 
		//('YES! Correct email address');
		return true;
	else 
		//alert('NO! Incorrect email address');
		return false;

}

function isEmail (emailStr) {
/* 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)$/;

	/* 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. */
	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("Email address seems incorrect (check @ and .'s)");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];

	// 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("Ths username contains invalid characters.");
			return false;
   	}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			//alert("Ths domain name contains invalid characters.");
			return false;
   	}
	}

	// See if "user" is valid 
	if (user.match(userPat)==null) {
		// user is not valid
		//alert("The username doesn't seem to be valid.");
		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 i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				//alert("Destination IP address is invalid!");
				return false;
   		}
		}
		return true;
	}

	// 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.");
			return false;
   	}
	}

	/* 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.");
			return false;
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
		//alert("This address is missing a hostname!");
		return false;
	}

	// If we've come this far, everything's valid!
	return true;
}

function isDigit (c){
   return ((c >= "0") && (c <= "9"))
}

function isInteger(iNum){
// function to check the passed value is an integer
	if(iNum.length == 0) return false;
    for (i = 0; i < iNum.length; i++){   
       // Check that current character is number.
       var c = iNum.charAt(i);
       if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}

function isPhoneNum(iSTD, iTel){
// checks that the values in the passed create a valid phone number
	var minlen = 2;
	var maxlen = 50;
	
	if(arguments.length < 2){
		alert("isPhoneNum: insufficient arguments.");
		return false;
	}
	if(iSTD == "" || iTel == "") return false;

  if(!isInteger(iSTD) || !isInteger(iTel)) return false;

	return true;
}

function trimFormElements(frm){
	with (frm){
		for(var i = 0; i < length; i++){
			if(elements[i].type == 'text' || elements[i].type == 'textarea')
				elements[i].value = trim(elements[i].value);
		}
	}
}

function trim(sStr){
	// regexp = multiple leading spaces
	var regexp = /^ +/
	// regexp = multiple trailing spaces
	var regexp2 = / +$/
	
	sStr = sStr.replace(regexp2, "");
	sStr = sStr.replace(regexp, "");
	return sStr;
}

function removePunctuation(frm){
// removes all punctuation that can cause problems in the future ie double-quotes
	var regexp = /[\"\,<>]/g
	with (frm){
		for(var i = 0; i < length; i++){
			if(elements[i].type == 'text' || elements[i].type == 'textarea')
				elements[i].value = elements[i].value.replace(regexp, "");
		}
	}
}
function TextFieldsEmpty(frm){
// checks if all text fields in passed form are empty
	var i;
	
	for(i=0; i<frm.length; i++){
		if(frm[i].type == "text"){
			if (frm[i].value != "")
				return false;
		}
	}
	
	return true;
}

function getElementIndex(obj) {
// returns the index number of the passed form field
	var theform = obj.form;
	for (var i=0; i<theform.elements.length; i++) {
		if (obj.name == theform.elements[i].name) {
			return i;
		}
	}
	return -1;
}

function autoTab(obj) {
//automatically tabs to next field in form when maxlength of field is reached 
// usage:
//<INPUT type="text" name=txtArea maxLength=3 onkeyup="return autoTab(this);"> 
 	var theForm = obj.form;
	var num = obj.value;
	var i = getElementIndex(obj);
	var j=i+1;
	if (j >= theForm.elements.length) { j = 0; }
	if (i == -1) { return; }
	 
	if(num.length == obj.maxLength) 
		theForm.elements[j].focus(); 
} 

function setSelectedItem(oSelect, sItem){
// sets the highlighted item in the passed select object to the passed item
	var i;

	oSelect.selectedIndex = 0;
	for(i=0; i<oSelect.length; i++){
		if(oSelect.options[i].value == sItem){
			oSelect.selectedIndex = i;
			return;
		}
	}
}

