function emailCheck (emailStr) {
/* 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("The email address is not in the correct format. Please try again.")
	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 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
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("The domain name doesn't seem to be valid.")
    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>3) {
   // the address must end in a two letter or three letter word.
   alert("The address must end in a three-letter domain, or two letter country.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}


//Fuctions to mimmick LTrim,  RTrim, and Trim...
function LTrim(str)
/*
        PURPOSE: Remove leading blanks from our string.
        IN: str - the string we want to LTrim
*/
{
        var whitespace = new String(" \t\n\r");

        var s = new String(str);

        if (whitespace.indexOf(s.charAt(0)) != -1) {
            // We have a string with leading blank(s)...

            var j=0, i = s.length;

            // Iterate from the far left of string until we
            // don't have any more whitespace...
            while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
                j++;


            // Get the substring from the first non-whitespace
            // character to the end of the string...
            s = s.substring(j, i);
        }

        return s;
}

function RTrim(str)
/*
        PURPOSE: Remove trailing blanks from our string.
        IN: str - the string we want to RTrim

*/
{
        // We don't want to trip JUST spaces, but also tabs,
        // line feeds, etc.  Add anything else you want to
        // "trim" here in Whitespace
        var whitespace = new String(" \t\n\r");

        var s = new String(str);

        if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
            // We have a string with trailing blank(s)...

            var i = s.length - 1;       // Get length of string

            // Iterate from the far right of string until we
            // don't have any more whitespace...
            while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
                i--;


            // Get the substring from the front of the string to
            // where the last non-whitespace character is...
            s = s.substring(0, i+1);
        }

        return s;
}


        function Trim(str)
        /*
                PURPOSE: Remove trailing and leading blanks from our string.
                IN: str - the string we want to Trim

                RETVAL: A Trimmed string!
        */
        {
                return RTrim(LTrim(str));
        }

// checks if a field is populated
function isPopulated(field) {
	if (field.length != 0) {
		return true;
	} else {
		return false;
	}
} // isPopulated

function isNumber(data) {      // checks if all characters 
	var valid = "0123456789";     // are valid numbers 
	var ok = 1; var checktemp;
	for (var i=0; i<data.length; i++) {
		checktemp = "" + data.substring(i, i+1);
		if (valid.indexOf(checktemp) == "-1") 
		return false; 
	}
	return true;
} //isNumber

function isNumberDot(data) {      // checks if all characters 
	var valid = "0123456789.";     // are valid numbers 
	var ok = 1; var checktemp;
	for (var i=0; i<data.length; i++) {
		checktemp = "" + data.substring(i, i+1);
		if (valid.indexOf(checktemp) == "-1") { 
			return false; 
		} else {
			if ( (checktemp == ".") && (data.length == 1) )
				return false;	
		}				
	}
	return true;
} //isNumberDot

function containNumber(data) {      // checks if there are numbers/certain chars in the string 
	var valid = "0123456789~`!@#$%^&*()-_+={}|<>?";
	var ok = 1; var checktemp;
	for (var i=0; i<data.length; i++) {
		checktemp = "" + data.substring(i, i+1);
		if ( valid.indexOf(checktemp) >= 0 ){
		return true; 
		}
	}
	return false;
} //containNumber


function containValidName(data) {      // checks if there are numbers/chars except for @ in the string 
	var valid = "0123456789~`!#$%^&*()-_+={}|<>?";
	var ok = 1; var checktemp;
	for (var i=0; i<data.length; i++) {
		checktemp = "" + data.substring(i, i+1);
		if ( valid.indexOf(checktemp) >= 0 ){
		return true; 
		}
	}
	return false;
} //containValidName

// checks for PHONE masking XXX-XXXXXXXXXX
// Need to call Trim.js Function from Library
function checkPhone(strPhone) {
	
		number1 = strPhone.substring(0,3);
		number2 = Trim(strPhone.substring(4,23));
		
		if (number2 == "")
			return false;
		else if ( !(isNumber(number1) && isNumber(number2) ) )
			return false;
	
	
	firstHyphen = strPhone.indexOf('-');
	//alert(firstHyphen);
	if (firstHyphen != 3)
		return false;
	return true;
} // checkphone


