/*  
***************************************************************
File Name       : JSLIB.JS
Author          : ANGIE GOH
Creation Date   : FEB 22, 2002
Company         : FIRST CAPITAL COPORATION

Module Name     : JAVASCRIPT ERROR CHECKING LIBARAY
Description     : Libary contains common form error checking
                  functions that check for valid inputs.
Changes         :
Angie Goh
Mar 14, 2002    : Added function to check and uncheck all 
                  checkboxes in the form
Angie Goh
Mar 19, 2002    : Added function to check if a option in a list 
                  box element is selected

Mar 20, 2002    : Changed isChecked function to check  
Angie Goh         if at least one radio button is checked

Mar 25, 2002    : Added function to check input value is of 
Angie Goh         valid currency format

Apr 5, 2002     : Added function to check input value is of 
Angie Goh         a valid file format

May 14, 2002    : Added function to check input value is negative
Hu Qiongwen       number format

May 15, 2002    : Changed chkValidEmail to check for invalid characters 
Angie Goh         in user part of user@domain.com

Aug 5, 2002     : Added function to check input value conforms to 
Angie Goh         password standard of no blank, no whitespace and 
                  more than or equal to 6 characters

Jan 20, 2003    : Added function to check if the percentages 
Angie Goh         supplied in the textbox inputs adds up to 100%

Feb 17, 2003    : Added function to check the length of input value
Angie Goh         is within specified range

May 8, 2003     : Added function to check the input values of a HTML
Angie Goh         textarea contains only carriage returns

Sep 30, 2003    : Rewrite of the isValidFile function for a 
Angie Goh         more comprehensive function

16 Jun 2005     : Added modified script found on the net to check
Angie Goh         a string for invalid characters.

5 Jan 2006	: Added functions isInteger, stripCharsInBag and isPhone
Jason Widjaja	  to be used in combination to check for valid phone number

***************************************************************
*/


/*
***************************************************************
Author          : ANGIE GOH
Creation Date   : FEB 22, 2002
Description     : Check if input is blank
Input           : Form Field Value
Output          : True or False
***************************************************************
*/

function isBlank(argStr)
{

/* Check the length of the input is zero. If it is zero, the 
   form field is empty, therefore returns true. Otherwise returns
   false */

    if (argStr.length == 0)
    {
        return true;
    }

    else
    {
        return false;
    }
}



/*
***************************************************************
Author          : ANGIE GOH
Creation Date   : FEB 25, 2002
Description     : Check if input is a space. Function adapted from
                  Date Validation Script by Subramanya Shastry Y V H
Input           : Form Field Value
Output          : True or False
Changes         :
May 14, 2002    : Rectified the Undefinded state
Angie Goh
***************************************************************
*/

function isWhiteSpace(argStr)
{
  var inticount;
  inticount = 0;

// Converts the form field value to type String
    argStr = argStr.toString();


/* Checks each character in the form field value to see if it's a space 
   or a tab. If it is not a space or a tab, returns false. Otherwise 
   returns true */

    for (var intI = 0; intI < argStr.length; intI++)
    {    
      if (argStr.charAt(intI) != ' ' && argStr.charAt(intI) != '\t')
 	  {   
           inticount = inticount + 1;
      }
      
    } 
    
    if (inticount > 0)
    {
        return false;
    }
    
    else
    {
        return true;
    } 
}

/*
***************************************************************
Author          : ANGIE GOH
Creation Date   : FEB 25, 2002
Description     : Check if input is a number
Input           : Form Field Value
Output          : True or False
***************************************************************
*/


function isDigit(argNum)
{

/* Check to see if the form field value is not a number, or a space or is 
   blank. If it is not a number, or is a space or is blank, returns false. 
   Otherwise returns true */

    if ((isNaN(argNum)) || (isWhiteSpace(argNum)) || (isBlank(argNum)))
    {
        return false;
    }

    else
    {
        return true;
    }
}

/*
***************************************************************
Author          : Hu Qiong Wen
Creation Date   : May 14, 2002
Description     : Check if input is a negative number
Input           : Form Field Value
Output          : True or False
***************************************************************
*/
function isNegativeNumber(argNum)
{

/* Check to see if the form field value is a negative number.
   If it is a negative number returns true, Otherwise returns false */

    if (isNaN(argNum))
    {
        return false;
    }

    else
    { 
	if (argNum < 0)
	{
	    return true;
	} 
        else
        {
            return false;
        }
    }
}


