// Global value to be set usually in the OnFocus event
var originalFieldValue

function setOriginalValue(field)
{
    originalFieldValue = field.value
    field.select()
}

function validateMe(field, type, length, precision, lowerLimit, upperLimit, inputRequired)
{
        var newValue = field.value
        var newLength = newValue.length
        var errorCode = false

        if(inputRequired == 0 && newLength == 0)
        {
                return
        }

        if (inputRequired == 1)
        {
          if (newLength == 0)
          {
            errorCode = true;
          }
          else
          {
      			if(doTrim(newValue) == "")
            {
              field.value = doTrim(originalFieldValue)
            }
            else
            {
              errorCode = false;
            }
          }
        }

        if (errorCode == false)
        {

        if(type == 'NONE')
        {

        }

        else if(type == 'NUM')
        {
                var newLength = newValue.length

                for(var i = 0; i != newLength; i++)
                {
                        aChar = newValue.substring(i,i+1)
                        if( ( aChar < "0" || aChar > "9") && ( aChar != "-" ) )
                        {
                                errorCode = true
                        }
                }

                if( (field.value < lowerLimit) || (field.value > upperLimit) )
                {
                        errorCode = true
                }

                if(errorCode == true)
                {
                        alert('This field requires a value in the range of ' + lowerLimit + ' to ' + upperLimit + '.\nPlease re-enter a value')
                        field.value = originalFieldValue;
                        field.focus()
                        field.select()
                }

        }

        // This uses javascripts date functions.  Works pretty good, but doesn't handle dates of the form mm.dd.yy (with periods) too well.
        else if(type == 'DATE')
        {
                if( isNaN(Date.parse(field.value)) )
                {
                        alert('This field requires a valid date.\nPlease re-enter a value')
                        field.value = originalFieldValue;
                        field.focus()
                        field.select()
                }
        }

        // Currency.  Precision is hard coded to 2, upper and lower limits are important
        else if(type == 'CURR')
        {
                decimalValid(field, type, 2, lowerLimit, upperLimit)
        }

        // Decimal.  Precision, as well as upper and lower limits are important
        else if(type == 'DEC')
        {
                decimalValid(field, type, precision, lowerLimit, upperLimit)
        }

        else if(type == 'ALPH')
        {
                var extraChars=". -,"
                var search

                if(newLength == 0)
                {
                        alert('This field requires a valid alphabetical string.\nPlease re-enter a value')
                        field.value = originalFieldValue
                        field.focus()
                        //field.select()
                }

                if(newLength > length)
                {
                        alert('This field supports a maximum length of '+length.toString()+'.\nPlease re-enter a value')
                        field.value = originalFieldValue
                        field.focus()
                        field.select()
                }


                for(var i = 0; i != newLength; i++)
                {
                        aChar = newValue.substring(i,i+1)
                        aChar = aChar.toUpperCase()
                        search = extraChars.indexOf(aChar)
                        if(search == -1 && (aChar < "A" || aChar > "Z") )
                        {
                                alert('This field requires a valid alphabetical string.\nPlease re-enter a value')
                                field.value = originalFieldValue
                                field.focus()
                                field.select()
                        }
                }
        }
        else if(type == 'STR')
        {
                var extraChars=". -,0123456789:?><!@#$%^&*()_+=|}{][/\'\""
                var search

                if(newLength == 0)
                {
                        alert('This field requires a valid alphanumeric string.\nPlease re-enter a value')
                        field.value = originalFieldValue
                        field.focus()
                        //field.select()
                }

                if(newLength > length)
                {
                        alert('This field supports a maximum length of '+length.toString()+'.\nPlease re-enter a value')
                        field.value = field.value.substring(0,length-1)
                        field.focus()
                        field.select()
                }

                for(var i = 0; i != newLength; i++)
                {
                        aChar = newValue.substring(i,i+1)
                        aChar = aChar.toUpperCase()
                        search = extraChars.indexOf(aChar)
                        if(search == -1 && (aChar < "A" || aChar > "Z") )
                        {
                                alert('This field requires a valid alphanumeric string.\nPlease re-enter a value')
                                field.value = originalFieldValue
                                field.focus()
                                field.select()
                        }
                }
        }
        else if (type == 'TIME')
        {
                var status1 = true
                status1 = pictureValid(field, "##:##:##")
                if(status1 == false )
                {
                    alert('This field requires a valid Time ##:##:## .\nPlease re-enter a value')
                    field.value = originalFieldValue
                    field.focus()
                    field.select()
                }
        }
        else if(type == 'ZIP')
        {
                var status1 = true
                var status2 = true

                status1 = pictureValid(field, "#####")
                if(status1 == false)
                {
                        status2 = pictureValid(field, "#####-####")
                }

                if(status1 == false && status2 == false)
                {
                                alert('This field requires a valid ZIP code of the form ##### or #####-####.\nPlease re-enter a value')
                                field.value = originalFieldValue
                                field.focus()
                                field.select()
                }
        }
        else if(type == 'PHONE')
        {
                var failed = true
                var fieldtemp
                var switchme = field.value

                if(switchme.length == 7)
                {
                    if(pictureValid(field, "#######") == true)
                    {
                      fieldtemp = switchme.substring(0,3) + '-' + switchme.substring(3, switchme.length)
                      field.value = fieldtemp
		      failed = false;
                    }
                }
                else if(switchme.length == 8)
                {
                   if(pictureValid(field, "###-####") == true)
                   {
		      failed = false;
                   }
                }
                else if(switchme.length == 10)
                {
                   if(pictureValid(field, "##########") == true)
                   {
                      fieldtemp = switchme.substring(0,3) + '-' +
                                  switchme.substring(3,6) + '-' +
                                  switchme.substring(6, switchme.length);
                      field.value = fieldtemp
		      failed = false;
                   }
                }
                else if(switchme.length == 12)
                {
                   if(pictureValid(field, "###-###-####") == true)
                   {
		      failed = false;
                   }
		}

                if(failed == true)
                {
                        alert('This field requires a valid phone number of the form ###-####, #######, ###-###-#### or ##########.\nPlease re-enter a value'+status+switchme+switchme.length)
                        field.value = originalFieldValue
                        field.focus()
                        field.select()
                }

        }
        else if(type == 'SSN')
        {
                var status1 = true
                var status2 = true
                var fieldtemp

                status1 = pictureValid(field, "###-##-####")
                if(status1 == false)
                {
                        status2 = pictureValid(field, "#########")
                        if(status2 == true)
                        {
                               fieldtemp = field.value.substring(0,3) + '-' + field.value.substring(3, 5) + '-' +  field.value.substring(5,9)
                               field.value = fieldtemp
                        }

                }

                if(status1 == false && status2 == false)
                {
                        alert('This field requires a valid Social Security number of the form ###-##-#### or #########.\nPlease re-enter a value')
                        field.value = originalFieldValue
                        field.focus()
                        field.select()
                }

        }
        else if(type == 'EMAIL')
        {
                var errorCode = false
                if (newLength > 5)
                {
                        var linSumOfx = 0;
                        var linSumOfy = 0

                        for (j=0; j < newLength; j++)
                        {
                                Ch = newValue.charAt(j);

                                if (ReplaceWildChar("@-_",Ch) == true)
                                {
                                        errorCode = true;
                                }

                                if (Ch == "@")
                                {
                                        //check posisi . (error : xxx@.com)
                                        if (linSumOfy > 0)
                                        {
                                                linSumOfy = 0;
                                        }

                                        if ( newValue.substring(j,(j+2)) == "@.")
                                        {

                                                errorCode = true;
												break;
                                        }
                                        linSumOfx++;
                                }
                                else if (Ch == ".")
                                {
                                        linSumOfy++;
                                }
                        }

                        if (errorCode == true)
                        {
                                alert( "This MUST be a Correctly Formatted E-Mail Address\n.Please re-enter a value" );
                                field.value = originalFieldValue
                                field.focus()
                                field.select()
                        }
                        else if ((linSumOfx > 1) || (linSumOfx < 1))
                        {
                                alert( "There can be only 1 '@' symbol!" );
                                field.value = originalFieldValue
                                field.focus()
                                field.select()
                        }
                        else if (linSumOfy < 1)
                        {
                                alert( "There MUST be at least 1 '.' following the '@' symbol!" );
                                field.value = originalFieldValue
                                field.focus()
                                field.select()
                        }
                }
                else
                {
                        alert( "An E-Mail Address MUST be Greater than 5 characters." );
                        field.value = originalFieldValue
                        field.focus()
                        field.select()
                }
        }
        else if(type == 'URL')
        {
                var errorCode = false
                //set begin of URL : http://www.

                if (newValue.substring(0,11) == "http://www.")
                {
                        var lstrURL = "";
                        var status = "0";
                }
                else if (newValue.substring(0,4) == "www.")
                {
                        var lstrURL = "http://";
                        var status = "1";
                }
                else
                {
                        var lstrURL = "http://www.";
			var status = "3";
                }

                var linSumOfDot = 0;
                var linSumOfDotBeforeSlash = 0;
                var linSumOfSlash = 0;
                var linSumOfDot2 = 0;
                var linSumOfSlash2 = 0;

                for (j=0; j < newLength; j++)
                {
                        Ch = newValue.charAt(j);

                        if (ReplaceWildChar("-_:/",Ch) == true)
                        {
                                field.value = "";
                                field.focus();
                                field.select();
                        }

/* Check if user input http://www.bali.com/ ---> substring(0,11)
   Check if user input www.bali.com ---> substring(0,4)
   syntax URL : Domain_Name/Dir/subDir/
*/

                        if ((lstrURL == "http://www.") || (lstrURL == "http://"))
                        {
                                if ((Ch == ":") || (newValue.substring(j,j+1) == "//"))
                                {
                                        errorCode = true;
                                        field.value = "";
                                        field.focus();
                                        field.select();
                                }
                                if (Ch == ".")
                                {
                                        linSumOfDot++;
                                }

                                if (Ch == "/")
                                {
                                        linSumOfSlash++;
                                        if (lstrURL == "http://www.")
                                        {
                                                if (linSumOfDot < 1)
                                                {
                                                        errorCode = true;
                                                }
                                        }
                                        else
                                        {
                                                if (linSumOfDot < 2)
                                                {
                                                        errorCode = true;
                                                }
                                        }

                                        if (linSumOfSlash == 1)
                                        {
                                                linSumOfDotBeforeSlash = linSumOfDot;
                                        }
                                }
                        }

                        if (lstrURL == "")
                        {
                                if (Ch == ":")
                                {
                                        linSumOfDot2++;
                                }

                                if ((Ch == ":") && (linSumOfDot2 > 1))
                                {
                                        errorCode = true;
                                }

                                if ((newValue.substring(j,j+1) == "//") && (linSumOfSlash2 > 1))
                                {
                                        errorCode = true
                                }
                                else
                                {
                                        linSumOfSlash2++;
                                }

                                if (Ch == ".")
                                {
                                        linSumOfDot++;
                                }

                                if ((Ch == "/") && (linSumOfSlash2 == 1))
                                {
                                        if ((linSumOfDot < 2) && (linSumOfSlash == 0))
                                        {
                                                errorCode = true;
                                        }
                                        else
                                        {
                                                linSumOfSlash++;
                                                if (linSumOfSlash == 1)
                                                {
                                                        linSumOfDotBeforeSlash = linSumOfDot ;
                                                }
                                        }
                                }
                        }
                }
                // end of For statement

                if (linSumOfSlash == 0)
                {
                        linSumOfDotBeforeSlash = linSumOfDot ;
                }

                if ((status <= "1"))
                {
                        if (linSumOfDotBeforeSlash < 2)
                        {
                                errorCode = true;
                        }
                }
                else
                {
                        if (linSumOfDotBeforeSlash < 1)
                        {
                                errorCode = true;
                        }
                }

                if (errorCode == true)
                {
                        alert('This field requires a valid syntax URL of the form .\nwww.DomainName/  http://www.DomainName/  DomainName/ . \nPlease re-enter a value');
                        field.value = originalFieldValue
                        field.focus()
                        field.select()
                }
                else
                {
                        field.value = lstrURL + newValue;
                }
        }
        else if(type == 'PERCENT')
        {
                var lstrCheckOK = "1234567890.%";
                var errorCode = false
                gstrNewStr = "";
                lblPct = false;

                if((field.value < lowerLimit) || (field.value > upperLimit))
                {
                        alert('This field requires a value in the range of ' + lowerLimit + ' to ' + upperLimit + '.\nPlease re-enter a value')
                        errorCode = true;
                        field.value = originalFieldValue
                        field.focus()
                        field.select()
                }

                CheckNumeric(newValue,"%.");
                if (allValid)
                {
                        decimalValid(field, type, 3, lowerLimit, upperLimit)
                        newValue = field.value;

                        for (j=0; j < newValue.length ; j++)
                        {
                                lstrCh = newValue.charAt(j);
                                for (k=0; k < lstrCheckOK.length ; k++)
                                {
                                        if ((lstrCh == lstrCheckOK.charAt(k)) && (!lblPct))
                                        {
                                                if (lstrCh == ".")
                                                {
                                                        //gstrNewStr = parseInt(gstrNewStr);
                                                        //lblDec = true;
                                                        gstrNewStr += lstrCh;
                                                }
                                                else if (lstrCh == "%")
                                                {
                                                        lblPct = true;
                                                        gstrNewStr == gstrNewStr;
                                                }
                                                else
                                                {
                                                        gstrNewStr += lstrCh;
                                                }
                                        }
                                        else
                                        {
                                                k == lstrCheckOK.length;
                                        }
                                }
                        }
                }

//              gstrNewStr = parseFloat(gstrNewStr);
                if (gstrNewStr >= 0)
                {
                        field.value = gstrNewStr;
                }
                else
                {
                        errorCode = true;
                        field.value = originalFieldValue
                        field.focus()
                        field.select()
                }
        } //End Code of type == 'PERCENT'
        else if (type == 'DOLLAR')
        {
                var lstrcheckOK = "0123456789.";
                var gstrNewStr = "";
                var errorCode = false

                if((field.value < lowerLimit) || (field.value > upperLimit))
                {
                        alert('This field requires a value in the range of ' + lowerLimit + ' to ' + upperLimit + '.\nPlease re-enter a value')
                        errorCode = true;
                        field.value = originalFieldValue
                        field.focus()
                        field.select()
                }

                CheckNumeric(newValue,"$,.");
                if (allValid)
                {
                        for (j=0; j < newValue.length ; j++)
                        {
                                lstrCh = newValue.charAt(j);
                                for (k=0; k < lstrcheckOK.length ; k++)
                                {
                                        if (lstrCh == lstrcheckOK.charAt(k))
                                        {
                                                gstrNewStr = gstrNewStr + lstrCh;
                                        }
                                }
                        }
                }
                gstrNewStr = parseFloat(gstrNewStr);
                if (gstrNewStr >=0)
                {
                        field.value = gstrNewStr;
                }
                else
                {
                        errorCode = true;
                        field.value = originalFieldValue
                        field.focus()
                        field.select()
                }
        } // End Code of type == 'DOLLAR'

        } // End Code Error Code == false
}


