// formvalidation.js
//
// 18 Feb 97 created Eric Krock
//
// (c) 1997 Netscape Communications Corporation
//
// Modified by Jeffrey Leong

// FUNCTIONS TO INTERACTIVELY CHECK FIELD CONTENTS:
//
// checkString (theField, s [,eok])    		Check that theField.value is not empty or all whitespace.
// checkInteger (theField, s [,eok])    		Check that theField.value is not empty or all whitespace.
// checkCheckBox (obj, message, fullmsg) 	Check that theField.value is not empty or all whitespace.
// checkRadioButton (obj, message, fullmsg)
// checkDate (theField)							   		Check that theField.value is a valid Date
// checkEmail (theField [,eok])        		Check that theField.value is a valid Email.
// checkPhone (theField ,s [,eok])  	 		Check that theField.value is a valid phone number
// checkSelect(theField, field_default, message, fullmsg)
// checkPassword(theField_1, theField_2, field_size, msg_1, msg_2)
// checkPasswordNew(theField_1, theField_2, theField_3, field_size, msg_1, msg_2, msg_3) {


// isInteger (STRING s [, BOOLEAN emptyOK])
// isEmail (STRING s [, BOOLEAN emptyOK])
// checkInternationalPhone (theField [,eok])  Check that theField.value is a valid International Phone.
// promptEntry (s)

// FUNCTIONS TO REFORMAT DATA:
//
// stripCharsInBag (s, bag)            Removes all characters in string bag from string s.
// stripWhitespace (s)                 Removes all whitespace characters from s.
// stripInitialWhitespace (s)          Removes initial (leading) whitespace characters from s.
// reformat (TARGETSTRING, STRING,     Function for inserting formatting characters or
//   INTEGER, STRING, INTEGER ... )       delimiters into TARGETSTRING.



// VARIABLE DECLARATIONS

var digits = "0123456789";

var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"

var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"


// whitespace characters
var whitespace = " \t\n\r";


// decimal point character differs by language and culture
var decimalPointDelimiter = "."

var dtCh= "-";
var minYear=1900;
var maxYear=2100;

var phoneNumberDelimiters = "()- ";
var validWorldPhoneChars = phoneNumberDelimiters + "+";
var minDigitsInIPhoneNumber = 8;

// CONSTANT STRING DECLARATIONS
// (grouped for ease of translation and localization)

// m is an abbreviation for "missing"

var mPrefix = "Please enter a value for the "
var mSuffix = " field. This is required."

// s is an abbreviation for "string"
var sEmail = "Email"


// i is an abbreviation for "invalid"
var iEmail = "This field must be a valid Email Address. Please re-enter it now."
var iWorldPhone = "This field must be a valid phone number. Please re-enter it now."

// p is an abbreviation for "prompt"

var pEntryPrompt = "Please enter a "
var pEmail = "valid email address."

var defaultEmptyOK = false

function makeArray(n) {
//*** BUG: If I put this line in, I get two error messages:
//(1) Window.length can't be set by assignment
//(2) daysInMonth has no property indexed by 4
//If I leave it out, the code works fine.
//   this.length = n;
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   }
   return this
}


// Check whether string s is empty.

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}



// Returns true if string s is empty or
// whitespace characters only.

function isWhitespace (s)

{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}



// Removes all characters which appear in string bag from string s.

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++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}


// Removes all whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripWhitespace (s)

{   return stripCharsInBag (s, whitespace)
}

//
// charInString (CHARACTER c, STRING s)
//
// Returns true if single character c (actually a string)
// is contained within string s.

function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}


// Removes initial (leading) whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripInitialWhitespace (s)

{   var i = 0;

    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;

    return s.substring (i, s.length);
}



// Returns true if character c is an English letter
// (A .. Z, a..z).
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}



// Returns true if character c is a digit
// (0 .. 9).

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}



// Returns true if character c is a letter or digit.

function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}



// isInteger (STRING s [, BOOLEAN emptyOK])
//
// Returns true if all characters in string s are numbers.
function isInteger (s)

{   var i;

    if (isEmpty(s))
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }
    // All characters are numbers.
    return true;
}