// checks for IC masking XXXXXX-XX-XXXX
function checkIC(strIC) {
	
	if (strIC.length != 14) {
		return false;
	} else {
		number1 = strIC.substring(0,6);
		number2 = strIC.substring(7,9);
		number3 = strIC.substring(10,14);
		if ( !( isNumber(number1) && isNumber(number2) && isNumber(number3) ) )
			return false;
	}
	
	firstHyphen = strIC.indexOf('-');
	//alert(firstHyphen);
	if (firstHyphen != 6)
		return false;
	else { 
		strTemp = strIC.substring(7,strIC.length);
		secondHyphen = strTemp.indexOf('-');
		if (secondHyphen != 2)
			return false;
	}
	return true;
} // checkIC


// validates for x.xx or xxxxxxxx = true, .xx and .x are false
// only validate for position of dot, does not validate for numeric
function checkDecimal(amt) {
	firstDot = amt.indexOf(".");
	totalLength = amt.length;
	if (firstDot > 0) { // found dot
		decimalPoint = (totalLength - 1) - firstDot;
		if (decimalPoint != 2) 
			return false;
		else return true;
	} else if (firstDot < 0) { // not found dot
		return true;
	} else { // string starts with dot
		return false;
	}
}//checkDecimal

function isFloatNumber(amt) {
	firstDot = amt.indexOf(".");
	totalLength = amt.length;
	if ( (firstDot + 3) == totalLength ) {
		number1 = amt.substring(0,firstDot);
		number2 = amt.substring(firstDot+1,amt.length);
		if ( isNumber(number1) && isNumber(number2) ) {
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}	
} // isFloatNumber

// validates for xxxxxx.xx where x = 0,1,....,9
function checkFloat(amt) {
	firstDot = amt.indexOf(".");
	if ( checkDecimal(amt) ) { 
		if (firstDot > 0) { // found dot
			if ( isFloatNumber(amt) )
				return true;
			else return false;
		} else { // not found dot
			return false;
		}
	} else {
		return false;
	}
	//return checkDecimal(amt);
	//if (amt.length == 5)
} //checkFloat


//--------------------------------------------------------------------------------------------------------

// validate empty string
function isEmpty(string) {  	
	var nameEmpty = 1;
 	
	string = Trim(string);
	
	if (string.length == 0) {
		nameEmpty = 1
	} else {
		nameEmpty = 0
	}
	
	if (nameEmpty==0){
  		return false;
 	} else {
		return true;
	}	
}			


//validate postcode
function isPostcode(postcode) {
  	var postcodeEmpty = 1;
  
  	postcode = Trim(postcode);
	
	if ((postcode.length == 0) || (postcode.length != 5)) {
		postcodeEmpty = 0
	} else {
		for (var i = 0; i < postcode.length; i++){ 
			var ch = postcode.substring (i, i + 1);
			if ((ch < "0") || (ch > "9")){postcodeEmpty = 0; break}
		}			
	}				
   	
	if (postcodeEmpty==0){
  		return false;
 	} else {
		return true;
	}	
}	


//validate drop down menu
function isSelected(selecter) {
	var selecterEmpty = 1
 	for (var k = 1; k < selecter.length; k++) {   
		if (selecter.options[k].selected) {selecterEmpty = 0; break }
    }
 	if (selecterEmpty==0) {
  		return true		
 	} else {
		return false
	}	 
}


//validate radio button
function isChecked (radio) {
 	var radioEmpty = 1
 	for (var i = 0; i < radio.length; i++) {   
		if (radio[i].checked) {radioEmpty = 0; break }
    }
	if (radioEmpty==0){
  		return true;
 	} else {
		return false;
	}			
}		


//validate old IC no
function isOldIC (icno) {
	
	icno = Trim(icno);
	
	var icEmpty = 1
	if (icno.length != 7) { 
		if (icno.length != 8){
			return false;
		} else {
			return true;
		}
	} else {
		return true;
	}
}		


//validate isAreaCode
function isAreaCode (areacode) {
	
	areacode = Trim(areacode);
	var areacodeEmpty = 1
	if (areacode.length != 0)	{
		if (areacode.length == 2) {
			if ( !isNumber(areacode) ) {
				areacodeEmpty = 0;
			}
		} else if (areacode.length == 3) { 
			if ( !isNumber(areacode) ) {
				areacodeEmpty = 0;
			}
		} else {
			areacodeEmpty = 0;
		}	
	}
		
	if (areacodeEmpty == 1) {
		return true;	
	} else {
		return false;
	}	
 }
 
 
 //validate isTelNo 
function isTelNo(telno) {
	telno = Trim(telno);
	var telnoEmpty = 1
	if (telno.length != 0)	{
		if (telno.length == 6) {
			if ( !isNumber(telno) ) {
				telnoEmpty = 0;
			}
		} else if (telno.length == 7) {
			if ( !isNumber(telno) ) {
				telnoEmpty = 0;
			}
		} else if (telno.length == 8) { 
			if ( !isNumber(telno) ) {
				telnoEmpty = 0;
			}
		} else {
			telnoEmpty = 0;
		}	
	} 	
		
	if (telnoEmpty == 1) {
		return true
	} else {
		return false
	}		
}


//validate isServiceCode
function isServiceCode (servicecode) {
	servicecode = Trim(servicecode);
	var servicecodeEmpty = 1
	if (servicecode.length != 0)	{
		if (servicecode.length == 3) { 
			if ( !isNumber(servicecode) ) {
				servicecodeEmpty = 0;
			}
		} else {
			servicecodeEmpty = 0;
		}		
	} 
		
	if (servicecodeEmpty == 1) {
		return true;	
	} else {
		return false;
	}	
}


//validate isMobileNo
function isMobileNo (mobileno) {
	mobileno = Trim(mobileno);
	var mobilenoEmpty = 1
	if (mobileno.length != 0)	{
		if (mobileno.length == 7) { 
			if ( !isNumber(mobileno) ) {
				mobilenoEmpty = 0;
			}
		} else {
			mobilenoEmpty = 0;
		}		
	} 		
		
	if (mobilenoEmpty == 1) {
		return true;	
	} else {
		return false;
	}	

}


//validate dob
function isDob (bdate) {
	var bdateEmpty = 1
	if ( verifyDate(bdate) ) {
		if ( checkYear(bdate) ) {
			bdateEmpty = 0;
		} else {
			bdateEmpty = 1;
		}
	} else {
		bdateEmpty = 1;
	}	
	if (bdateEmpty==0) {
		return true;
	} else {
		return false;
	}	
}


// validate email 
function isEmail(email) {
 	var emailEmpty = 1;
 	if (email.length==0 || (email.indexOf('@', 0) == -1) || (email.indexOf('.', 0) == -1)) {emailEmpty = 0}
		if (emailEmpty==1) {
  			return true;
 		} else {
			return false;
		}
}			


//validate is future valid date 
function isFutureDate (date) {
	var dateEmpty = 1;
	if ( verifyDate(date) ) { 
		if ( checkYearGlobal(date) ) {
			dateEmpty = 0;
		} else {
			dateEmpty = 1;
		}
	} else {
		dateEmpty = 1;	
	}
	if (dateEmpty==0) {
  		return true;
 	} else {
		return false;
	}
}	
	
//validate project info
function isPrjPopulated(title, fMth, fYear, tMth, tYear, team, role, desc) {

var TOTALPRJFIELDS = 8;
var projectCounter = 0;	

	if (!isEmpty(title)){
		projectCounter++;
	} 
	if (fMth > 0) {
		projectCounter++;
	} 
	if (fYear > 0) {
		projectCounter++;
	} 
	if (tMth > 0) {
		projectCounter++;
	} 
	if (tYear > 0) {
		projectCounter++;
	} 
	if (team > 0) {
		projectCounter++;
	} 
	if (!isEmpty(role)) {
		projectCounter++;
	} 
	if (!isEmpty(desc)) {
		projectCounter++;
	}
		
	if ( (projectCounter > 0) && (projectCounter < TOTALPRJFIELDS) ){
		return false;
	} else {
		return true;
	}				
							
}

//validate co information
function isPopulated(name, title, fMth, fYear, tMth, tYear, func) {

var TOTALCOFIELDS = 7;
var companyCounter = 0;	

	if (!isEmpty(name)){
		companyCounter++;
	} 
	if (!isEmpty(title)) {
		companyCounter++;
	} 
	if (fMth > 0) {
		companyCounter++;
	} 
	if (fYear > 0) {
		companyCounter++;
	} 
	if (tMth > 0) {
		companyCounter++;
	} 
	if (tYear > 0) {
		companyCounter++;
	}  
	if (!isEmpty(func)) {
		companyCounter++;
	} 
	
	if ( (companyCounter > 0) && (companyCounter < TOTALCOFIELDS) ){
		return false;
	} else {
		return true;
	}				
							
}

//validate co info
function selectPrjEmptyField(title, fMth, fYear, tMth, tYear, team, role, desc) {

var empty_field = "";

	if (isEmpty(title)){
		empty_field = "title";
	} else if (fMth == 0) {
		empty_field = "fMth";
	} else if (fYear == 0) {
		empty_field = "fYear";
	} else if (tMth == 0) {
		empty_field = "tMth";
	} else if (tYear == 0) {
		empty_field = "tYear";
	} else if (team == 0) {
		empty_field = "team";
	} else if (isEmpty(role)) {
		empty_field = "role";	
	} else if (isEmpty(desc)) {
		empty_field = "desc";
	}
		
	if ( empty_field != "" ){
		return empty_field;				
	}						
}

//validate co info
function selectEmptyField(name, title, fMth, fYear, tMth, tYear, func) {

var empty_field = "";

	if (isEmpty(name)){
		empty_field = "name";
	} else if (isEmpty(title)) {
		empty_field = "title";
	} else if (fMth == 0) {
		empty_field = "fMth";
	} else if (fYear == 0) {
		empty_field = "fYear";
	} else if (tMth == 0) {
		empty_field = "tMth";
	} else if (tYear == 0) {
		empty_field = "tYear";
	} else if (isEmpty(func)) {
		empty_field = "func";
	}
		
	if ( empty_field != "" ){
		return empty_field;				
	}						
}

//validate family info
/*
function selectEmptyField(name, dob, indicator, icno, rel, occ, height, weight) {

var empty_field = "";

	if (isEmpty(name)){
		empty_field = "name";
	} else if (isEmpty(dob)) {
		empty_field = "dob";
	} else if (indicator == 0) {
		empty_field = "indicator";
	} else if (isEmpty(icno)) {
		empty_field = "icno";
	} else if (rel == 0) {
		empty_field = "rel";
	} else if (isEmpty(occ)) {
		empty_field = "occ";
	} else if (isEmpty(height)) {
		empty_field = "height";
	} else if (isEmpty(weight)) {
		empty_field = "weight";
	}
		
	if ( empty_field != "" ){
		return empty_field;				
	}						
}*/

//validate company info whether all fields are empty or not
function isProjectEmpty(title, fMth, fYear, tMth, tYear, team, role, desc) {

var TOTALPRJFIELDS = 8;
var projectCounter = 0;	

	if (!isEmpty(title)) {
		projectCounter++;
	} 
	if (fMth > 0) {
		projectCounter++;
	} 
	if (fYear > 0) {
		projectCounter++;
	} 
	if (tMth > 0) {
		projectCounter++;
	} 
	if (tYear > 0) {
		projectCounter++;
	}
	if (team > 0) {
		projectCounter++;
	} 
	if (!isEmpty(role)) {
		projectCounter++;
	} 
	if (!isEmpty(desc)) {
		projectCounter++;
	}
	
		
	if (projectCounter == 0){
		return true;
	} else {
		return false;
	}				
							
}

//validate company info whether all fields are empty or not
function isCompanyEmpty(name, title, fMth, fYear, tMth, tYear, func) {

var TOTALCOFIELDS = 7;
var companyCounter = 0;	

	if (!isEmpty(name)){
		companyCounter++;
	} 
	if (!isEmpty(title)) {
		companyCounter++;
	} 
	if (fMth > 0) {
		companyCounter++;
	} 
	if (fYear > 0) {
		companyCounter++;
	} 
	if (tMth > 0) {
		companyCounter++;
	} 
	if (tYear > 0) {
		companyCounter++;
	} 
	if (!isEmpty(func)) {
		companyCounter++;
	} 
	
		
	if (companyCounter == 0){
		return true;
	} else {
		return false;
	}				
							
}

//validate family info whether all fields are empty or not
function isFamilyEmpty(name, dob, indicator, icno, rel, occ, height, weight) {

var TOTALFAMILYFIELDS = 8;
var familyCounter = 0;	

	if (!isEmpty(name)){
		familyCounter++;
	} 
	if (!isEmpty(dob)) {
		familyCounter++;
	} 
	if (indicator > 0) {
		familyCounter++;
	} 
	if (!isEmpty(icno)) {
		familyCounter++;
	} 
	if (rel > 0) {
		familyCounter++;
	} 
	if (!isEmpty(occ)) {
		familyCounter++;
	} 
	if (!isEmpty(height)) {
		familyCounter++;
	} 
	if (!isEmpty(weight)) {
		familyCounter++;
	}
		
	if (familyCounter == 0){
		return true;
	} else {
		return false;
	}				
							
}			

//=====================================================================================================


// converts text field to uppercase
function makeUpper(pthisField) {
	pthisField.value = pthisField.value.toUpperCase();
} // makeUpper

// calculates age based on birthdate in "dd/mm/yyyy" format
// e.g. calculateAge("01/01/1950", 1)
function calculateAge(pBirthDate, pMode) {
	// pMode == 1 -> returns years
	// pMode == 2 -> returns days

	today = new Date();
	thisMonth = today.getMonth()+1;
	//thisYear = today.getYear();
	thisYear = today.getFullYear();
	thisDay = today.getDate();
	
	// get ddmmyyyy for birthdate
	pDay = pBirthDate.substring(0,2);
	pMonth = pBirthDate.substring(3,5);
	pYear = pBirthDate.substring(6,10);
	
	// get age's date
	ageDay = thisDay - pDay;
	ageMonth = thisMonth - pMonth;
	ageYear = thisYear - pYear;

	// the age to be calculated
	var nAge = 0; // years
	var nDays = 0; // days
	
	if (ageMonth == 0) {
		if (ageDay < 0) {
			nAge = ageYear - 1;
		} else {
			nAge = ageYear;
		}
	} else {
		if (ageMonth < 0) {
			nAge = ageYear - 1;
		} else {
			nAge = ageYear;
		}
	}

	dBirthDay = new Date();
	dBirthDay.setYear(pYear);
	dBirthDay.setMonth(pMonth - 1);
	dBirthDay.setDate(pDay);

/*
	arrMonth = new Array();
	arrMonth[0] = "January";
	arrMonth[1] = "February";
	arrMonth[2] = "March";
	arrMonth[3] = "April";
	arrMonth[4] = "May";
	arrMonth[5] = "June";
	arrMonth[6] = "July";
	arrMonth[7] = "August";
	arrMonth[8] = "September";
	arrMonth[9] = "October";
	arrMonth[10] = "November";
	arrMonth[11] = "December";
*/		
	
	//strDate = "August 20, 1997";
	//strDate = "April 6, 2000";
	//dBirthDay = new Date(strDate);
	
	msPerDay = 24 * 60 * 60 * 1000 ;
	timeDiff = ( today.getTime() - dBirthDay.getTime() );
	daysLeft = timeDiff / msPerDay;
	daysLeft = Math.floor(daysLeft);
	nDays = daysLeft;
	
	if (pMode == 1) {
		return nAge;
	} else if (pMode == 2) {
		return nDays;
	}
}//calculateAge

// returns number of years
function getAge(pBirthDate) {
	nAge = calculateAge(pBirthDate, 1);
	return nAge;
} // getAge

// returns number of days
function getAgeDays(pBirthDate) {
	nDays = calculateAge(pBirthDate, 2);
	return nDays;
}//getAgeDays

function isValidDate(dateStr) {
// Checks for the following valid date formats:
// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
// Also separates date into month, day, and year variables
// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

// To require a 4 digit year entry, use this line instead:
 	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
		//alert("Date is not in a valid format.")
		return false;
	}

	month = matchArray[1]; // parse date into variables
	day = matchArray[3];
	year = matchArray[4];
	
	if (month < 1 || month > 12) { // check month range
		//alert("Month must be between 1 and 12.");
		return false;
	}
	if (day < 1 || day > 31) {
		//alert("Day must be between 1 and 31.");
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		//alert("Month "+month+" doesn't have 31 days!")
		return false
	}
	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
			//alert("February " + year + " doesn't have " + day + " days!");
			return false;
	   }
	}
	return true;  // date is valid
}//isValidDate