function decimalValid(field, type, precision, lowerLimit, upperLimit)
{
        var errorCode = false
        var newValue = field.value

        var decAmount = ""
        var dolAmount = ""
        var decFlag = false
        var aChar = ""
        var totalValue = 0
        var decLen = 0

        // ignore all but digits and decimal points.
        for(i=0; i < newValue.length; i++)
        {
                aChar = newValue.substring(i,i+1)
                if(aChar >= "0" && aChar <= "9")
                {
                        if(decFlag)
                        {
                                decAmount = "" + decAmount + aChar
                        }
                        else
                        {
                                dolAmount = "" + dolAmount + aChar
                        }
                }
                else if(aChar == ".")
                {
                        if(decFlag)
                        {
                                dolAmount = ""
                                errorCode = true
                                break
                        }
                        decFlag=true
                }
                else if( aChar == "-" )
                {
                        if( dolAmount != "" )
                        {
                                errorCode = true
                                break
                        }
                }
				else if( aChar == "," )
				{
					continue
				}
                else
                {
                        errorCode = true
                        break
                }
        }

        // Ensure that at least a zero appears for the dollar amount.
        if(dolAmount == "")
        {
                dolAmount = "0"
        }
        // Strip leading zeros.
        if(dolAmount.length > 1)
        {
                while(dolAmount.length > 1 && dolAmount.substring(0,1) == "0")
                {
                        dolAmount = dolAmount.substring(1,dolAmount.length)
                }
        }

        // Round the decimal amount.
        if(decAmount.length > precision)
        {
                if(decAmount.substring(precision,precision+1) > "4")
                {
                        var decAmount2 = parseInt(decAmount.substring(0,precision)) + 1

                        if(decAmount2 < Math.pow(10, precision-1))
                        {
                                decLen = precision - decAmount2.toString(10).length
                                for(var j=0; j< decLen; ++j)
                                {
                                        decAmount2 = "0" + decAmount2
                                }
                        }
                        else
                        {
                                decAmount2 = "" + decAmount2
                        }

                        decAmount = decAmount2
                }
                else
                {
                        decAmount = decAmount.substring(0,precision)
                }
                if (decAmount == Math.pow(10,precision))
                {
                        decAmount = ""
                        for(var j=0; j<= precision; ++j)
                        {
                                decAmount = "0" + decAmount
                        }

                        dolAmount = parseInt(dolAmount) + 1
                }
        }

        // Pad right side of decAmount
        if(decAmount.length < precision)
        {
                decLen = precision-decAmount.length
                for(var j=0; j< decLen; ++j)
                {
                        decAmount = decAmount + "0"
                }
        }

        //if the precision = 0, drop the decimal point
        if (precision == 0) {
                totalValue =  dolAmount
        }
        else {
                totalValue = dolAmount + "." + decAmount
        }

        if( (parseFloat(totalValue) < lowerLimit) || (parseFloat(totalValue) > upperLimit) )
        {
                errorCode = true
        }

        if(errorCode == true)
        {
                if(type == 'CURR')
                {
                        alert('This field requires a valid currency amount in the range of ' + lowerLimit + ' to ' + upperLimit + '.\nPlease re-enter a value')
                }
                else
                {
                        alert('This field requires a valid decimal amount in the range of ' + lowerLimit + ' to ' + upperLimit + '.\nPlease re-enter a value')
                }
                field.value = originalFieldValue
                field.focus()
                field.select()
        }
        else
        {
                // Check for negative values and reset textObj
                if(newValue.substring(0,1) != '-' || (dolAmount == "0" && decAmount == "00"))
                {
                        field.value = totalValue
                }
                else
                {
                        field.value = '-' + totalValue
                }
        }
}