/*
***************************************************************
Author          : ANGIE GOH
Creation Date   : FEB 26, 2002
Description     : Check if email address conforms to specified 
                  domains or email structure. Function adapated 
                  from Email Validation Script bt Sandeep V. 
                  Tamhankar
Input           : Form Field Value
Output          : True or False
Changes         :  
May 15, 2002    : Checks if the user part of user@domain.com
Angie Goh       : contains invalid characters
***************************************************************
*/


function chkValidEmail(argStr)
{
    var strDomainPat;
    var strEmailPat;
    var strSpecialChars;
    var strValidChars;
    var strWhiteSpacePat;
    var strAtom;
    var strWord;
    var strUserPat;
    var intCharCount;    
    var arrSplitString;

    intCharCount = 0;

/*  This pattern specifies the valid domains for matching. 
    The allowed domains are: 
    1) fcc.com.sg
    2) gisl.com.sg
    3) myhome.com.sg 
    4) guocoland.com.sg 

*/ 

//    strDomainPat = /^fcc.com.sg$|^gisl.com.sg$|^myhome.com.sg$|^guocoland.com.sg$/g;

/*  This pattern specifies the email structure for matching, i.e. 
    user@domain.com is a valid email structure */

    strEmailPat=/^(.+)@(.+)$/;

/*  This pattern specifies white space in the user part of an email
    address for matching, i.e. it matches the white space found in 
    "user  @domain.com" or "u  ser@domain.com"
*/
    strWhiteSpacePat = /\w*\s/


/*  The following string represents the pattern for matching all 
    special characters that are not allowed in an email address. 
    These characters include ( ) < > @ , ; : \ " [ ] */

    strSpecialChars = "\\(\\)><@,;:\\\\\\\"\\[\\]"

/*  The following string states which characters aren't allowed 
    in the domain or user part of an email address */ 

    strValidChars = "\[^\\s" + strSpecialChars + "\]";


/*  The following string represents a series of non-special 
    characters */

    strAtom = strValidChars + '+';

/*  The following string represents one word in the typical username.
    I.e., in user@domain.com, user is a word. A word is an atom. */

    strWord="(" + strAtom + ")";

//  The following pattern describes the structure of the user
    strUserPat = new RegExp("^" + strWord + "(\\." + strWord + ")*$");

/*  Performs matching of email structure by breaking the input into 
    two parts and stores into an array. If input cannot be broken, 
    the input is of an invalid email structure, returns false. */

    var strarrMatchArray = argStr.match(strEmailPat);

    if (strarrMatchArray == null) 
    {
        return false;
    }

//  Retrieves the username and domain from the array
    var strUser   = strarrMatchArray[1];
    var strDomain = strarrMatchArray[2];

/*  Performs matching of whitespace found in an email address. 
    If a match is found, returns false. */

    if ((strUser.match(strWhiteSpacePat) != null) || 
        (strDomain.match(strWhiteSpacePat) != null))
    {
        return false;
    }

/* Checks if only alpha numeric characters and . - _ are in the 
   email address. Returns false if email address does not contain
   these characters */

    for (i = 0; i < strUser.length; i++)
    {        
        if ((strUser.charCodeAt(i) > 122) || (strUser.charCodeAt(i) < 45) ||
            ((strUser.charCodeAt(i) > 57) && (strUser.charCodeAt(i) < 65)) || 
            ((strUser.charCodeAt(i) > 90) && (strUser.charCodeAt(i) < 95)) ||
            (strUser.charCodeAt(i) == 47) || (strUser.charCodeAt(i) == 96))        
        {
             intCharCount = intCharCount + 1;
        }     
    }

    if (intCharCount > 0)
    {
        return false;
    }

    intCharCount = 0;

    for (i = 0; i < strDomain.length; i++)
    {        
        if ((strUser.charCodeAt(i) > 122) || (strUser.charCodeAt(i) < 45) ||
            ((strUser.charCodeAt(i) > 57) && (strUser.charCodeAt(i) < 65)) || 
            ((strUser.charCodeAt(i) > 90) && (strUser.charCodeAt(i) < 95)) ||
            (strUser.charCodeAt(i) == 47) || (strUser.charCodeAt(i) == 96))        
        {
             intCharCount = intCharCount + 1;
        }
    }

    if (intCharCount > 0)
    {
        return false;
    }

/* Performs matching on domains. Returns false if
   a match is not found */
/*
    if (strDomain.match(strDomainPat) == null)
    {
        return false;
    }
*/
/* Performs matching on users. Returns false if a 
   match is not found */

    if (strUser.match(strUserPat) == null)
    {
        return false;
    }

    arrSplitString = strDomain.split(".")
    
    if (arrSplitString[0] == "")
    {
        return false;
    }

//  Everything checks out, returns true.
    return true;
}