// month chars to its integer 
// e.g. NOV -> 11
function convertMthToNum(nMonth) {
	if (nMonth == "JAN") {
		return "01";
	} else if (nMonth == "FEB") {
		return "02";
	} else if (nMonth == "MAR") {
		return "03";
	} else if (nMonth == "APR") {
		return "04";
	} else if (nMonth == "MAY") {
		return "05";
	} else if (nMonth == "JUN") {
		return "06";
	} else if (nMonth == "JUL") {
		return "07";
	} else if (nMonth == "AUG") {
		return "08";
	} else if (nMonth == "SEP") {
		return "09";
	} else if (nMonth == "OCT") {
		return "10";
	} else if (nMonth == "NOV") {
		return "11";
	} else if (nMonth == "DEC") {
		return "12";
	} else {
		// Error occur
		return "01";
	}
} //convertMthToNum	

// dd/mm/yyyy to mm/dd/yyyy
function convertDMY2MDY(nDate) {
	nNewYear = nDate.substring(6,10);
	nNewMonth = nDate.substring(3,5);
	nNewDay = nDate.substring(0,2);
	return nNewMonth + "/" + nNewDay + "/" + nNewYear;
}

// verifies date if its dd/mm/yyyy
function verifyDate(pDate) {
	if (pDate.length != 10) {
		if (pDate.length != 0) {
			//alert("not 10, not 0");
			return false;
		}
	}
	dNewDate = convertDMY2MDY(pDate);

	return isValidDate(dNewDate);
}//verifyDate