//  PictureValid will validate against a format mask, such as (###) ###-####
// The following are valid values
// @ - Any character allowed by an HTML text element
// ? - Any Letter
// # - Any Number
// $ - Money Characters. 0 through 9, minus sign (-), plus sign (+), and decimal point (.)
// [] - Specifies custom data set to use for the character, such as [2345] would allow 2, 3, 4, or 5
// * - any number of the character that follows it.  For example, using an asterisk followed by a ?
//     would allow any number of letters to be entered.

// Globals used by pictureValid
var DIGITS = "0123456789"
var UPPERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var LOWERS = "abcdefghijklmnopqrstuvwxyz"

function pictureValid(field, picture)
{
        var status = true
        var isRepeat = false
        var pLen = picture.length
        var search = 0
        var validData = ""
        var picChar = ""
        var aChar = ""
        var newValue = field.value
        var tLen = newValue.length
        var detailError = ""

        for(var i = 0, j = 0; (i != newValue.length)&& (j != picture.length)&& (status==true); i++)
        {
                picChar=picture.substring(j,j+1)
                if(picChar == "[")
                {
                        validData = ""
                        j++
                        for(; j != picture.length; j++)
                        {
                                if(picture.substring(j,j+1) == "]")
                                {
                                        break
                                }
                                validData = validData + picture.substring(j,j+1)
                        }
                }
                else if(picChar =="@")  // Any character
                {
                        j++
                        continue
                }
                else if(picChar == "?")   // Any letter
                {
                        validData = UPPERS + LOWERS
                }
                else if(picChar == "#")      // Any number
                {
                        validData = DIGITS
                }
                else if(picChar =="$")       // Money characters
                {
                        validData = DIGITS + "." + "-" + "+"
                }
                else if(picChar == "*")
                {
                        isRepeat = true
                        j++
                        i--
                        continue
                }

                else
                {
                        validData = picChar
                }

                aChar = newValue.substring(i,i+1)
                search = validData.indexOf(aChar)

                if(search == -1)
                {
                        if(isRepeat)
                        {
                                isRepeat = false
                                j++
                                i--
                                continue
                        }
                        status = false
                        if(aChar == " ")
                        {
                                detailError = "A space is not allowed in position #"+(i+1)+". "
                        }
                        else
                        {
                                detailError = "The character, " + aChar + ", is not allowed in position #"+(i+1)+". "
                        }
                }
                else
                {
                        if(!isRepeat)
                        {
                                j++
                        }
                }
       }

        //Check length
         if(status == true && (j < picture.length || i < newValue.length))
        {
                status = false
                detailError = "incorrect length"
        }

 //       if(detailError != "")
 //       {
 //               alert(detailError+'\nPlease re-enter a value')
 //               field.value = originalFieldValue
 //               field.focus()
 //               field.select()
 //       }

       return(status)
}

