// regular expressions
var reWhitespace	= /^\s+$/
var reAlpha		= /^[a-zA-Z]*$/
var reNumeric		= /^\d*$/

/**** regular expressions for entry fields *****/
//only alphabets, numbers
var reGeneralString = /^[a-zA-Z\d\*\-\(\)\+\~;`<>|]*$/	

//only alphabets, numbers and space
var reGeneralStringSp = /^[a-zA-Z\d\s\*\-\(\)\+\~;`<>|_=$%^&]*$/		

//------------------------------------------------------
//must contain at least one wildcard and consist of alphabets, numbers, special char
var reGenStringQuery = /^[%a-zA-Z#\d\*\-\(\)\+\~;`<>|_$^&]*$/	

//must contain at least one wildcard and consist of alphabets, numbers, space, special char
var reGenStringSpQuery = /^[%a-zA-Z#\d\s\*\-\(\)\+\~;`<>|_$^&@]*$/		
//------------------------------------------------------

// do not allow space, '*', '(' , ')', '\', '~', ';', quotes, '<', '>', '|' .
var reProjectDefinition	= /^[^\s\*\(\)\\~;'"`<>|]*$/	

// only alphabets, numbers, ' ', '&', '-', '(', ')' ,'+', '/',
var reCheckType=/^[a-zA-Z\d\s&\-\(\)\+\/]*$/	

// all digits beginning with 6, minimum	8 chars and maximum 12 chars long						
var reSASServiceOrder=/^6[\d]{7,11}/	
var reEGRServiceOrder=/^1[\d]{7,11}/

// must contain at least one wildcard, and must begin with 6 or wildcard, and consist of numbers or wildcard			
// note : below expression cannot control length.  must check using string length to be max 12
var reSASServiceOrderWildcard=/(^[6%][\d]*%+[%\d]*$|^%[%\d]*$)/	
var reEGRServiceOrderWildcard=/(^[6%][\d]*%+[%\d]*$|^%[%\d]*$)/	

// only alphabets, numbers, '/' , '-' and space
var reJobNo=/^[a-zA-Z\d\-\*\/\s]*$/		

// only alphabets, numbers, '/', '-' , '%' and space
var reJobNoWildcard	= /^[%a-zA-Z\d\-\*\/\s]*$/		

// must be 3 digit
var reZoneNo=/^\d{3}/			

// must be 8 digit
var reEmployeeNo=/^\d{8}/

// 0-3 digits or wildcards; note: below expression does not ensure there must be at least one
// wildcard if length is < 3; must use program logic to check
var reZoneNoWildcard=/^[%\d]{0,3}$/

//Check EARN prefix. Allow only alpha-numeric and space
var rePrefix = /[^a-zA-Z0-9\-]/

// only alphabets, numbers or '-' or '#' or space or '/' or '.'
//--- commented original check phase on 2005 June 22 for SASCO request to allow '.' ---
//var reWorkcardNo=/^[a-zA-Z#\d\-\(\)\*\/\s]*$/
var reWorkcardNo=/^[a-zA-Z#\d\-\(\)\*\/\s\.]*$/


// only alphabets, numbers or '-' or '#' or ',' space or '/' or '.'
//--- commented original check phase on 2005 June 22 for SASCO request to allow '.' ---
//var reWorkcardNoAllowMany=/^[a-zA-Z#\d\-\(\)\*\/\s\,]*$/
var reWorkcardNoAllowMany=/^[a-zA-Z#\d\-\(\)\*\/\s\,\.]*$/


// only alphabets, numbers or '-' or '%' or space or '/' or '.'
//--- commented original check phase on 2005 June 22 for SASCO request to allow '.' ---
//var reWorkcardNoWildcard=/^[a-zA-Z#%\d\(\)\*\-\/\s]*$/
var reWorkcardNoWildcard=/^[a-zA-Z#%\d\(\)\*\-\/\s\.]*$/

// only alphabets, numbers, ' ', '&', '-', '(', ')' ,'+', '/',
var reAttachment=/[a-zA-Z\d\s\-\(\)\+\/\.\_]:/	

function select (field)
{
	field.focus();
	field.select();
}

//Part I
//To perform the date format validation
//ASP pages will call checkDate() function by passing three string parameters:iday,imonth,iyear
//
function daysInFebruary (year)
{   
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28);
}

//Added by Sydney to reserved dd/mm/yyyy to mm/dd/yyyy format or vice verse
function ReverseMonthDay(inDate)
{
var arr=inDate.split("/");
Part1 = arr[0];
Part2 = arr[1];
Part3 = arr[2];
outDate = (Part2 + "/" + Part1 + "/" + Part3);
return outDate;
}

	
function ChangDateBySBU(SBUID, inDate, CR)
{//801,806,911,913,921,808
if (SBUID == "801") return ChangDateFormat(inDate, CR);
if (SBUID == "802") return ChangDateFormat(inDate, CR);
if (SBUID == "803") return ChangDateFormat(inDate, CR);
if (SBUID == "806") return ChangDateFormat(inDate, CR);
if (SBUID == "808") return ChangDateFormat(inDate, CR);
if (SBUID == "921") return ChangDateFormat(inDate, CR);
return inDate;
}

//Added by Sydney, to convert the date format from mm/dd/yyyy to dd/mm/yyyy
function ChangDateFormat(inDate, CR)
{
var arr=inDate.split("/");
theDay = arr[0]
if (theDay.length==1) theDay = "0" + theDay;
theMonth = arr[1]
if (theMonth.length==1) theMonth = "0" + theMonth;
theYear = arr[2]
if(!CR)
    outDate = (theMonth + "/" + theDay + "/" + theYear)
else
    outDate = (theYear + "-" + theMonth + "-" + theDay)
return outDate;
}


//------------------------------------------------------------------------
// Modified by Sydney
// to check for date fields display based on sbuid perferred date format
//------------------------------------------------------------------------
/*function checkDate (InputDate,fieldname, SBUID)
{   
    
    InputDate = ChangDateBySBU(SBUID,InputDate, false);
	alert("InputDate is: "+InputDate);
	//alert("SBUID:" +SBUID+ ", InputDate: "+InputDate)
    var arr=InputDate.split("/");
    var iday = arr[1];
    var imonth = arr[0];
    var iyear = arr[2];
    
    //alert(imonth+"/"+ iday +"/"+ iyear);
    // catch invalid years (not 2- or 4-digit) and invalid months and days.
    if (!(validateYear(iyear,fieldname) && validateMonth(imonth,fieldname) && validateDay(iday,fieldname))) 
    	return false;

    var intYear = parseInt(iyear, 10);
    var intMonth = parseInt(imonth, 10);
    var intDay = parseInt(iday, 10);
    
    var monthMax = new Array (31,29,31,30,31,30,31,31,30,31,30,31);
    var top = monthMax[intMonth - 1];
    
	//alert("intDay is: "+intDay);
    if ((intDay<1) || (intDay>top))
    {
		var error ="Error occured in field:" + fieldname + ". Please enter a day between 1 and " + top;
		alert (error);
		return false;
    }
	//alert("intMonth is: "+intMonth);
    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) 
    {
    	var error ="Error occured in field:" + fieldname +  ". There are 29 days in February in a leap year only!";
    	alert (error);	
    	return false;
    }
    return true;
}*/

/* backup by sydney b4 the date format changes by SBUID
function checkDate (iday, imonth, iyear,fieldname)
{   
    // catch invalid years (not 2- or 4-digit) and invalid months and days.
    if (!(validateYear(iyear,fieldname) && validateMonth(imonth,fieldname) && validateDay(iday,fieldname))) 
    	return false;

    var intYear = parseInt(iyear, 10);
    var intMonth = parseInt(imonth, 10);
    var intDay = parseInt(iday, 10);
    
    var monthMax = new Array (31,29,31,30,31,30,31,31,30,31,30,31);
    var top = monthMax[intMonth - 1];
    
    if ((intDay<1) || (intDay>top))
    {
		var error ="Error occured in field:" + fieldname + ". Please enter a day between 1 and " + top;
		alert (error);
		return false;
    }

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) 
    {
    	var error ="Error occured in field:" + fieldname +  ". There are 29 days in February in a leap year only!";
    	alert (error);	
    	return false;
    }
    return true;
}*/

function validateMonth (field,fieldname)
{
	var input = parseInt (field, 10);
		if (isNaN (input))
		{
			alert ("Error occured in field:" + fieldname + ". Please enter a 2 digit month!");
			return false;
		}
		else
		{
			if ((input>12) || (input<1))
			{	
				alert ("Error occured in field:" + fieldname + ". Please enter a number between 1 [January] and 12 [December].");
				return false;
			}
		}	
	//	alert("validatemonth end");
	return true;
}

function validateDay (field,fieldname)
{
	var input = parseInt (field, 10);
	if (isNaN(input))
	{
		alert ("Error occured in field:" + fieldname + ". Please enter a 2 digit day!");
		return false;
	}
	else
	{
		if ((input>31) || (input<1))
		{	
			alert ("Error occured in field:" + fieldname + ". Please enter a valid day.");
			return false;
		}
	}
//	alert("validateday end");
	return true;
}

function validateYear(field,fieldname)
{
		var input = parseInt(field);
		if(isNaN(input))
		{
			alert("Error occured in field:" + fieldname + ". Please enter a 4 digit year!");
			return false;
		}
		else
		{
			if((input<1900) || (input>2999))
			{	
				alert("Error occured in field:" + fieldname + ". Please enter a valid year.");
				return false;
			}
		}
//		alert("validateyear end");
	return true;
}

//End of Part I

function formatFloat (expr, decplaces) 
{

	var str = "" + Math.round(eval(expr) * Math.pow(10, decplaces));
	
	while (str.length <= decplaces) {
		str = "0" + str;			
	}	

	var decpoint = str.length - decplaces;
	
	return str.substring(0, decpoint) + "." + str.substring(decpoint, str.length);
}

function getSBUSxnoStartChar(sbuid)
{
	var ret="";
	if(sbuid=="806") ret="6";
	if(sbuid=="911") ret="9";
	return ret;
}


// general purpose function to see if an input value has been entered at all
// Returns true if string s is empty or
// whitespace characters only.
function isWhitespace (s)
{   // Is s empty?	
    return (isEmpty(s) || reWhitespace.test(s));
}


function isEmpty (inputStr)
{
	if (inputStr == "" || inputStr == null)
		return true;
	else
		return false;
}




// function:
//	checkCheckType
// description:
//	Check if the input field is a valid Check Type
//	Only alphabets, numbers, '-', '+', '&', '/', '(', ')' or spaces.
//	Also display the error message.
// parameters :		
//	inputField		input field
//	fieldLabel		label of the field
// return :	
//	true			input field passes check
//	false			input field fails check
// assumptions :
//
function checkCheckType(inputField, fieldLabel) {

	str = inputField.value;

	if (!reCheckType.test(str)) {
		alert("Please enter only alphanumeric characters, or "
		 + "characters '-', '+', '&', '/' , '(', ')', "
		 + "or spaces for " + fieldLabel + ".");					
		select(inputField);
		return false;
	}

	return true;
}
function checkPrefix(str, inputField, fieldLabel) 
{
	//var rePrefix = new RegExp(/[^a-zA-Z0-9\-]/); 
	
	// Check for white space
	if (rePrefix.test(str)) {
		alert("Please enter only alphanumeric characters, or "
			 + "characters '-' for " + fieldLabel + ".");		
		select(inputField);
		return false;
	}
	return true;
}

function checkString(inputField, fieldLabel, AllowSpace) {
	str = inputField.value;
	
	if (AllowSpace) {
		if (!reGeneralStringSp.test(str)) {
			alert("Please enter a alpha numeric string for " + fieldLabel + ". \n\n" +						      	      
			      "Note that single quote (') or ('@')is not allowed.")    					
			select(inputField);
			return false;
		}
	}
	else {
		if (!reGeneralString.test(str)) {
			alert("Please enter a alpha numeric string for " + fieldLabel + ". \n\n" +						      	      
			      "Note that single quote (') or ('@') or space is not allowed.")    								
			select(inputField);
			return false;
		}
	}
	
	return true;
}

// function:
//	checkGenStringVale
// description:
//	Check if the field belongs to the valid list.
//	Also display the error message.
// parameters :		
//	inputField			input field
//	fieldLabel			label of the field
//	AllowSpace			indicator for allowing space (true/false)
// return :	
//	true			input field passes check
//	false			input field fails check
// assumptions :
//
function checkGenStringQuery(inputField, fieldLabel, AllowSpace) {
	str = inputField.value;
	
	if (AllowSpace) {
		if (!reGenStringSpQuery.test(str)) {
			alert("Please enter a alpha numeric string for " + fieldLabel + ", or \n" +
		      	      "a string containing only wildcards ('%') " +
		      	      "for " + fieldLabel + ". \n\n" +								      	      
			      "Note that single quote (') is not allowed.")    			      
			select(inputField);
			return false;
		}
	}	
	else {
		if (!reGenStringQuery.test(str)) {
			alert("Please enter a alpha numeric string for " + fieldLabel + ", or \n" +
		      	      "a string containing only wildcards ('%') " +
		      	      "for " + fieldLabel + ". \n\n" +								      	      
			      "Note that single quote (') or space is not allowed.")    			      					
			select(inputField);
			return false;
		}
	}
	
	return true;
}


function checkProjectDefinition(inputField, fieldLabel) 
{
	str = inputField.value;
/*	Project definition alphanumeric check	*/	
	if (reProjectDefinition.test(str)) {	
		return true;
	}	
	alert("Please enter a alpha numeric string followed by \'/" + 
		"\' for " + fieldLabel + ".  The string should not contain spaces, quotes or the " +
		"characters \'*\', \'(\' , \')\', \'\\', \'~\', \';\', \'<\', \'>\', \'|\'.")
	select(inputField);
	return false;
}


function checkGroupID(inputField, fieldLabel) 
{
	str = inputField.value;
/*	Group ID alphanumeric check	*/	
	if (reProjectDefinition.test(str)) {	
		return true;
	}	
	alert("Please enter a alpha numeric string for " + fieldLabel + 
		".  The string should not contain spaces, quotes or the " +
		"characters \'*\', \'(\' , \')\', \'\\', \'~\', \';\', \'<\', \'>\', \'|\'.")
	select(inputField);
	return false;
}



/* Compare two dates,if d2 later than d1 return true,otherwise return false */
function stcomparedate_string(d1,d2)
{
	var id=new Date(d1);	
	var od=new Date(d2);
		
	if(id>od){
		return false;
	}else{
		return true;
	}		
}


/* Compare two dates,if d2 later than d1 return true,otherwise return false */
function stcomparedate(d1,d2)
{
	var id=new Date(d1.value);
	var od=new Date(d2.value);
	if(id>od){
		return false;
	}else{
		return false;
	}		
}

// function:
//	checkServiceOrderNo | checkServiceOrderNoValue
// description:
//	Check if the input field is a valid Service Order number.
//	Must be all digits beginning with 6, minimum 8 chars and maximum 12 chars long
//	Also display the error message.
// parameters :		
//	inputField			input field
//	fieldLabel			label of the field
// return :	
//	true			input field passes check
//	false			input field fails check
// assumptions :
//
function checkServiceOrderNo(inputField,fieldLabel,sbuid) {

	var str = inputField.value;
	//alert("inputField: "+str);
	if(sbuid.value=="806")
	{
		//alert("1");
		if (!reSASServiceOrder.test(str)) {
			alert("Please enter a minimum of 8 numbers beginning with '6' for " + fieldLabel + ".");					
			select(inputField);
			return false;
		}
	}
	if(sbuid.value=="801")
		{
		if(!reEGRServiceOrder.test(str)){
			alert("Please enter a minimum of 8 numbers beginning with '1' for " + fieldLabel + ".");	
			select(inputField);
			return false;
		}
	}

	return true;
}

function checkServiceOrderNoValue(sxno,fieldLabel,sbuid) {
//	alert(str);
	if(sbuid.value=="806")
	{
		if (!reSASServiceOrder.test(sxno)) 
		{
			alert("Please enter a minimum of 8 numbers beginning with '6' for " + fieldLabel + ".");					
			//select(inputField);
			return false;
		}
	}
	if(sbuid.value=="801")
		{
		if(!reEGRServiceOrder.test(sxno)){
			alert("Please enter a minimum of 8 numbers beginning with '1' for " + fieldLabel + ".");	
		//	select(inputField);
			return false;
		}
	}

	return true;
}

// function:
//	checkServiceOrderNoQuery
// description:
//	Check if the input field is a valid Service Order number for query based on sbuid.
//	For SASCO and STA Engrg, Either
//	(a) all digits beginning with (6) for SASCO or (1) for STA Engrg, minimum 8 chars and maximum 12 chars long					
//	OR
//	(b) must contain at least one wildcard, and must begin with 6 or wildcard,
//		and consist of numbers or wildcard, and max 12 chars long.		
//	Also display the error message.
// parameters :		
//	inputField			input field
//	fieldLabel			label of the field
//      sbuid				input field from sbuid page
// return :	
//	true			input field passes check
//	false			input field fails check
// assumptions :
//
function checkServiceOrderNoQuery(inputField, fieldLabel,sbuid) {

	str = inputField.value;

	if(sbuid.value=="806") {
		// if expression is exact search, must begin with '6' + at least 7 digits
		if (reSASServiceOrder.test(str)) return true;
	
		// if expression is wildcard search
		if (reSASServiceOrderWildcard.test(str) && str.length <= 12) return true;

		alert("Please enter a minimum of 8 numbers beginning with '6', or \n" +
		      "a string containing only wildcards ('%') and numbers " +
		      "for " + fieldLabel + ".");					
		      
		select(inputField);
		return false;
	}

	if(sbuid.value=="801") {
		// if expression is exact search, must begin with '1' + at least 7 digits
		if (reEGRServiceOrder.test(str)) return true;
	
		// if expression is wildcard search
		if (reEGRServiceOrderWildcard.test(str) && str.length <= 12) return true;

		alert("Please enter a minimum of 8 numbers beginning with '1', or \n" +
		      "a string containing only wildcards ('%') and numbers " +
		      "for " + fieldLabel + ".");					
		      
		select(inputField);
		return false;
	}
		
	return true;
}

// function:
//	checkWorkcardNo
// description:
//	Check if the input field is a valid Workcard number
//		Only allow alphanumerics and '-' and '#' or '/'
//	Also display the error message.
// parameters :		
//	inputField		input field
//	fieldLabel		label of the field
// return :	
//	true			input field passes check
//	false			input field fails check
// assumptions :
//
function checkWorkcardNo(inputField, fieldLabel) {

	str = inputField.value;

	if (!reWorkcardNo.test(str)) {
		alert("Please enter only alphanumeric characters or '-' or '#' or '/' or '.' for " + fieldLabel + ".");
		select(inputField);
		return false;
	}

	return true;
}

function checkAttachmentName(inputField, fieldLabel) {
	
	string = inputField.value;
	var arrFileName=string.split("\\");
	
	//alert(arrFileName[arrFileName.length -1]);
	
	var iChars = "*|,\"<>[]{}`';@&$#%";
	for (var i = 0; i < arrFileName[arrFileName.length -1].length; i++) 
	{
		if (iChars.indexOf(arrFileName[arrFileName.length -1].charAt(i)) != -1)
		{
			alert("Please enter only alphanumeric characters or numbers or '-' or '_' or ' ' or '()' for " + fieldLabel + ".");
			select(inputField);
			return false;
		}	
	}	
	return true;
	
}


// function:
//	checkWorkcardNoAllowMany
// description:
//	Check if the input field is a valid Workcard number
//		Only allow alphanumerics and '-' and '#' and ',' and '/'
//	Also display the error message.
// parameters :		
//	inputField		input field
//	fieldLabel		label of the field
// return :	
//	true			input field passes check
//	false			input field fails check
// assumptions :
//
function checkWorkcardNoAllowMany(inputField, fieldLabel) {

	str = inputField.value;

	if (!reWorkcardNoAllowMany.test(str)) {
		alert("Please enter only alphanumeric characters or '-' or '#' or ',' or '/', or '.' for " + fieldLabel + ".");
		select(inputField);
		return false;
	}

	return true;
}


// function:
//	checkWorcardNoQuery
// description:
//	Check if the input field is a valid Workcard number for query.
//	Only alphanumeric characters or '-' or '#' or '%' or '/' or '.'
//	Also display the error message.
// parameters :		
//	inputField			input field
//	fieldLabel			label of the field
// return :	
//	true			input field passes check
//	false			input field fails check
// assumptions :
//
function checkWorkcardNoQuery(inputField, fieldLabel) {

	str = inputField.value;

	if (reWorkcardNoWildcard.test(str)) return true;
	
	alert("Please enter only alphanumeric characters or '-' or '#' or '/' or '.' or wildcards ('%') for " + fieldLabel + ".");
	select(inputField);
	return false;
}


// function:
//	checkCheckType
// description:
//	Check if the input field is a valid Check Type
//	Only alphabets, numbers, '-', '+', '&', '/', '(', ')' or spaces.
//	Also display the error message.
// parameters :		
//	inputField		input field
//	fieldLabel		label of the field
// return :	
//	true			input field passes check
//	false			input field fails check
// assumptions :
//
function checkCheckType(inputField, fieldLabel) {

	str = inputField.value;

	if (!reCheckType.test(str)) {
		alert("Please enter only alphanumeric characters, or "
		 + "characters '-', '+', '&', '/' , '(', ')', "
		 + "or spaces for " + fieldLabel + ".");					
		select(inputField);
		return false;
	}

	return true;
}

// function:
//	checkJobNo
// description:
//	Check if the input field is a valid job number
//	Only alphabets, numbers, '-' and '/'.
//	Also display the error message.
// parameters :		
//	inputField		input field
//	fieldLabel		label of the field
// return :	
//	true			input field passes check
//	false			input field fails check
// assumptions :
//
function checkJobNo(inputField, fieldLabel) {

	str = inputField.value;

	if (!reJobNo.test(str)) {
		alert("Please enter only alphanumeric characters or characters '-', '/'"
		 + " for " + fieldLabel + ".");					
		select(inputField);
		return false;
	}

	return true;
}

// function:
//	checkJobNoQuery
// description:
//	Check if the input field is a valid job number for query
//	Only alphabets, numbers, '-', '/' and '%'.
//	Also display the error message.
// parameters :		
//	inputField		input field
//	fieldLabel		label of the field
// return :	
//	true			input field passes check
//	false			input field fails check
// assumptions :
//
function checkJobNoQuery(inputField, fieldLabel) {

	str = inputField.value;

	if (!reJobNoWildcard.test(str)) {
		alert("Please enter only alphanumeric characters or characters '-', '/',\n"
		 + " or wildcards ('%') for " + fieldLabel + ".");					
		select(inputField);
		return false;
	}

	return true;
}

// function:
//	checkZoneNo
// description:
//	Check if the input field is a valid zone number.
//	Must be a 3 digit value.
//	Also display the error message.
// parameters :		
//	inputField		input field
//	fieldLabel		label of the field
// return :	
//	true			input field passes check
//	false			input field fails check
// assumptions :
//
function checkZoneNo(inputField, fieldLabel) {

	str = inputField.value;

	if (!reZoneNo.test(str)) {
		alert("Please enter a 3 digit number for " + fieldLabel + ".");					
		select(inputField);
		return false;
	}

	return true;
}

// function:
//	checkZoneNoQuery
// description:
//	Check if the input field is a valid Zone number for query.
//	Either
//	(a) a 3 digit value ; exact search					
//	OR
//	(b) contain at least 1 wildcard and a 0 - 3 char string consisting of 
//		numbers and wildcards.
//	Also display the error message.
// parameters :		
//	inputField		input field
//	fieldLabel		label of the field
// return :	
//	true			input field passes check
//	false			input field fails check
// assumptions :
//
function checkZoneNoQuery(inputField, fieldLabel) {

	str = inputField.value;
	
	if (reNumeric.test(str)) {		// contains all numeric characters ?
		// expression must be exact search
		if (reZoneNo.test(str)) return true;			
	}
	else {	
		// expression must be 0-3 numbers + wildcards
		if (reZoneNoWildcard.test(str)) return true;
	}			
		
	alert("Please enter a 3 digit number, or only numbers\n"
		+ "and at least 1 wildcard ('%') for " + fieldLabel + ".");					
	select(inputField);

	return false;
}


// function:
//	checkSignNDec
//
// description:
//	check if a string contains a number, including sign and maximum number of decimal places.
//	p.s. sorry if this function seems too messy and non-standard.
//
// parameters :		
//	s			input string
//	sign			sign of number:
//					"+" - positive
//					"-" - negative
//					"" - does not matter
//	maxDecimalPlaces	maximum decimal places:
//					"0" - no decimal places, i.e. integer
//					"n" (n is a number) - maximum n decimal places
//					"" - does not matter
// return :	
//	0	ok
//	1	not a number
//	2	sign is not correct
//	3	not an integer
//	4	too many decimal places	
//	5	bad parameters
//
// assumptions :
//	The input string is already trimmed of leading and trailing blanks
//
function checkSignNDec( s, sign, maxDecimalPlaces ) {
    
    str = s.toString();
    metDecimalPoint = false;	// encountered decimal point ?
    metSign = false;		// encountered sign ?
    metDigit = false;
    numDecimalPlaces = 0;
    startPos = 0;

    if (s.length == 0) return 0;

    if (!( sign == "-" || sign == "+" || sign == "" )) return 5;	// bad parameters
    if (isNaN(maxDecimalPlaces) && maxDecimalPlaces != "") return 5;	// bad parameters
    
    var oneChar = str.charAt(startPos);
    if (oneChar == "-" || oneChar == "+") {
	if (sign != "" && oneChar != sign)
		return	2;		// sign is not correct	   	 
   	startPos+=1;
    }
        
    for (i = startPos; i < str.length; i++) {
	
	var oneChar = str.charAt(i);
	
	if (oneChar == ".") {
		if (maxDecimalPlaces == "0") // not an integer
			return 3;	
		else {
			if (metDecimalPoint)	// already encountered decimal point
				return 1;
			else {
				metDecimalPoint = true;	
				continue;	
			}				
		}				
	}
	
	if (oneChar < "0" || oneChar > "9") {
		return 1;
  	}
    	else {
    		metDigit = true;
    		if (metDecimalPoint) {
    			numDecimalPlaces++;
    			if (maxDecimalPlaces != "" && numDecimalPlaces > maxDecimalPlaces) return 4;
    		}
    	}    	
    
    }
    
    if (!metDigit) return 1;					// not a number
    if (metDecimalPoint && numDecimalPlaces == 0) return 1;	// not a number


    return 0;
}


// function:
//	checkFieldSignNDec
//
// description:
//	Check if a field contains a number, including sign and maximum number of decimal places.
//	Also display the error message.
//
// parameters :		
//	inputField		input field
//	sign			sign of number:
//					"+" - positive
//					"-" - negative
//					"" - does not matter
//	maxDecimalPlaces	maximum decimal places:
//					"0" - no decimal places, i.e. integer
//					"n" (n is a number) - maximum n decimal places
//					"" - does not matter
//	fieldLabel		label of the field
//
// return :	
//	0	ok
//	1	not a number
//	2	sign is not correct
//	3	not an integer
//	4	too many decimal places	
//	5	bad parameters
//
// assumptions :
//	The input field value is already trimmed of leading and trailing blanks
//
function checkFieldSignNDec( inputField, sign, maxDecimalPlaces, fieldLabel ) {

	var messageEnding = '';
	if (fieldLabel != '')
		messageEnding = ' for ' + fieldLabel + '.';
	else
		messageEnding = '.';
		
	var i = checkSignNDec(inputField.value, sign, maxDecimalPlaces);
	
	if (i == 0) return i;
	
	if (i == 1) alert('Please enter a number' + messageEnding);

	if (i == 2) { 
		if (sign == "+")
			alert('Please enter a positive number' + messageEnding);
		else
			if (sign == "-")
				alert('Please enter a negative number' + messageEnding);
			else			
				alert('Please enter a number of the correct sign' + messageEnding);
			
	}

	if (i == 3) alert('Please enter an integer' + messageEnding);
		
	if (i == 4) alert('Please limit the number of decimal places to ' + maxDecimalPlaces
			+ messageEnding);	

	if (i== 5) alert('Bad parameters for function'); 
	
	select(inputField);			
		
	return i;
}


// function:
//	checkHours
//
// description:
//	Check if a hours field is valid:
//		1) empty string, or a non-negative float with maximum decimal places 2
//		2) not equal to zero
//	Used for checking estimated / budgeted hours for projects and task cards.
//	Also display the error message.
//
// parameters :		
//	inputField		input field
//	fieldLabel		label of the field
//	allowZero [optional]	allow zero : true or false; if not specified, is taken as false
// return :	
//	true			input field passes check
//	false			input field fails check
//
// assumptions :
//	The input field value is already trimmed of leading and trailing blanks
//
function checkHours(inputField, fieldLabel, allowZero) {
	
	// message already displayed in function checkFieldSignNDec
	if (checkFieldSignNDec(inputField, '+', '2', fieldLabel) != 0) return false;

	if (allowZero) return true;
	
	// hours cannot be zero
	if (inputField.value != '' && (parseFloat(inputField.value) == 0.00)) {
		alert('Please enter a non-zero figure for ' + fieldLabel + '.' );		
		select(inputField);
		return false;
	}
	
	return true;	
	
}


// function:
//	checkHoursQuery
// description:
//	Check if the input operator and hours value used to query for records are valid.
//	E.g. if user entered an operator, like '=', '>=' then the hours value must be non-empty.
//	Also check for validity of hours field.
//	Also display the error message.
// parameters :		
//	inputOpField		input operator field; it MUST be a SELECT input type:
//					"All" - ignore the value of hours of desired records
//					"Empty" - hours of desired records must be null
//					"Filled" - hours of desired records must be non-null
//					">="
//					">"
//					"<="
//					"<"
//	inputHoursField		input hours field
//	fieldLabel		label of the field
// return :	
//	true			input field passes check
//	false			input field fails check
// assumptions :
//
function checkHoursQuery(inputOpField, inputHoursField, fieldLabel,allowZero) {

	var hoursOp = inputOpField.options[inputOpField.selectedIndex].value;
//	if (hoursOp == 'All' || hoursOp == 'Empty' || hoursOp == 'Filled') {

	if (hoursOp == 'All' || hoursOp == 'is null' || hoursOp == 'is not null') {
	}
	else {
		// if user chose an operator, must enter value of hours
		if (isWhitespace(inputHoursField.value)) {
			alert('Please enter ' + fieldLabel + '.');
			inputHoursField.focus();
			return false;		
		}			
		else {
			// check the format of the value of hours
			if (!checkHours(inputHoursField, fieldLabel,allowZero)) return false;	
		}			
	}

	return true;
}


// function:
//	hasWhitespace
// description:
//	Check if the input field contains whitespace
//	If true, display the error message.
// parameters :		
//	inputField		input field
//	fieldLabel		label of the field
// return :	
//	true			input field fails check
//	false			input field pass check
// assumptions :
//
function hasWhitespace(inputField, fieldLabel) {

	str = inputField.value;

	if (reWhitespace.test(str)) {
		alert("Whitespace or blanks are not allowed for " + fieldLabel + ".");
		select(inputField);
		return false;
	}

	return true;
}

function checkEmployeeNo(empno,sbuid)
{
	if(!reEmployeeNo.test(empno))
	{
		alert("Only 8 numeric characters allowed in employee No field");
		return false;
	}
	else
	{
		if(empno.substring(0,3)!=sbuid)
		{
			alert("Please make sure your employee no starts with " + sbuid);
			return false;
		}
	}
	return true;
}


function checkCheckBox(inputField) {
 for (var cb=0; cb < inputField.length; cb++)
 {
   if (inputField[cb].checked)
       return true;
 }
 return false;
}

function checklength(field,maxlength)
{
	if (field.value.length > maxlength) {
		var maxstring = "" + maxlength ;
		alert ("Input field has a max of " + maxstring);
		field.focus();
	}
}

function Trim(TRIM_VALUE)
{
	if(TRIM_VALUE.length < 1)
		return "";
	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);
	
	if(TRIM_VALUE=="")
		return "";
	else
		return TRIM_VALUE;
}

function RTrim(VALUE)
{
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 0)
		return"";

	var iTemp = v_length -1;

	while(iTemp > -1)
	{
		if(VALUE.charAt(iTemp) == w_space){}
		else
		{
			strTemp = VALUE.substring(0,iTemp +1);
			break;
		}
		iTemp = iTemp-1;
	}

	return strTemp;
}

function LTrim(VALUE)
{
	var w_space = String.fromCharCode(32);
	if(v_length < 1)
		return "";

	var v_length = VALUE.length;
	var strTemp = "";
	var iTemp = 0;

	while(iTemp < v_length)
	{
		if(VALUE.charAt(iTemp) == w_space){}
		else
		{
			strTemp = VALUE.substring(iTemp,v_length);
			break;
		}
		iTemp = iTemp + 1;
	}
	
	return strTemp;
}

/*Added By Jacinth, check date format for SBUs*/
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
	for (i = 0; i < s.length; i++){   
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}

function stripCharsInBag(s, bag){
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++){   
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
			if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
			if (i==2) {this[i] = 29}
		} 
	return this
	}
	
//------------------------------------------------------------------
// Modified by Jacinth on 2005 Jul 11
// to check for non numeric chars on date fields and display err msg
//------------------------------------------------------------------
function checkDate(dtStr,fieldname,sbuid){
	var daysInMonth = DaysArray(12)
		var pos1=dtStr.indexOf(dtCh)
		var pos2=dtStr.indexOf(dtCh,pos1+1)
		var strMonth;
		var strDay;
		var dateformat = GetDateFormat(sbuid)
		if (dateformat=="DD/MM/YYYY")
		{
			strMonth=dtStr.substring(pos1+1,pos2)
			strDay=dtStr.substring(0,pos1)			
		}
		else
		{
			strMonth=dtStr.substring(0,pos1)
			strDay=dtStr.substring(pos1+1,pos2)
		}
		var strYear=dtStr.substring(pos2+1)
		strYr=strYear
		if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
			if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
				for (var i = 1; i <= 3; i++) {
					if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
					}
		month=parseInt(strMonth)
		day=parseInt(strDay)
		year=parseInt(strYr)
		if (pos1==-1 || pos2==-1){
			alert("Invalid date format for "+fieldname+". The date should be in "+dateformat+ " format.");
				return false
			}
		if (strMonth.length<1 || month<1 || month>12){
			alert("Please enter a valid month for "+fieldname+".")
				return false
			}
		if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
			alert("Please enter a valid day for "+fieldname+".")
				return false
			}
		if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
			alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear+" for "+fieldname+".")
				return false
			}
		if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
			alert("Please enter a valid date for "+fieldname+".")
				return false
			}
		return true
}

function GetDateFormat(SBUID)
{
	var SBUdateformat;
	
	switch (SBUID)
	{
	case "801": 
		SBUdateformat = "DD/MM/YYYY"
		break;
	case "802": 
		SBUdateformat = "DD/MM/YYYY"
		break;
	case "803": 
		SBUdateformat = "DD/MM/YYYY"
		break;		
	case "806": 
		SBUdateformat = "DD/MM/YYYY"
		break;
	case "808": 
		SBUdateformat = "DD/MM/YYYY"
		break;
	case "921": 
		SBUdateformat = "DD/MM/YYYY"
		break;
	default : SBUdateformat = "eeeMM/DD/YYYY"
	}
	return SBUdateformat;
}