/*
***************************************************************
Author          : ANGIE GOH
Creation Date   : FEB 25, 2002
Description     : Check if input is a valid email address
Input           : Form Field Value
Output          : True or False
***************************************************************
*/

function isValidEmail(argStr)
{

/* Checks to see the form field value is a space, or is blank, or it does not 
   conform to the specified domains or email adddress structure. If it is a 
   space, or is blank, or it does not conform to the specified domains or email 
   adddress structure, returns false. Otherwise returns true. */

   if ((isWhiteSpace(argStr)) || (isBlank(argStr)) || (!(chkValidEmail(argStr))))
   {
      return false;
   }   

    return true;
}


/*
***************************************************************
Author          : ANGIE GOH
Creation Date   : FEB 22, 2002
Description     : Checks to see if at least one checkbox is checked
Input           : Form Name
Output          : True or False
Changes         :
Mar 20, 2002    : Added another argument to cater to checking if
Angie Goh         at least one radio button is checked
***************************************************************
*/

function isChecked(argFormName, argType)
{
//  This variable stores the total number of checkboxes checked

    var intNumChecked;

    var intCounter;

// Initialse the variable to 0

    intNumChecked = 0;


/* Loop until the end of the form. If the checkbox is checked, add one 
   to the variable. Returns true if there is a least one checkbox checked.
   Otherwise returns false. */

    for (intCounter = 0; intCounter < argFormName.length; intCounter++)
        if ((argFormName.elements[intCounter].type == argType) && 
            (argFormName.elements[intCounter].checked))
        {
            intNumChecked = intNumChecked + 1;         
        }

    if (intNumChecked > 0)
    {
        return true;
    }
  
    else
    {
        return false;
    }
}


/*
***************************************************************
Author          : ANGIE GOH
Creation Date   : MAR 14, 2002
Description     : Checks/Unchecks all checkboxes in the form
Input           : Form Name and a checkbox state
Output          : Checked/Uncheck All Checkboxes
***************************************************************
*/

function setCheckboxState(argFormName, argState)
{
    var inti;

/* Loop until the end of the form. If the element in the form is 
   a checkbox, then check or uncheck the checkbox depending on 
   the valud of argState. If argState is 1, then check the checkbox.
   If argState is 0, then uncheck the checkbox. */

    for (inti = 0; inti < argFormName.length; inti++)
    {
        if (argFormName.elements[inti].type == "checkbox")
        {
            argFormName.elements[inti].checked = argState;
        }
    }
}


/*
***************************************************************
Author          : ANGIE GOH
Creation Date   : MAR 19, 2002
Description     : Checks if an option in list box is selected
Input           : Form Name Element
Output          : True or False

Changes         :
Mar 22, 2002    : Added another argument to cater to checking if
Angie Goh         at an option in drop down list box is selected
***************************************************************
*/

function isListOptionSelected(argFormElement, argType)
{
/*  Returns true is an option in a drop-down list box or a list box is 
    not selected. Otherwise returns false. If the form element is a 
    drop-down list box and there is no option selected, the index is 0. 
    If the form element if a list box and there is no option selected, 
    the index is -1  */

    if (((argType == "dropdown") && (argFormElement.selectedIndex == 0)) || 
        ((argType == "listbox") && (argFormElement.selectedIndex == -1)))
    {
        return true;
    }

    else
    {
        return false;
    }
}


/*
***************************************************************
Author          : ANGIE GOH
Creation Date   : MAR 25, 2002
Description     : Checks if input is a valid currency format.
Input           : Form Field Value
Output          : True or False
***************************************************************
*/

