// convert a string to lowercase with 1st letter capitalised, returns a string
function ucFirst(element){
	var s = element.value;
	var c = s.charAt(0);

	if (parseInt(s.length)==1){
		return c.toUpperCase();
	}
	else
	{
		return c.toUpperCase() + s.slice(1).toLowerCase();
	}
}
// remove leading and trailing spaces, returns a string
function Trim(element){
	var s = element.value;
	var trimmed="";
	var leading = true;
	var trailing = true;
	
	// strip leading spaces
    for(var i = 0; i < s.length; i++) 
	{
        var c = s.charAt(i);
        if (c == ' ') 
        { 
			if (leading==false)
			{
				trimmed=trimmed+c;
			}
		}
		else
		{	
			leading=false;
			trimmed=trimmed+c;
		}
    }
    
    // strip trailing spaces
    for (var i = trimmed.length-1; i>0; i--) 
    {
		var c = trimmed.charAt(i);
		if (c != " ")
		{
			return trimmed;
		}
		else
		{
			trimmed=trimmed.substr(0,trimmed.length-1);
		}
    }
	
	return trimmed;
}
// same as ucFirst, but repeated for all words in a string after
// converting all underscore characters to spaces
function ReadableName(element){
	var s = element.value;
	var formatted = "";
	var c = "";
	var wStart = true;
    for(var i = 0; i < s.length; i++) 
    {
        c = s.charAt(i);
        if (c == "_"){c=" ";}
        if (wStart==true){formatted=formatted+c.toUpperCase();wStart=false;}
        else {formatted=formatted+c.toLowerCase();}
        if (c == " "){wStart=true;}
    }
    return formatted;
}
// checks whether a field is empty, returns bool
function IsEmpty(element){
	var s = element.value;
	
	if ((s == '') || (s == null)) {return true;}
	
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) 
			return false;
    }
    return true;
}
// validate an email address, returns bool
function IsValidEmail(element){
	// assume an email address cannot start with an @ or white space, but it
	// must contain the @ character followed by groups of alphanumerics and '-'
	// followed by the dot character '.'
	// It must end with 2 or 3 alphanumerics.
	var e = element.value;
	var alnum="a-zA-Z0-9";
	exp="^[^@\\s]+@(["+alnum+"+\\-]+\\.)+["+alnum+"]["+alnum+"]["+alnum+"]?$";
	emailregexp = new RegExp(exp);

	result = e.match(emailregexp);
	if (result != null)
	{
		return true;
	}
	else
	{
		return false;
	}
}
// Checks if time is in HH:MM:SS format. returns bool
// The seconds are optional.
function IsValidTime(strTime) {


	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?$/;
	var matchArray = strTime.match(timePat);
	if (matchArray == null) {
		return false;
	}

	hour = matchArray[1];
	minute = matchArray[2];
	second = matchArray[4];

	if (second=="") { second = null; }

	if (hour < 0  || hour > 23) {
		return false;
	}

	if (minute<0 || minute > 59) {
		return false;
	}
	if (second != null && (second < 0 || second > 59)) {
		return false;
	}
	return true;
}
// CHecks to see if the passed in string is a number, returns bool
function IsValidNumber(numval){
	if (numval==""){return false;}
	var myRegExp = new RegExp("^[/+|/-]?[0-9]*[/.]?[0-9]*$");
	return myRegExp.test(numval);
}
// internal function for date function
function IsValidInterval(interval){
	var strIntervals = new Array("yrs","year","years","mos","month","months","day","days","week","weeks","hrs","hour","hours","mins","min","minutes","secs","sec","second","seconds");
	strArray = interval.split(" ");
	
	// need at least two items
	if (strArray.length < 2) {return false;}
	
	// check all pairs of values to be valid intervals (e.g 2 hrs 5 mins) 
	for (i = 0;i<strArray.length-1;i=i+2) {
		if (isNaN(strArray[i])){return false;}
		found=false;
		for (var x = 0;x<strIntervals.length;x++) {
			if (strArray[i+1].toUpperCase() == strIntervals[x].toUpperCase()) {found=true;}
		}
		if (!found){return false;}
	}
	return true;
}
// Checks the validity of the date (d), returns bool. 
// if convert is specified, it will return a formatted date
function IsValidDate(d,convert) {
	var strDatestyle = "US"; //United States date style
	//var strDatestyle = "EU";  //European date style
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intDay;
	var intMonth;
	var intYear;
	var booFound = false;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var err = 0;
	var strMonthArray = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	
	// sets strDate to the passed in date value
	strDate = d;
	
	if (strDate.length < 1) {
		return false;
	}
	if (strDate.toLowerCase()=="today" || strDate.toLowerCase()=="now"){return true;}

	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3) 
			{
				err = 1;
				return false;
			}
			else 
			{
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];
			}
			booFound = true;
		}
	}

	if (booFound == false) {
		if (strDate.length>5) {
			strDay = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strYear = strDate.substr(4);
		}
		else
			return false;
	}
	
	// verify year part	2 or 4 digits
	if (strYear.length != 2 && strYear.length != 4) {return false;}
	if (isNaN(strYear)){return false;}
	// US style (swap month and day)
	if (strDatestyle == "US") {
		strTemp = strDay;
		strDay = strMonth;
		strMonth = strTemp;
	}

	// verify 1 or 2 digit integer day
	if (strDay.length<1 || strDay.length>2) {return false;}
	if (isNaN(strDay)){return false;}
	
	// month may be digits of characters, hence following check
	intMonth = parseInt(strMonth, 10);
	if (isNaN(intMonth)) {
		for (i = 0;i<12;i++) {
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
			}
		}
		if (isNaN(intMonth)) {
			err = 3;
			return false;
		}
	}

	intDay=parseInt(strDay,10);
	intYear = parseInt(strYear, 10);
	
	if (intMonth>12 || intMonth<1) {
		err = 5;
		return false;
	}
	
	// day in month check
	if (intDay < 1 || intDay > 31){return false;}
		
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intDay > 30)) {
		return false;
	}
	
	if (intMonth == 2) {
		if (LeapYear(intYear)) {
			if (intDay > 29) {return false;}
		}
		else 
		{
			if (intDay > 28) {return false;}
		}
	}
	
	if (!convert)
		return true;
	else
	{
		if (intYear<=99){intYear=intYear+2000;}
		return intDay+"/"+intMonth+"/"+intYear;
	}
}
// Checks for ten digit phone number, returns bool
function IsValidPhoneNumber(element) {
	
		// removes leading and trailing whitespaces
		var phoneNumber = Trim(element);
		
		var numberSize = phoneNumber.length;
		var valid = true;
		var goodNums = "0123456789";
		var i;
		var size = 0;
		
		// Return false if number is empty
		if (phoneNumber=="") 
			valid = false;
		// Checks different formats
		
		// phone number must include area code to be valid
		if (numberSize < 10)
			valid = false;
			
		// ten-digit phone number without spaces and symbols
		if (numberSize == 10)
			for (i = 0; i < numberSize; i++)
				if (goodNums.indexOf(phoneNumber.charAt(i)) == -1)
					valid = false;
		
		// ten-digit phone number with spaces and/or symbols
		// checks for ten digits in any combination
		if (numberSize > 10){
			for (i = 0; i < numberSize; i++)
				if (goodNums.indexOf(phoneNumber.charAt(i)) != -1)
					size++;
			if (size != 10)
				valid = false;
		}
		
		return valid;
}
// Returns formatted phone number
function ReturnPhoneNumber(element){
	if (IsValidPhoneNumber(element)){
		
		var numberStr = "";
		var phoneNumber = Trim(element);
		var goodNums = "0123456789";
		var i;
		
		// gets the numbers from string
		for (i = 0; i < phoneNumber.length; i++)
				if (goodNums.indexOf(phoneNumber.charAt(i)) != -1)
					numberStr = numberStr + phoneNumber.charAt(i);
		// builds phone number in standard format
		var areaCode = numberStr.substr(0,3);
		var prefix = numberStr.substr(3,3);
		var lineNumber = numberStr.substr(6,4);
		var fullNumber = "(" + areaCode + ") " + prefix + "-" + lineNumber;
		
		return fullNumber;
	}
	else 
		return "Not a valid phone number!";
	
}