function isTelephoneNumber(data) {      // checks if all characters 
	var valid = "0123456789-";     // are valid numbers 
	var ok = 1; var checktemp;
	for (var i=0; i<data.length; i++) {
		checktemp = "" + data.substring(i, i+1);
		if (valid.indexOf(checktemp) == "-1") 
		return false; 
	}
	return true;
} //isTelephoneNumber

// check for year, must not be more than 100 years old from current year
// also checks for same year but future month -> false
function checkYear(bdate) {
	today = new Date();
	thisMonth = today.getMonth()+1;
	//thisYear = today.getYear();
	thisYear = today.getFullYear();
	thisDay = today.getDate();	
	pDay = bdate.substring(0,2);
	pMonth = bdate.substring(3,5);
	pYear = bdate.substring(6,10);
	startYear = thisYear - 100; // 100 years old max
	
	if (pYear < startYear) {
		// age is more than 100 years old
		return false;
	} else if (pYear > thisYear) {
		// reference to future date
		return false;
	} else if (pYear == thisYear) {
		if (pMonth > thisMonth) {
			return false;
		} else if (pMonth == thisMonth) {
			if (pDay > thisDay) {
				return false;
			}
		}
	}
	return true;
} // checkYear

// date can be in the future, but can not be back dated
function checkYearGlobal(bdate) {
	today = new Date();
	thisMonth = today.getMonth()+1;
	thisYear = today.getFullYear();
	thisDay = today.getDate();	
	thisYear = thisYear * 1;
	thisMonth = thisMonth * 1;
	thisDay = thisDay * 1;
	
	pDay = bdate.substring(0,2);
	pMonth = bdate.substring(3,5);
	pYear = bdate.substring(6,10);
	
	if (pYear.length != 4) {
		return false;
	} else {
		pYear = pYear * 1;
		pMonth = pMonth * 1;
		pDay = pDay * 1;
		if (pYear < thisYear) {
			return false;
		} else if (pYear == thisYear) { // same year
			if (pMonth < thisMonth) {
				return false;
			} else if (pMonth == thisMonth) {
				if (pDay < thisDay) { //changed this to disallow current date as a future date
					return false;
				} else {
					return true;
				} // compare day
			} // same month
		} // same year 
	}
	return true;
	
} //checkYearGlobal