function isCurrency(argCurrency)
{
//  This variable is used to contain the split elements of the input value 
    var lngCurrency;  

//  These variables are integar counters
    var inticount, intNumCount, intSearchResult;

//  This variable is to stored the search pattern for ','
    var strSearchExp;

//  Initialise variables
    intNumCount = 0;
    strSearchExp = /,/gi

//  Perform searching
    intSearchResult = argCurrency.search(strSearchExp)

//  If a pattern match is count, then split the input value into an array
    if (intSearchResult > 0)
    {
        lngCurrency = argCurrency.split(",");
    }

//  Otherwise, input value becomes an element in an array
    else
    {
        lngCurrency = Array(argCurrency)
    }

/*  Loop until the end of the array. If the element of the array is either 
    not numeric or is a negative numerial, add one to a variable. */ 

    for (inticount = 0; inticount < lngCurrency.length; inticount++)
    { 
        if ((!(isDigit(lngCurrency[inticount]))) || (lngCurrency[inticount] < 0))
        {
            intNumCount = intNumCount + 1;
        }

    }

//  If the variable is greater than zero, returns false. Otherwise returns true. 

    if (intNumCount > 0)
    {
        return false;
    }

    else 
    {
        return true;
    }       
}


/*
***************************************************************
Author          : ANGIE GOH
Creation Date   : APR 5, 2002
Description     : Checks if input is a valid file name.
Input           : Form Field Value
Output          : True or False

Changes         : Rewrite to a more comprehesive check
Angie Goh
Sep 30, 2003
***************************************************************
*/

