// BASIC DATA VALIDATION FUNCTIONS:
//
// isWhitespace (s)
// isLetter (c)
// isCapsLetter(c)
// isDigit (c)
// isLetterOrDigit (c)
// isInteger (s [,eok])
// isSignedInteger (s)
// isNonnegativeInteger (s)
// isFloat (s [,ndecimals][,eok])
// isAlphabetic (s [,eok])
// isAlphanumeric (s [,eok])
// isIntegerInRange (s, a, b)
// isEmail (s [,eok])
// isYear (s [,eok])
// isMonth (s [,eok])
// isDay (s [,eok])
// daysInFebruary (year)
// isDate (year, month, day)
// isDateGreater(fDate, tDate)
// isLength (s, lVal, uVal)
// isPassword (s)
// isDateEqual (fDate, tDate) 
// isFromDateGreater (fDate, tDate)
// isSpecialCharacter(s)
// isFirstCharacter(s)
// chkKey(e)
// isDateDiffLessThanOneYear (fDate, tDate)
// toDateMonthValidation (tDate, sDate, day) 
// isGoodPhoneFax(no)
// emailCheck
// isUsernameSpecialCharacter(s)
// trimSpace
// isSingleWord
// isUsernameSpecialCharacter
// checkRemarksLength(s)
// checkforSpaceandEnterchars(s)
// checkRemarksWithLength(s,length)
// isGoodName(s)

// VARIABLE DECLARATIONS

var whitespace = " \t\n\r";

var decimalPointDelimiter = "."

var defaultEmptyOK = false

function makeArray(n) {
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}

var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function isWhitespace (s)
{   var i;

    if (isEmpty(s)) return true;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (whitespace.indexOf(c) == -1) return false;
    }

    return true;
}

function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}

function isCapsLetter (c)
{   return ( ((c >= "A") && (c <= "Z")) )
}


function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

function isInteger (s)
{   var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (!isDigit(c)) return false;
    }

    return true;
}

function isSignedInteger (s)
{   if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}

function isNonnegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) >= 0) ) );
}

function isFloat (s)
{   var i;
    var seenDecimalPoint = false;
    var NoOfDecimals=0;
    var decimals = 0;
    

    if (isEmpty(s)) 
       if (isFloat.arguments.length == 3) return defaultEmptyOK;
       else return (isFloat.arguments[2] == true);

	if (isFloat.arguments.length == 2)
	{
		decimals = isFloat.arguments[1];
	}

    if (s == decimalPointDelimiter) return false;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if ((c == decimalPointDelimiter) && !seenDecimalPoint) seenDecimalPoint = true;
        else if (!isDigit(c)) return false;
        if (seenDecimalPoint && c != decimalPointDelimiter && decimals != 0)
        {
			NoOfDecimals++;
			if (NoOfDecimals > decimals) return false;
		}

    }

    return true;
}

function isAlphabetic (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (!isLetter(c))
        return false;
    }

    return true;
}

function isAlphanumeric (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);

        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    return true;
}

function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    if (isWhitespace(s)) return false;

	if(!(isSpecialCharacterForEmail(s))) return false;
														// Checking for special characters other than @ and .

    var i = 1;
    var sLength = s.length;

    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
//    else return true;

	
    if(s.substring(s.indexOf('@')+1).indexOf('@')>=0 || s.substring(s.indexOf('@')+1).indexOf('.')< 0)
    {
  		return false;
    }
    else if( (s.charAt(s.length-1)=='.') || (s.charAt(s.length-2)=='.')){
	 	return false;
    }
	else return true;

}

function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    if (!isInteger(s, false)) return false;

    var num = parseInt (s);
    return ((num >= a) && (num <= b));
}

function isYear (p)
{   var s = p.toString();
	if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}

function isMonth (p)
{   var s = p.toString();
	if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}

function isDay (p)
{   var s = p.toString();
	if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 1, 31);
}

function daysInFebruary (year)
{   return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}

function isDate (pyear, pmonth, pday)
{   
	year = pyear.toString();
	month = pmonth.toString();
	day = pday.toString();
	
	if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);

    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}