//Function strToCurr()
//Author: Greg Burgess
//Purpose: This function takes one parameter (a string representing a currency amount) which it validates
//formats and returns.
//
//Example strToCurr("12.5")   --> 12.50
//	  strToCurr("12")      --> 12.00
//	  strToCurr("12.59") --> 12.60

function strToCurr(newValue) {
        var errorCode = false
        var decAmount = ""
        var dolAmount = ""
        var decFlag = false
        var aChar = ""
        var totalValue = 0
        var decLen = 0

        // ignore all but digits and decimal points.
        for(i=0; i < newValue.length; i++)
        {
                aChar = newValue.substring(i,i+1)
                if(aChar >= "0" && aChar <= "9")
                {
                        if(decFlag)
                        {
                                decAmount = "" + decAmount + aChar
                        }
                        else
                        {
                                dolAmount = "" + dolAmount + aChar
                        }
                }
                else if(aChar == ".")
                {
                        if(decFlag)
                        {
                                dolAmount = ""
                                errorCode = true
                                break
                        }
                        decFlag=true
                }
                else
                {
                        errorCode = true
                        break
                }
        }
        // Ensure that at least a zero appears for the dollar amount.
        if(dolAmount == "")
        {
                dolAmount = "0"
        }
        // Strip leading zeros.
        if(dolAmount.length > 1)
        {
                while(dolAmount.length > 1 && dolAmount.substring(0,1) == "0")
                {
                        dolAmount = dolAmount.substring(1,dolAmount.length)
                }
        }

        // Round the decimal amount.
        precision = 2;
		if( strToCurr.arguments.length > 1 )
			precision = strToCurr.arguments[1];
        if(decAmount.length > precision)
        {
                if(decAmount.substring(precision,precision+1) > "4")
                {
                        var decAmount2 = parseInt(decAmount.substring(0,precision)) + 1

                        if(decAmount2 < Math.pow(10, precision-1))
                        {
                                decLen = precision - decAmount2.toString(10).length
                                for(var j=0; j< decLen; ++j)
                                {
                                        decAmount2 = "0" + decAmount2
                                }
                        }
                        else
                        {
                                decAmount2 = "" + decAmount2
                        }

                        decAmount = decAmount2
                }
                else
                {
                        decAmount = decAmount.substring(0,precision)
                }
                if (decAmount == Math.pow(10,precision))
                {
                        decAmount = ""
                        for(var j=0; j<= precision; ++j)
                        {
                                decAmount = "0" + decAmount
                        }

                        dolAmount = parseInt(dolAmount) + 1
                }
        }
        // Pad right side of decAmount
        if(decAmount.length < precision)
        {
                decLen = precision-decAmount.length
                for(var j=0; j< decLen; ++j)
                {
                        decAmount = decAmount + "0"
                }
        }

         totalValue = dolAmount + "." + decAmount
        if(errorCode == true)
        {
                alert('This field requires a valid currency amount.')
	return 0
        }
        else
        {
	return totalValue
        }
}