// validate if a currentAge is between fromAge and toAge, inclusive
function validAge(currentAge, fromAge, toAge) {
	if ( (currentAge <= toAge) && (currentAge >= fromAge) ) {
		return true;
	} else {
		return false;
	}
} // validAge

function addYear(currDate,nYears) {
	pDay = bdate.substring(0,2);
	pMonth = bdate.substring(3,5);
	pYear = bdate.substring(6,10);
	
	dtCurrDate = new Date();
	dtCurrDate.setYear(pYear+1); // add 1 year here
	dtCurrDate.setMonth(pMonth);
	dtCurrDate.setDate(pDay);
	
	newYear = dtCurrDate.getFullYear();
	newMonth = dtCurrDate.getMonth();
	newDate = dtCurrDate.getDate();
	
	strReturn = newDate + "/" + newMonth+ "/" + newYear;
	
	//return newDate + "/" + newMonth+ "/" + newYear;
	//strReturn = newDate + "/" + newMonth + "/" newYear;
	return strReturn;
}//addYear

// global
var Days_in_Month = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

// set February to 29 days if leap year
function setLeapYear(Year) {
    if ((Year % 400 == 0) || ((Year % 4 == 0) && (Year % 100 != 0))) {
        Days_in_Month[1] = 29;
    }
} // setLeapYear