// reformat (TARGETSTRING, STRING, INTEGER, STRING, INTEGER ... )
//           "(", 3, ") ", 3, "-", 4)

function reformat (s)

{   var arg;
    var sPos = 0;
    var resultString = "";

    for (var i = 1; i < reformat.arguments.length; i++) {
       arg = reformat.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
           resultString += s.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return resultString;
}

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 );
}

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
}


// isEmail (STRING s [, BOOLEAN emptyOK])
//
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isEmail (s)
{   if (isEmpty(s))
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);

    // is s whitespace?
    if (isWhitespace(s)) return false;

    // there must be >= 1 character before @, so we
    // start looking at character position 1
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}



/* FUNCTIONS TO NOTIFY USER OF INPUT REQUIREMENTS OR MISTAKES. */


// Display prompt string s in status bar.

function prompt (s)
{   window.status = s
}



// Display data entry prompt string s in status bar.

function promptEntry (s)
{   window.status = pEntryPrompt + s
}




// Notify user that required field theField is empty.
// String s describes expected contents of theField.value.
// Put focus in theField and return false.

function warnEmpty (theField, s)
{   theField.focus()
    alert(mPrefix + s + mSuffix)
    return false
}



// Notify user that contents of field theField are invalid.
// String s describes expected contents of theField.value.
// Put select theField, pu focus in it, and return false.

function warnInvalid (theField, s)
{   theField.focus()
    theField.select()
    alert(s)
    return false
}




/* FUNCTIONS TO INTERACTIVELY CHECK VARIOUS FIELDS. */

// checkString (TEXTFIELD theField, STRING s, [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is not all whitespace.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkString (theField, s, emptyOK)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if (checkString.arguments.length == 2) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (isWhitespace(theField.value))
       return warnEmpty (theField, s);
    else return true;
}

function checkInteger (theField, s, emptyOK)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if (checkInteger.arguments.length == 2) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (isWhitespace(theField.value))
       return warnEmpty (theField, s);
    else {
    	if (isInteger(theField.value))
    		return true;
    	else
    		return warnInvalid (theField, "This " + s+ " fields contains invalid Numbers! ");
    }
}

function checkCheckBox(obj, message, fullmsg)  {
   if (obj.checked) {
     return true;
   }   
   if (fullmsg == 1) {
      alert(message);
   } else {
      alert("Please choose an answer for " + message + ".");
   }  
   obj.focus();
   return false;
}

function checkRadioButton(obj, message, fullmsg)  {

   for (var i=0;i<obj.length;i++) {
       if (obj[i].checked) {
	  return true;
       }
   }

   if (fullmsg == 1) {
      alert(message);
   } else {
      alert("Please choose an answer for " + message + ".");
   }
   obj[0].focus();
   return false;
}


function checkDate(theField){
	
	var dtStr = theField.value
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	
	var strDay=dtStr.substring(0,pos1)
	var strMonth=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){
		return warnInvalid (theField,"The date format should be : DD-MM-YYYY" );		
	}
	
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return warnInvalid (theField,"Please enter a valid day");		
	}
	
	if (strMonth.length<1 || month<1 || month>12){
		return warnInvalid (theField,"Please enter a valid month" );		
	}	
	
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return warnInvalid (theField,"Please enter a valid 4 digit year between "+minYear+" and "+maxYear );		
	}
	
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return warnInvalid (theField,"Please enter a valid date");		
	}
	
	return true
}

// checkEmail (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid Email.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkEmail(theField, emptyOK) {

	var str = theField.value
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	
	if (checkEmail.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;	
	
	if ( (str.indexOf(at)==-1) ||
		 	 (str.indexOf(at)==-1  || str.indexOf(at)==0  || str.indexOf(at)==lstr)  ||
		 	 (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) ||
		 	 (str.indexOf(at,(lat+1))!=-1)  ||
		 	 (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) ||
		 	 (str.indexOf(dot,(lat+2))==-1) ||
		 	 (str.indexOf(" ")!=-1) )
		   
	   return warnInvalid (theField, iEmail);
	
 	else return true;					
}