function isValidFileName(argFileName)
{
  var strToMatch;

  strToMatch = argFileName.replace(/^http:\/\//i, "");
  strToMatch = strToMatch.replace(/^\w:\\/i, "");
  strToMatch = strToMatch.replace(/\\/g, "/");

  if ((strToMatch.match(/^[\-\w/. ?%=&]+$/) != null) &&
      (strToMatch.match(/\.\/|\/\.|^\.|\.$|\/ | \//) == null) &&
      (strToMatch.charAt(strToMatch.length - 1) != '/') &&
      ((strToMatch.match(/\w+\.\w{3}$/) != null) ||
       (strToMatch.match(/\w+\.\w{3}\?[\w=%&]*$/) != null)))
  {
    return true;
  }
  else
  {
    return false;
  }
}
/*
***************************************************************
Author          : ANGIE GOH
Creation Date   : AUG 5, 2002
Description     : Checks if input conforms to password standard 
                  of minimum 6 characters and not blank or whitespace.
Input           : Form Field Value
Output          : True or False
***************************************************************
*/


function isValidPassword(argStr)
{

//  Check if it is blank or whitespace. returns false if it is blank or whitespace
    if ((isWhiteSpace(argStr)) || (isBlank(argStr)))

       {
         return false;
       }   

//  Check if it is less than 6 characters. returns false if it is less than 6 characters

    if (argStr.length < 6)
       {
         return false;
       }

    return true;
}


/*
***************************************************************
Author          : ANGIE GOH
Creation Date   : JAN 20, 2003
Description     : Checks for the summation of values is equal to 100
Input           : Form Field Values
Output          : True or False
***************************************************************
*/


function checkSum(argFormName,argTxtBoxName,argTextBoxNo)
{
    var strFormEleName;
    var inti, intTot;
    var arrSum;
    arrSum = new Array(eval(parseInt(argTextBoxNo)));
    strFormEleName = ""
    intTot = 0
 
    for (inti = 0; inti < eval(parseInt(argTextBoxNo)); inti++)
    {
        strFormEleName = argFormName + "." + argTxtBoxName + inti + ".value";
        arrSum[inti] = eval(strFormEleName);
    }

    for (inti = 0; inti < eval(parseInt(argTextBoxNo)); inti++)
    {
        intTot = intTot + parseInt(arrSum[inti]);
    }


    if (parseInt(intTot) != 100)
    {
        return false;
    }

    else
    {
        return true;
    }
}


/*
***************************************************************
Author          : ANGIE GOH
Creation Date   : FEB 17, 2003
Description     : Checks if the number of characters in input is     
                  within range of the specified limited.
Input           : Form Field Name, Character Limit
Output          : If limit is exceeded concatenation of input                   
***************************************************************
*/


function HasExceedMaxCount(argStr, argInt) 
{ 
    if (argStr.value.length > parseInt(argInt) - 1)
    {
        alert("Field has exceeded the maximum length");
        argStr.value = argStr.value.substring(0, eval(parseInt(argInt) - 1));
    }
}


/*
***************************************************************
Author          : ANGIE GOH
Creation Date   : MAY 8, 2003
Description     : Checks if input from a HTML textarea contains carriage returns.
Input           : TextArea Field Value
Output          : True or False                   
***************************************************************
*/

function isAllCR(argStr)
{

  strCRPat = /^[\n\r ]*$/
  if (strCRPat.test(argStr))
  {
    return true;
  }
  else
  {
    return false;
  }
}

/*
***************************************************************
Author            : ANGIE GOH
Creation Date     : FEB 21, 2003
Description       : Uses NumberFormat150.js to format decimal places, pls 
                    include the NumberFormat150.js when using this function
Input             : Float
Output            : Float with argDec decimal places
***************************************************************
*/

function FormatDec(argPrice,argDec)
{
  var lngFormatPrice;

  var lngFormatPrice = new NumberFormat(argPrice);
  lngFormatPrice.setCommas(true);
  lngFormatPrice.setPlaces(argDec);
  lngFormatPrice.setCurrencyPrefix("");
  return lngFormatPrice.toFormatted();
}

/*
***************************************************************
Author            : Tan Su Sen
Creation Date     : Nov 19, 2004
Description       : Extract numbers and decimal points from string
Input             : Float
Output            : Float
***************************************************************
*/

function FormatDecWithoutCommas(argPrice,argDec)
{
  var lngFormatPrice;

  var lngFormatPrice = new NumberFormat(argPrice);
  lngFormatPrice.setCommas(false);
  lngFormatPrice.setPlaces(argDec);
  lngFormatPrice.setCurrencyPrefix("");
  return lngFormatPrice.toFormatted();
}

/*
***************************************************************
Author            : Duncan Crombie
Creation Date     : 1999
Description       : Checks input string contains invalid characters
                    Modified by Angie Goh to suit internal requirements
Input             : String
Output            : Boolean
***************************************************************
*/

function isAllRegChars(argFormEleVal, argPatNo)
{
    var blnparsed = true;
    var strvalidchars;

    switch (argPatNo)
    {
        case 1 :
            strvalidchars = "abcdefghijklmnopqrstuvwxyz0123456789.-_";
            break;
        case 2 :
            strvalidchars = "abcdefghijklmnopqrstuvwxyz0123456789";
            break;
        case 3 :
            strvalidchars = "abcdefghijklmnopqrstuvwxyz0123456789><=/ ";
            break;
    }

    for (var inticount=0; inticount < argFormEleVal.length; inticount++) 
    {
        var strletter = argFormEleVal.charAt(inticount).toLowerCase();
        if (strvalidchars.indexOf(strletter) != -1)
        continue;       
        blnparsed = false;
        break;
    }

  return blnparsed;
}

/*
***************************************************************
Author            : Jason Widjaja 
		    Modified from DHTML phone number validation script. Courtesy of 		    		    SmartWebby.com (http://www.smartwebby.com/dhtml/)
Creation Date     : 5 Jan 2006
Description       : Validates input for multiple telephone numbers
		    Allows for multiple numbers seperated by a slash and international numbers
                    E.g. 91234567 / 61231234
 		    E.g. +65 97654321
		    E.g. (1800-12345678)
Input             : String
Output            : Boolean
***************************************************************
*/

function isInteger(s)
{   var i;
    var digits = "0123456789";
    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++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function isPhone(strPhone)
{

// non-digit characters which are allowed in phone numbers
// brackets and pluses may be used in international phone numbers
// slashes are used to seperate phone numbers
var phoneNumberDelimiters = "()- +/";

// Minimum no of digits in a phone no.
var minDigitsInPhoneNumber = 8;

	s=stripCharsInBag(strPhone,phoneNumberDelimiters);
	return (isInteger(s) && s.length >= minDigitsInPhoneNumber);
}

/*
***************************************************************
Author            : Angie Goh
Creation Date     : 27 JUN 2006
Description       : Checks input string contains "                                    
Input             : String
Output            : Boolean
***************************************************************
*/

function HasInvalidCharacters(argStringVal)
{
    var intJCount;
    
    for (intJCount = 0; intJCount < argStringVal.length; intJCount++)
    {
        if (argStringVal.charCodeAt(intJCount) == 34)
        {
            alert("\" not allowed");
            return true;
            break;                                    
        }
    }
}

/*
***************************************************************
Author            : Angie Goh
Creation Date     : 11 JUL 2006
Description       : Unchecks all elements in a radio button array                                    
Input             : String, Integer
Output            : Nil
***************************************************************
*/

function fnUncheckRadio(argFormEleName, argNumEles)
{
    var intCounter;
    var strToEval
    
    for (intCounter = 0; intCounter < argNumEles; intCounter++) 
    {
        strToEval = argFormEleName + "[" + intCounter + "].checked"

        if (eval(strToEval))
        {
            eval(argFormEleName + "[" + intCounter + "].checked = false");       
        }    
    }
}