function unsetLeapYear() {
	Days_in_Month[1] = 28;
}//unsetLeapYear

// returns date of nYears from now
function addYears(currDate, nYears) {
	pDay = currDate.substring(0,2);
	pMonth = currDate.substring(3,5);
	pYear = currDate.substring(6,10);
	
	pDay = pDay * 1;
	pMonth = pMonth * 1;
	pYear = pYear * 1;

	targetDate = checkDate(pDay,pMonth,pYear);
	return targetDate;	
}//addYears


function checkDate(fromDate,fromMonth,fromYear) {
	if (fromMonth == 1) { // january
		if (fromDate == 1) {
			toDate = 31; // last day of december
			toMonth = 12; // december
			toYear = fromYear;
		} else {
			toDate = fromDate - 1;
			toMonth = fromMonth;
			toYear = fromYear + 1;
		}
	} else { // months other than january
		
		toYear = fromYear + 1;
		if (fromDate == 1) { // first day of month
			toMonth = fromMonth - 1;
			setLeapYear(toYear);
			toDate = Days_in_Month[toMonth-1];
			unsetLeapYear();
		} else {
			toDate = fromDate - 1;
			toMonth = fromMonth;
		}
	}
	
	// prepend "0" for single digits
	if (toDate < 10) {
		toDate = "0" + toDate;
	}
	if (toMonth < 10) {
		toMonth = "0" + toMonth;
	}
	
	strReturn = toDate + "/" + toMonth + "/" + toYear;
	return (strReturn);
}//checkMonth