function sumValues( list, cnt ) {
	var totVal = 0;
	var precision = 2;
	if( sumValues.arguments.length > 2 )
		precision = sumValues.arguments[2];

	var mult = Math.pow( 10, precision );
	for( var x = 0; x < cnt; x++ )
		totVal += Math.round( (list[x] * mult) );

	return( strToCurr( ("" + (totVal / mult)), precision ) );
}

function sumFieldValues( fields, cnt ) {		// this will assume a precision of 2, but will accept an optional precision argument
	var precision = 2;
	if( sumFieldValues.arguments.length > 2 )
		precision = sumFieldValues.arguments[2];

	var values = new Array( cnt );
	for( var x = 0; x < cnt; x++ )
		values[x] = fields[x].value;
	return( sumValues( values, cnt, precision ) );
}

function validateR50( pwd ) {           // second argument optionally a Boolean true or false to allow spaces

	var rtnPwd = pwd.value.toUpperCase();
	var valid = " .'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ#";
	var i, c, pos = 1;
	if( validateR50.arguments.length > 1 ) {
		var allowSpace = new Boolean( validateR50.arguments[1] );
		if( allowSpace == true )
			pos = 0;
	}
	/* space is invalid - if pos == 1 */
	for( i = 0; i < rtnPwd.length; i++ ) {
		if( valid.indexOf( rtnPwd.charAt( i ) ) < pos ) {
			alert( "Field Contains Invalid Characters!" );
			pwd.focus();
			pwd.select();
			return( false );
		}
	}
	pwd.value = rtnPwd;
	return( true );
}