function check_Email (theField, emptyOK)
{   if (checkEmail.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else if (!isEmail(theField.value, false))
       return warnInvalid (theField, iEmail);
    else return true;
}

// checkPhone (TEXTFIELD theField, STRING s [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid International Phone.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkPhone (theField,s, emptyOK)
{   if (checkPhone.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {
    	if (!isPhoneNumber(stripCharsInBag(theField.value,'-() ')))
          return warnInvalid (theField,"This field must be a valid " + s + ". Please re-enter it now.");
       else return true;
    }
}

// isPhoneNumber (STRING s [, BOOLEAN emptyOK])
//
// isInternationalPhoneNumber returns true if string s is a valid
// international phone number.  Must be digits only; any length OK.
// May be prefixed by + character.
//
// NOTE: A phone number of all zeros would not be accepted.
// NOTE: Strip out any delimiters (spaces, hyphens, parentheses, etc.)
// from string s before calling this function.  You may leave in
// leading + character if you wish.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function isPhoneNumber (s, emptyOK)
{
	if (isPhoneNumber.arguments.length == 1) emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (isEmpty(s.value))) return true;
  else
  {
    return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
  }
}

function checkSelect(theField, field_default, message, fullmsg) {
  
	if (!(theField.value == field_default)) {
		 return true
	}  
	if (fullmsg == 1) {
      alert(message);
  } else {
      alert("Please select a value for " + message + ".");
  }
  theField.focus();
  return false;  
}

// 
//
function checkPassword(theField_1, theField_2, field_size, msg_1, msg_2) {
	
	var password	   = theField_1.value;
	var confirmation = theField_2.value;

	if (password == '' || password.length < field_size) 
	{
		return warnInvalid(theField, msg_1)
	} 
	else if (password != confirmation) 
	{
		return warnInvalid(theField, msg_2)
	}
}

// 
//
function checkPasswordNew(theField_1, theField_2, theField_3, field_size, msg_1, msg_2, msg_3) {

	var password_current = theField_1.value;
	var password_new 		 = theField_2.value;
	var password_confirmation = theField_3.value;

	if (password_current == '' || password_current.length < field_size) 
	{
		return warnInvalid(theField, msg_1)
  } 
  else if (password_new == '' || password_new.length < field_size) 
  {
		return warnInvalid(theField, msg_2)
  } 
  else if (password_new != password_confirmation) 
  {
		return warnInvalid(theField, msg_3)
  }
}











/* concat by syeo... for form checking */

/**************************************************************
 LTrim: Returns a String containing a copy of a specified
        string without leading spaces

 Parameters:
      String = The required string argument is any valid
               string expression. If string contains null,
               false is returned

 Returns: String
***************************************************************/
function LTrim(String)
{
	var i = 0;
	var j = String.length - 1;

	if (String == null)
		return (false);

	for (i = 0; i < String.length; i++)
	{
		if (String.substr(i, 1) != ' ' &&
		    String.substr(i, 1) != '\t')
			break;
	}

	if (i <= j)
		return (String.substr(i, (j+1)-i));
	else
		return ('');
}

/**************************************************************
 RTrim: Returns a String containing a copy of a specified
        string without trailing spaces

 Parameters:
      String = The required string argument is any valid
               string expression. If string contains null,
               false is returned

 Returns: String
***************************************************************/
function RTrim(String)
{
	var i = 0;
	var j = String.length - 1;

	if (String == null)
		return (false);

	for(j = String.length - 1; j >= 0; j--)
	{
		if (String.substr(j, 1) != ' ' &&
			String.substr(j, 1) != '\t')
		break;
	}

	if (i <= j)
		return (String.substr(i, (j+1)-i));
	else
		return ('');
}

/**************************************************************
 RTrim: Returns a String containing a copy of a specified
        string without both leading and trailing spaces

 Parameters:
      String = The required string argument is any valid
               string expression. If string contains null,
               false is returned

 Returns: String
***************************************************************/
function Trim(String)
{
	if (String == null)
		return (false);

	return RTrim(LTrim(String));
}

/**************************************************************
 Len: Returns a Long containing the number of characters in a
      string or the number of bytes required to store a
      variable.

 Parameters:
      string = Any valid string expression. If string contains
               null, false is returned.

 Returns: Long
***************************************************************/
function Len(string)
{
	if (string == null)
		return (false);

	return String(string).length;
}