function isLength (s, lVal, uVal)
{   if (isEmpty(s)) 
       if (isLength.arguments.length == 1) return defaultEmptyOK;
       else return (isLength.arguments[1] == true);

    var sLength = s.length;
    if (sLength < lVal || sLength > uVal) return false;

    return true;
}

function isPassword (s)
{   var i;

    if (isEmpty(s)) 
       if (isPassword.arguments.length == 1) return defaultEmptyOK;
       else return (isPassword.arguments[1] == true);

    var nCount = 0;
    var aCount = 0;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (isLetter(c)) aCount++;
        if (isDigit(c)) nCount++;
    }

    if (aCount < 2 || nCount < 2) return false; 
 
	aCount = 0;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (isCapsLetter(c)) aCount++;
    }

    if (aCount < 1) return false; 

    return true;
}

function isUserName (s)
{   var i;

    if (isEmpty(s)) 
       if (isUserName.arguments.length == 1) return defaultEmptyOK;
       else return (isUserName.arguments[1] == true);

    var nCount = 0;
    var aCount = 0;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (isLetter(c)) aCount++;
        if (isDigit(c)) nCount++;

    }

    if (aCount < 1 || nCount < 1) return false; 
 
    return true;
}

function isDateEqual (fDate, tDate)
{
    var frmDate = new Date();
    var toDate = new Date();
    
    frmDate.setTime(Date.parse(fDate));
    toDate.setTime(Date.parse(tDate));

	if (	(frmDate.getDate() == toDate.getDate()) 
			&& (frmDate.getMonth() == toDate.getMonth()) 
			&& (frmDate.getYear() == toDate.getYear())
		)
		return true;
	else
		return false;
}

function isDateGreater (fDate, tDate)
{
    var frmDate = new Date();
    var toDate = new Date();
    
    frmDate.setTime(Date.parse(fDate));
    toDate.setTime(Date.parse(tDate));

	if ((frmDate.getYear() < toDate.getYear()) ||
		((frmDate.getMonth() < toDate.getMonth()) && frmDate.getYear() == toDate.getYear()) ||
		((frmDate.getDate() < toDate.getDate()) && (frmDate.getMonth() == toDate.getMonth()) && frmDate.getYear() == toDate.getYear())
		)
		return false;
	else
		return true;
}

function isSingleWord (s)
{   if (isEmpty(s)) 
       if (isSingleWord.arguments.length == 1) return defaultEmptyOK;
       else return (isSingleWord.arguments[1] == true);
     
    var sCount = 0;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
	if (c == " ") sCount++;
    }

    if (sCount > 0) return false;

    return true;
}

function isFromDateGreater (fDate, tDate)
{
    if(isDateEqual (fDate, tDate)) return false;
    else
    var frmDate = new Date();
    var toDate = new Date();
    
    frmDate.setTime(Date.parse(fDate));
    toDate.setTime(Date.parse(tDate));

	if ((frmDate.getYear() < toDate.getYear()) ||
		((frmDate.getMonth() < toDate.getMonth()) && frmDate.getYear() == toDate.getYear()) ||
		((frmDate.getDate() < toDate.getDate()) && (frmDate.getMonth() == toDate.getMonth()) && frmDate.getYear() == toDate.getYear())
		)
		return false;
	else
		return true;
}


function isSpecialCharacter(s)	{
	for (i = 0; i < s.length; i++)
	{   
	    var c = s.charAt(i);
	    if ( (s.charAt(i) == "~") 
	    || (s.charAt(i) == "!") 
	    || (s.charAt(i) == "@") 
	    || (s.charAt(i) == "#") 
	    || (s.charAt(i) == "$") 
	    || (s.charAt(i) == "%") 
	    || (s.charAt(i) == "*")
		|| (s.charAt(i) == ";")		   
		|| (s.charAt(i) == ":") 
	    || (s.charAt(i) == ",") 
	    || (s.charAt(i) == ".") 
	    || (s.charAt(i) == "/") 
	    || (s.charAt(i) == "?") 
	    || (s.charAt(i) == "+") 
	    || (s.charAt(i) == "|") 
	    || (s.charAt(i) == "&") 
	    || (s.charAt(i) == "<") 
  	    || (s.charAt(i) == ">") 
	    || (s.charAt(i) == "”") 
  	    || (s.charAt(i) == "’") 
		)
	    return false;
	}    

    return true;
}	 