function pwCrypt( origStr, edFlag ) {  //edFlag: 0 = Encrypt, 1 = Decrypt
	var DCRPTSTR = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
	var ECRPTSTR = "~{[}u;Ce83KX%:VIm!|gs]_aL-QEOpx<UlzZjBq6#1($\\\"FS5H0'cM&>Po.NGA*Jr)Y Dv/t9kd?^fni,hR2Wy=`+4T@7wb"
	var uepwd = "" + origStr;
    var l_DecryptPass = "";
    var l_Work = "";
    var l_Length = 0, l_Position = 0, l_Multiplier = 0, l_Offset = 0, l_Count = 0;

    l_Length = uepwd.length;

    if( (l_Length >= 1) && (l_Length <= 3) )
        l_Multiplier = 1;
    else if( (l_Length >= 4) && (l_Length <= 6) )
        l_Multiplier = 2;
    else if( (l_Length >= 7) && (l_Length <= 9) )
        l_Multiplier = 3;
    else
        l_Multiplier = 4;

    for( l_Count = 1; l_Count <= l_Length; l_Count++ ) {
        l_Offset = (l_Count * l_Multiplier) * ((edFlag) ? 1 : -1);
        l_Work = uepwd.charAt( l_Count - 1 );
		if( edFlag == 0 )
			l_Position = DCRPTSTR.indexOf( l_Work ) + 1;
		else
			l_Position = ECRPTSTR.indexOf( l_Work ) + 1;
        l_Position = l_Position - l_Offset;
        if( edFlag == 0 ) {
            l_Position %= 95;
            l_Position++;
        }
        else {
            l_Position--;
            while( l_Position <= 0 )
                l_Position += 95;
        }
        l_DecryptPass[l_Count - 1] = (edFlag == 1) ?
                DCRPTSTR[l_Position - 1] : ECRPTSTR[l_Position - 1];
        if ( (l_Multiplier >= 1) && (l_Multiplier <= 3) )
            l_Multiplier++;
        else
            l_Multiplier = 1;
    }
    return( l_DecryptPass );
}