function calcPremium(nPlan,nAge,nNoDays) {
	cat0 = new Array(120,210,400); // child 30 days to 18 years
	cat1 = new Array(200,480,900); // 19 - 35 years
	cat2 = new Array(250,600,1125); // 36 - 45 years
	cat3 = new Array(350,840,1575); // 46 - 55 years
	cat4 = new Array(400,960,1800); // 56 - 60 years
		
	if (nPlan == 1) {
		
		if ( ((nAge <= 18) && (nNoDays >= 30)) || ((nAge <= 18) && (nNoDays == 0)) ){
			nPremium2 = cat0[0];
		} else if ( (nAge >= 19) && (nAge <= 35) ) {
			nPremium2 = cat1[0];
		} else if ( (nAge >= 36) && (nAge <= 45) ) {
			nPremium2 = cat2[0];
		} else if ( (nAge >= 46) && (nAge <= 55) ) {
			nPremium2 = cat3[0];
		} else if ( (nAge >= 56) && (nAge <= 60) ) {
			nPremium2 = cat4[0];
		} else 
			{nPremium2 = 0}
	} else if (nPlan == 2) {
		if ( ((nAge <= 18) && (nNoDays >= 30)) || ((nAge <= 18) && (nNoDays == 0)) ) {
			nPremium2 = cat0[1];
		} else if ( (nAge >= 19) && (nAge <= 35) ) {
			nPremium2 = cat1[1];
		} else if ( (nAge >= 36) && (nAge <= 45) ) {
			nPremium2 = cat2[1];
		} else if ( (nAge >= 46) && (nAge <= 55) ) {
			nPremium2 = cat3[1];
		} else if ( (nAge >= 56) && (nAge <= 60) ) {
			nPremium2 = cat4[1];
		} else 
			{nPremium2 = 0}
	} else if (nPlan == 3) {
		if ( ((nAge <= 18) && (nNoDays >= 30)) || ((nAge <= 18) && (nNoDays == 0)) ) {
			nPremium2 = cat0[2];
		} else if ( (nAge >= 19) && (nAge <= 35) ) {
			nPremium2 = cat1[2];
		} else if ( (nAge >= 36) && (nAge <= 45) ) {
			nPremium2 = cat2[2];
		} else if ( (nAge >= 46) && (nAge <= 55) ) {
			nPremium2 = cat3[2];
		} else if ( (nAge >= 56) && (nAge <= 60) ) {
			nPremium2 = cat4[2];
		} else 
			{nPremium2 = 0}
	} // planX
	return nPremium2;
} // calcPremium