function isMalicousCharacter(s)	{
	for (i = 0; i < s.length; i++)
	{   
	    var c = s.charAt(i);
	    if ( (s.charAt(i) == "~") 
	    || (s.charAt(i) == "<") 
  	    || (s.charAt(i) == ">") 
		|| (s.charAt(i) == ")") 
		|| (s.charAt(i) == "(") 
	    || (s.charAt(i) == "”") 
  	    || (s.charAt(i) == "’") 
		|| (s.charAt(i) == ";")	
	    || (s.charAt(i) == "%") 
		|| (s.charAt(i) == "&") 
		)
	    return false;
	}    

    return true;
}


function isMalicousUserNameCharacter(s)	{
	for (i = 0; i < s.length; i++)
	{   
	    var c = s.charAt(i);
	   if ( (s.charAt(i) == "~") 
	    || (s.charAt(i) == "!") 
	    || (s.charAt(i) == "@") 
	    || (s.charAt(i) == "#") 
	    || (s.charAt(i) == "$") 
	    || (s.charAt(i) == "%") 
	    || (s.charAt(i) == "*")
		|| (s.charAt(i) == ";")		   
		|| (s.charAt(i) == ":") 
	    || (s.charAt(i) == ",") 
		|| (s.charAt(i) == ".") 
	    || (s.charAt(i) == "/") 
	    || (s.charAt(i) == "?") 
	    || (s.charAt(i) == "+") 
	    || (s.charAt(i) == "|") 
	    || (s.charAt(i) == "&") 
		|| (s.charAt(i) == "<") 
  	    || (s.charAt(i) == ">") 
		|| (s.charAt(i) == ")") 
		|| (s.charAt(i) == "(") 
	    || (s.charAt(i) == "{") 
		|| (s.charAt(i) == "}") 
	    || (s.charAt(i) == "[") 
		|| (s.charAt(i) == "]") 
		|| (s.charAt(i) == "=") 
  		|| (s.charAt(i) == "^") 
		|| (s.charAt(i) == "`") 
		)
	    return false;
	}    

    return true;
}

function isSpecialCharacterForEmail(s)	{
	for (i = 0; i < s.length; i++)
	{   
	    var c = s.charAt(i);
	    if ( (s.charAt(i) == "~") 
	    || (s.charAt(i) == "!") 
	    || (s.charAt(i) == "#") 
	    || (s.charAt(i) == "$") 
	    || (s.charAt(i) == "%") 
	    || (s.charAt(i) == "*")
		|| (s.charAt(i) == ";")		   
		|| (s.charAt(i) == ":") 
	    || (s.charAt(i) == ",") 
	    || (s.charAt(i) == "/") 
	    || (s.charAt(i) == "?") 
	    || (s.charAt(i) == "+") 
	    || (s.charAt(i) == "|") 
	    || (s.charAt(i) == "&") 
		)
	    return false;
	}    

    return true;
}

function isFirstCharacter(s) {
		var c = s.charAt(0);
		if (!isLetter(c)) return false; 

	return true;
}


function chkKey(e){
	var BRW = (document.all)?"IE":"NS";
	var strKeyCode;
			
	if (BRW == "IE"){		
		strKeyCode = e.keyCode;
	}
	else if (BRW == "NS"){
		strKeyCode = e.which;
	}
			
	if (strKeyCode == 13){			
			return false;	
	}	
	return true;			
}