/***************************************************************************************
 * Encryption algorithm developed by: Curinir / ZErtA
 * EMAIL - curinir@zerta.org	Atridox encryption algorithm
 * 	MODIFIED to use milliseconds instead of Math.random() for consistency between browsers
 * *************************************************************************************/

function NewpwCrypt( origStr, edFlag ) {  /* edFlag: 0 = Encrypt, 1 = Decrypt */
	var numbers		= "0123456789";
	var lowerCase	= "abcdefghijklmnopqrstuvwxyz";
	var upperCase	= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var special		= " ,.:;!?/\\|@#$%^&*()[]{}<>+=-_«»\"<>";
	var special2	= "'";
	var special3	= "æøåÆØÅ";
	var charArray	= numbers + lowerCase + upperCase + special + special2 + special3;		// Put together main-string
	var charsLen	= charArray.length;
	var encodedStr	= "";
	var decodedStr	= "";
	var adder		= 0;

	if( edFlag == 0 ) {
		var strToEnc = "" + origStr;
		var today = new Date();
		var len = strToEnc.length;
		var o = 0;

		if( len < 1 )
			return( "" );
		adder = Math.round( (((today.getTime() % 999.0) / 999.0) * 89) + 10 );				// Create a random number
		for( var i = 0; i <= len; i++ ) {
			if( i >= len )
          		o = charsLen;
        	else
          		o = charArray.indexOf( strToEnc.charAt( i ) );
        	if( o <= charsLen && o >= 0 )
				encodedStr += 10000 + (adder * 2 * i) + (2 * charsLen * o) + ((i^2) + 1 * adder); // Do encrypting
		}
		return( encodedStr + adder );														// Add decrypting help from adder and return
	}
	else {
		var strToDec = "" + origStr;
		var chars = 0.0;
        var n = 0, p = 0, q = 0;

		if( strToDec.length < 12 )
			return( "" );
		adder = strToDec.substring( strToDec.length - 2, strToDec.length );					// Get adder
        strToDec = strToDec.substring( 0, strToDec.length - 2 );							// Fix value of strToDec
        chars = (strToDec.length / 5) - 1;													// Check number of chars in output string
        for( var i = 0; i < (chars * 5); i += 5 ) {											// Do for each four of the characters
			p = strToDec.substring( i, i + 5 ).valueOf();												// Get four-digit code of strToDec
            q = (p - 10000 - (adder * 2 * n) - ((n^2) + 1 * adder)) / (2 * charsLen);		// Do decrypting
            decodedStr += charArray.substring( q, q + 1 ); 									// Add decrypted part of string
            n++;																			// Get decodedStr.substring value
        }
        return( decodedStr );																// Return decoded string
	}
}
/***************************************************************************************/

/*
BaliCamp Code
Author : I Made Susantho BPK

Function name: CheckNumeric(fobjToBeCheck, fstrParam)
Objective: check numeric value of string or inputted data on a html tag/object
Input parameter:
	fobjToBeCheck : String to be checked
	fstrParam : Some of Wild Character such as "%".
Output parameter : return value of variable "allValid" ---> true/false
*/

function CheckNumeric(fobjToBeCheck, fstrParam)
{
  var lstrCheckOK = "0123456789 " + fstrParam;
  allValid = true;
  for (i = 0;  i < fobjToBeCheck.length; i++)
  {
    lstrCh = fobjToBeCheck.charAt(i);

    for (j = 0; j < lstrCheckOK.length; j++)
      if (lstrCh == lstrCheckOK.charAt(j))
        break;

    if (j == lstrCheckOK.length)
    {
      allValid = false;
      break;
    }
  }

  if (!allValid)
  {
    alert("Please enter only valid characters in the field.");
    return (false);
  }
  return (true);
}

/*
Function name: ReplaceWildChar(fstrExclude,fstrCh)
Objective: check wild characters
Input parameter:
	fstrexclude : String to be checked
	fstrCh : Some of Wild Character such as "%" to be eliminate from list wild characters.
Output parameter : return value of variable "status" ---> true/false
*/

function ReplaceWildChar(fstrExclude,fstrCh)
{
	var lstrWildChar = "~!#$%^&*()+={}[]',<>?@-_:/|\ ";
	var status = false;
	fstrExclude = lstrWildChar.replace(fstrExclude,"");
    for (y = 0; y < fstrExclude.length; y++)
    {
      if (fstrCh == fstrExclude.charAt(y))
        {
			status = true;
			return(status);
        }
	}
}

/*
Function name: validateForm(gstrInputName)
Objective: check blank input (only required)
Input parameter:
	gstrInputName : Passing input text object must be not blank !
Output parameter : return value true/false.
*/

  function doTrim(oldValue) {
    var count = oldValue.length;
    var newValue = "";
    for(i=0;i<count;i++){
      if(oldValue.charAt(i) != " "){
	     newValue = newValue + oldValue.substring(i, i+1);
      }
    }
    return(newValue);
  }