//format day and mth to two digits
function leadZero(num, len) {
	var strNum = (Math.pow(10, len) + num) + "";
	return strNum.substr(1, len);
}


//==============================================================================================

// isIntegerInRange (STRING s, INTEGER a, INTEGER b [, BOOLEAN emptyOK])
// 
// isIntegerInRange returns true if string s is an integer 
// within the range of integer arguments a and b, inclusive.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.


function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = parseInt (s);
    return ((num >= a) && (num <= b));
}

function checkPublishDates (dateField1, dateField2, dateFormat, timeField1, timeField2 )
{
	// get current date and time
	now = new Date();
	nowDate =  parseInt(now.getMonth()) + 1  + "/" + now.getDate() + "/" + now.getYear();		
	nowTime =  now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();	
	dateComparison = dateCompare(dateField1, dateField2, dateFormat);
	
	// check if publish date is greater than archive date
	if (dateComparison == 1) { 
		alert('From date should be earlier than To date'); 
		return false 
	}
	return true;
}


		
function dateCompare (dateVar1, dateVar2, DateFormat)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
	
	if (dateCompare.arguments.length != 3) return false;

		
		if (DateFormat.charAt(0) == 'd')
		{
			DayValue1 = parseInt(DatePart(dateVar1,1), 10);
			MonthValue1 = parseInt(DatePart(dateVar1,2), 10);
			
			DayValue2 = parseInt(DatePart(dateVar2,1), 10);
			MonthValue2 = parseInt(DatePart(dateVar2,2), 10);
		}
		else
		{
			DayValue1 = parseInt(DatePart(dateVar1,2));
			MonthValue1 = parseInt(DatePart(dateVar1,1));
			
			DayValue2 = parseInt(DatePart(dateVar2,2));
			MonthValue2 = parseInt(DatePart(dateVar2,1));
		}
		
		YearValue1 = parseInt(DatePart(dateVar1,3));
		YearValue2 = parseInt(DatePart(dateVar2,3));
		
	
		if (YearValue1 > YearValue2)
			return 1
		else if (YearValue1 < YearValue2)
			return -1

		if (MonthValue1 > MonthValue2)
			return 1
		else if (MonthValue1 < MonthValue2)
			return -1
			
		if (DayValue1 > DayValue2)
			return 1
		else if (DayValue1 < DayValue2)
			return -1
		else return 0
			
    
}


function timeCompare (timeVar1, timeVar2)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
	
	if (timeCompare.arguments.length != 2) return false;

		HourValue1 = parseInt(timePart(timeVar1,1));
		HourValue2 = parseInt(timePart(timeVar2,1));
		
		MinValue1 = parseInt(timePart(timeVar1,2));
		MinValue2 = parseInt(timePart(timeVar2,2));

		secValue1 = parseInt(timePart(timeVar1,3));
		secValue2 = parseInt(timePart(timeVar2,3));
		
	
		if (HourValue1 > HourValue2)
			return 1
		else if (HourValue1 < HourValue2)
			return -1

		if (MinValue1 > MinValue2)
			return 1
		else if (MinValue1 < MinValue2)
			return -1
			
		if (secValue1 > secValue2)
			return 1
		else if (secValue1 < secValue2)
			return -1
		else return 0
			
    
}

function DatePart(s, n)
{
	var delimiter = '-'
	s = replaceAll (s, "/", delimiter)
		
	ss = delimiter + s + delimiter;
	
	for (d=0; d<=n-1; d++)
	{
		ss = ss.substring(ss.indexOf(delimiter)+1,ss.length);
	}
	
	return  ss.substring(0,ss.indexOf(delimiter));
	
}

function timePart(s, n)
{
	var delimiter = ':'
	
	ss = delimiter + s + delimiter;

	for (t=0; t<=n-1; t++)
	{
		ss = ss.substring(ss.indexOf(delimiter)+1,ss.length);
	}
	
	return  ss.substring(0,ss.indexOf(delimiter));

	
}

function replaceAll (s, s1, s2)
{
	while (s.indexOf(s1) != -1)
	{
		s = s.replace(s1, s2);
	}
	return s
}