function isDateDiffLessThanOneYear(fDate, tDate) {
    var fromDate = new Date();
    var toDate = new Date();

    fromDate.setTime(Date.parse(fDate));
    toDate.setTime(Date.parse(tDate));

	if (toDate.getYear() - fromDate.getYear() > 1)
		return false;
		
	if ((toDate.getYear() - fromDate.getYear() == 1) && 
		(toDate.getMonth() > fromDate.getMonth())
		)
		return false;
	
	if (
		(toDate.getYear() - fromDate.getYear() == 1) && 
		(toDate.getMonth() == fromDate.getMonth()) &&
		(toDate.getDate() > fromDate.getDate())
		)
		return false;
	
	return true;
}


//This function finds whether the month of todate is correct 
//depending on today's date (indicated by "day" - see Constants file).

function toDateMonthValidation(tDate, sDate, day) {

    var toDate = new Date();
    var sysDate = new Date();
    
    toDate.setTime(Date.parse(tDate));
	sysDate.setTime(Date.parse(sDate));

	if (sysDate.getDate() < day) 
		if ((toDate.getMonth()>= sysDate.getMonth() - 1) && (toDate.getYear() >= sysDate.getYear()))
			return false;
		else
			return true;
	else 
		if ((toDate.getMonth()>= sysDate.getMonth()) && (toDate.getYear() >= sysDate.getYear()))
			return false;
		else
			return true;
}

function isGoodPhoneFax(no)
{
	var checkOK = "1234567890-"
	var checkStr = no.value;		
	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		if (ch == checkOK.charAt(j))
		break;
		if (j == checkOK.length)
		{			
			return false;
			break;
		}		
	}	
	return true;
}


// Function that checks for valid Email Using Javascript Regular Expressions
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. */

if (emailStr.length > 5) {

}

/* 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. */
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid
if (user.match(userPat)==null) {
    // user is not 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) {
	        return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	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.
      return false
}*/

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
    return false
}

// If we've gotten this far, everything's valid!
return true;
}

/*This function returns true if S is a single word else returns false */
function isSingleWord(s){
	var s = trimSpace(s);
	var b = true;
		for (i=0;i<s.length-1;i++){
			if (s.charAt(i)== " ") {
				b= false;
				break;
			}
		}
	return b;
}

//function to trim spaces
function trimSpace ( inputVal ) {
	var inputStr = "";
	if ( isEmpty ( inputVal ) ) {
		return inputStr;
	}

	for ( var i = 0; i < inputVal.length && inputVal.charAt ( i ) == " "; i++ ) {
	// do nothing here
	}
	if ( i == inputVal.length ) {
			inputVal = "";
			return inputVal;
	}
	var tmpStr = inputVal.substring( i, inputVal.length );
	for ( var j = tmpStr.length - 1; j>=0 && tmpStr.charAt ( j ) == " "; j-- ) {
			// do nothing here
	}
	j++;
	return tmpStr.substring (0, j);
}

function isUsernameSpecialCharacter(s)	{
	var i;
	if (isEmpty(s))
	   if (isUsernameSpecialCharacter.arguments.length == 1) return defaultEmptyOK;
	   else return (isUsernameSpecialCharacter.arguments[1] == true);

		if (!isMalicousUserNameCharacter(s)) return false;

		return true;
}

function checkRemarksLength(s)
{   
	if (s.length>2000) return false; 

	return true;
}

function checkforSpaceandEnterchars(s)
{   
	var sCount = 0;
    var eCount = 0;
    var tCount = s.length;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charCodeAt(i);
        if (c==32) sCount++;
        if ((c==13)||(c==10)) eCount++;
    }


	if ((sCount+eCount)==tCount) return false; 
    return true;
}

function checkRemarksWithLength(s,llength)
{   
	if (s.length>llength) return false; 

	return true;
}

function isGoodName(s)
{
    if (isEmpty(s)) 
       if (isGoodName.arguments.length == 1) return defaultEmptyOK;
       else return (isGoodName.arguments[1] == true);
   
    if (isWhitespace(s)) return false;

    if(!(isMalicousUserNameCharacter(s))) return false;
    
    if(!(isSpecialCharacter(s))) return false;
    
    
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        
        if (s.charAt(i)!= " ") 
        {
		if (!isLetter(c))
		return false;
	}
    } 
    
    return true;
}