/*
Function name: validateForm(gstrInputName)
Objective: check blank input (only required)
Input parameter:
	gstrInputName : Passing input text object must be not blank !
Output parameter : return value true/false.
*/

function validateForm(gstrInputName)
{
	var TempObject = "";
	var TempObj = new Array();
	var TempObject_ = "";
	var SumOfObject = 0;

	for(i=0;i<gstrInputName.length;i++){
		TempObject_ = gstrInputName.charAt(i);
		if( TempObject_ == ","){
			TempObj[SumOfObject] = TempObject;
			TempObject = "";
			SumOfObject++;
		}
		else{
			TempObject = TempObject + TempObject_;
		}
	}
	for(k=0;k<=(SumOfObject-1);k++){
		Temp = TempObj[k];
			if(doTrim(document.forms[0].elements[Temp].value) == ""){
                                alert( 'Some Required Data is Missing.' )
				document.forms[0].elements[Temp].focus();
				document.forms[0].elements[Temp].select();
				k=(SumOfObject-1)
				return false;
			}
		}
}

/*
Function name: validateForm1(gstrInputName,IndexForm)
Objective: check blank input (only required) which use more than one FORM.
Input parameter:
	gstrInputName : Passing input text object must be not blank !
	IndexForm : number Form started from 0, counted form Top of HTML Page.
Output parameter : return value true/false.
*/

function validateForm1(gstrInputName,IndexForm)
{
	var TempObject = "";
	var TempObj = new Array();
	var TempObject_ = "";
	var SumOfObject = 0;

	for(i=0;i<gstrInputName.length;i++){
		TempObject_ = gstrInputName.charAt(i);
		if( TempObject_ == ","){
			TempObj[SumOfObject] = TempObject;
			TempObject = "";
			SumOfObject++;
		}
		else{
			TempObject = TempObject + TempObject_;
		}
	}
	for(k=0;k<=(SumOfObject-1);k++){
		Temp = TempObj[k];
			if(doTrim(document.forms[IndexForm].elements[Temp].value) == ""){
                                alert('Some required fields are missing.')
				document.forms[IndexForm].elements[Temp].focus();
				document.forms[IndexForm].elements[Temp].select();
				k=(SumOfObject-1)
				return false;
			}
		}
}

/*
Function name: validateSE(gstrInputName,IndexForm)
Objective: Check Start Date and End Date.
Input parameter:
	gstrInputName : Passing input text object must be not blank !
	IndexForm : number Form started from 0, counted form Top of HTML Page.
Output parameter : return value true/false.
*/

function validateSE(gstrInputName,IndexForm){
	var TempObject = "";
	var TempObj = new Array();
	var TempObject_ = "";
	var SumOfObject = 0;

        for(i=0;i<gstrInputName.length;i++){
		TempObject_ = gstrInputName.charAt(i);
		if( TempObject_ == ","){
			TempObj[SumOfObject] = TempObject;
			TempObject = "";
			SumOfObject++;
		}
		else{
			TempObject = TempObject + TempObject_;
		}
	}
		Temp = TempObj[0];
		var StartDate = parseDate(document.forms[IndexForm].elements[Temp].value);
		Temp = TempObj[1];
		var EndDate = parseDate(document.forms[IndexForm].elements[Temp].value);

		if (Date.parse(StartDate) > Date.parse(EndDate)){
			alert('End Date must be equal to or greater than Start Date')
			Temp = TempObj[0];
			document.forms[IndexForm].elements[Temp].focus();
			document.forms[IndexForm].elements[Temp].select();
			return false;
		}
}

function validateBDate(gstrInputName,IndexForm){
        var TempObject = "";
        var TempObj = new Array();
        var TempObject_ = "";
        var SumOfObject = 0;

        for(i=0;i<gstrInputName.length;i++){
                TempObject_ = gstrInputName.charAt(i);
                if( TempObject_ == ","){
                        TempObj[SumOfObject] = TempObject;
                        TempObject = "";
                        SumOfObject++;
                }
                else{
                        TempObject = TempObject + TempObject_;
                }
        }
        Temp = TempObj[0];
        var TBirthDate = parseDate(document.forms[IndexForm].elements[Temp].value);
        Temp = TempObj[1];
        var BToday = parseDate(document.forms[IndexForm].elements[Temp].value);

        if (Date.parse(TBirthDate) > Date.parse(BToday)){
                alert('Birthdate Cannot Be Greater Than Today!')
                Temp = TempObj[0];
                document.forms[IndexForm].elements[Temp].focus();
                document.forms[IndexForm].elements[Temp].select();
                return false;
        }
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/*
	End Of BaliCamp Code
*/

