/* *************************************************************
** FORMVAL.JS - JS Form Validation Library
** =======================================
** This library contains code to validate HTML form-field data.
** The bulk of this file was derived from Eric Krock's FormChek.js at
** developer.netscape.com/docs/examples/javascript/formval/overview.html
** (Many thanks, Eric!) Enjoy ... and please maintain this header.
**
** To load this library in an HTML doc, put the following
** line in the doc's HEAD (before any other SCRIPT tags):
**
** <SCRIPT SRC="formval.js" LANGUAGE="JavaScript"></SCRIPT>
**
************************************************************* */

/* *************************************************************
** USAGE
** =====
** Functions to Validata Form-Element Data:
**   isEmpty(s) - true if string s is empty
**   isBlank(s) - true if string s is empty or blank (all whitespace chars)
**   isLetter(c) - true if char c is an English letter 
**   isDigit(c) - true if char c is a digit 
**   isInteger(s) - true if string s is a signed/unsigned number
**   isIntegerInRange(s, a, b) - true if string s (integer) is a <= s <= b
**   isFloat(s) - true if string s is a signed/unsigned floating-point number
**   isNumeric(s) - true if s is numbers onlyisNumeric(s)
**   isAlphanumeric(s) - true if s is English letters and numbers only
**   isUSPhoneNumber(s) - true if string s is a valid U.S. phone number
**   isZIPCode(s) - true if string s is a valid U.S. ZIP code
**   isStateCode(s) - true if string s is a valid U.S. (2-letter) state code
**   isEmail(s) - true if string s is a valid email address
**   isEmailNew(s)- true if string s is a valid email address
**   getCheckedRadioButton(radioSet) - gets index checked radio button in set
**   getCheckedCheckboxes(checkboxSet) - gets index(es) of checked checkboxes in set
**   getCheckedSelectOptions(select) - gets index(es) of checked select options
**
** Functions to Reformat input=text Form-Field Data:
**   stripCharsInBag(s, bag) - removes all chars in string bag from string s
**   stripCharsNotInBag(s, bag) - removes all chars NOT in string bag from string s
**   stripBlanks(s) - removes all blank chars from s	
**   stripLeadingBlanks(s) - removes leading blank chars from s			//like ltrim(s)
**   stripTrailingBlanks(s) - removes trailing blank chars from s		//like rtrim(s)
**   stripLeadingTrailingBlanks(s) - removes lead+trail blank chars from s	//like trim(s)
**   Mid(string, start, length) - Returns a specified number of characters from a
**                            string
**   Right(string, length): Returns a specified number of characters from the
**                       right side of a string
**   Left(string, length): Returns a specified number of characters from the
**                      left side of a string

** Functions to format string
**   reformatString(targetStr, str1, int1 [, str2, int2 [, ..., ...]]) - 
**    			inserts formatting chars or delimiters in targetStr (see below)
**  FormatCurrency(Expression, NumDigitsAfterDecimal, IncludeLeadingDigit,
**               	UseParensForNegativeNumbers, GroupDigits)
**  FormatNumber(Expression, NumDigitsAfterDecimal, IncludeLeadingDigit,
**             		UseParensForNegativeNumbers, GroupDigits)
**  FormatDateTime(datetime, FormatType) : Returns an expression formatted
**                       as a date or time
**  FormatPercent(Expression, NumDigitsAfterDecimal, IncludeLeadingDigit,
**               	UseParensForNegativeNumbers, GroupDigits)
**- 	Returns an expression formatted as a percentage (multiplied by 100)
**  	with a trailing % character.
**  formatCurrency(str)-formats input to currency format
************************************************************* */


/* ********************************************************** */
/* Global Variables and Constants *************************** */
/* ********************************************************** */

var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var blanks = " \t\n\r";  // aka whitespace chars


// decimal point character differs by language and culture
var decimalPointDelimiter = "."

// non-digit characters allowed in phone numbers
var phoneNumberDelimiters = "()- +";

// characters allowed in US phone numbers
var validPhoneChars = digits + phoneNumberDelimiters;

// characters allowed in US phone numbers
var validUSPhoneChars = digits + phoneNumberDelimiters;


// U.S. phone numbers have 10 digits, formatted as ### ### #### or (###)###-####
var digitsInUSPhoneNumber = 10;

// non-digit characters which are allowed in ZIP Codes
var ZIPCodeDelimiters = "-";

// our preferred delimiter for reformatting ZIP Codes
var ZIPCodeDelimeter = "-"

// U.S. ZIP codes have 5 or 9 digits, formatted as ##### or #####-####
var digitsInZIPCode1 = 5
var digitsInZIPCode2 = 9

// Valid U.S. Postal Codes for states, territories, armed forces, etc.
// See http://www.usps.gov/ncsc/lookups/abbr_state.txt
var USStateCodeDelimiter = "|";
var USStateCodes = "AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|AE|AA|AE|AE|AP|al|ak|as|az|ar|ca|co|ct|de|dc|fm|fl|ga|gu|hi|id|il|in|ia|ks|ky|la|me|mh|md|ma|mi|mn|ms|mo|mt|ne|nv|nh|nj|nm|ny|nc|nd|mp|oh|ok|or|pw|pa|pr|ri|sc|sd|tn|tx|ut|vt|vi|va|wa|wv|wi|wy|ae|aa|ae|ae|ap"
//var month[] = {"JANUARY", "FEBURARY", "MARCH", "APRIL", "JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"};



/* ********************************************************** */
/* Functions ************************************************ */
/* ********************************************************** */

// Returns true if string s is valid email address
// The variable filter is 	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

function isEmailNew(s)
{		

		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (filter.test(s))
			{
					return true;
			}
		else 
		  {
		   return false;
		   }
}

// Returns true if string s is empty

function isEmpty(s)
  {
  return ((s == null) || (s.length == 0));
  }


// Returns true if string s is empty or all blank chars

function isBlank(s)
  {
  var i;

  // Is s empty?
  if (isEmpty(s))
    return true;

  // Search through string's chars one by one until we find first
  // non-blank char, then return false; if we don't, return true
  for (i=0; i<s.length; i++)
    {   
    // Check that current character isn't blank
    var c = s.charAt(i);
    if (blanks.indexOf(c) == -1) 
      return false;
    }
  // All characters are blank
  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 blank
    var c = s.charAt(i);
    if (bag.indexOf(c) == -1) 
      returnString += c;
    }
  return returnString;
  }


// Removes all characters which do NOT appear in string bag from string s

function stripCharsNotInBag (s, bag)
  {
  var i;
  var returnString = "";

  // Search through string's characters one by one;
  // if character is in bag, append to returnString
  for (i = 0; i < s.length; i++)
    {   
    // Check that current character isn't blank
    var c = s.charAt(i);
    if (bag.indexOf(c) != -1) 
      returnString += c;
    }
  return returnString;
  }


// Removes all blank chars (as defined by blanks) from s

function stripBlanks(s)
  {
  return stripCharsInBag(s, blanks)
  }


// Removes leading blank chars (as defined by blanks) from s

function stripLeadingBlanks(s)
  { 
  var i = 0;
  while ((i < s.length) && (blanks.indexOf(s.charAt(i)) != -1))
     i++;
  return s.substring(i, s.length);
  }


// Removes trailing blank chars (as defined by blanks) from s

function stripTrailingBlanks(s)
  { 
  var i = s.length - 1;
  while ((i >= 0) && (blanks.indexOf(s.charAt(i)) != -1))
     i--;
  return s.substring(0, i+1);
  }


// Removes leading+trailing blank chars (as defined by blanks) from s

function stripLeadingTrailingBlanks(s)
  { 
  s = stripLeadingBlanks(s);
  s = stripTrailingBlanks(s);
  return s;
  }


// Returns true if character c is an English letter (A .. Z, a..z)

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 all chars in string s are numbers;
// first character is allowed to be + or -; does not 
// accept floating point, exponential notation, etc.

function isInteger(s)
  {
  if (isBlank(s))
    return false;

  // skip leading + or -
  if ((s.charAt(0) == "-") || (s.charAt(0) == "+"))
    var i = 1;
  else
    var i = 0;

  // Search through string's chars one by one until we find a 
  // non-numeric char, then return false; if we don't, return true
  for (i; 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;
  }


// True if string s is an unsigned floating point (real) number; 
// first character is allowed to be + or -; no exponential notation.

function isFloat(s)
  { 
  var seenDecimalPoint = false;

  if (isBlank(s)) 
    return false;
  if (s == decimalPointDelimiter) 
    return false;

  // skip leading + or -
  if ((s.charAt(0) == "-") || (s.charAt(0) == "+"))
    var i = 1;
  else
    var i = 0;

  // Search through string's chars one by one until we find a 
  // non-numeric char, then return false; if we don't, return true

  for (i; i<s.length; i++)
    {   
    // Check that current character is number
    var c = s.charAt(i);

    if ((c == decimalPointDelimiter) && !seenDecimalPoint) 
      seenDecimalPoint = true;
    else if (!isDigit(c)) 
      return false;
    }
  // All characters are numbers
  return seenDecimalPoint;
  }


// Returns true if string s is English letters (A .. Z, a..z) only

function isAlphabetic(s)
  {
  var i;

  if (isBlank(s)) 
     return false;

  // Search through string's chars one by one until we find a 
  // non-alphabetic char, then return false; if we don't, return true

  for (i = 0; i < s.length; i++)
  {   
  // Check that current character is letter
  var c = s.charAt(i);

  if (!isLetter(c))
    return false;
  }

  // All characters are letters
  return true;
  }


// Returns true if string s is English letters (A .. Z, a..z) and numbers only

function isAlphanumeric(s)
  {
  var i;

  if (isBlank(s)) 
     return false;

  // Search through string's chars one by one until we find a 
  // non-alphanumeric char, then return false; if we don't, return true

  for (i = 0; i < s.length; i++)
    {   
    // Check that current character is number or letter
    var c = s.charAt(i);

    if (! (isLetter(c) || isDigit(c) ) )
    return false;
    }

  // All characters are numbers or letters
  return true;
  }
// Returns true if string s is Digits Only (0..9) and numbers only

function isNumeric(s)
  {
  var i;

  if (isBlank(s)) 
     return false;

  // Search through string's chars one by one until we find a 
  // non-numeric char, then 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;
  }

// reformatString(targetStr [, str1, int1, str2, int2, ... strN, intN])       
//
// Handy function for arbitrarily inserting formatting characters
// or delimiters of various kinds within targetString.
//
// reformatString() takes one required string argument, targetStr, 
// and 0-N optional string/integer-pair arguments. These optional 
// arguments specify how targetStr is to be reformatted and how/where 
// other strings are to be inserted in it.
//
// reformatString() processes the optional args in order one by one.
// * If the argument is an integer, reformatString() appends that number 
//   of sequential characters from targetStr to the resultString.
// * If the argument is a string, reformatString() appends the string
//   to the resultString.
//
// NOTE: The first argument after targetString must be a string.
// (It can be empty.)  The second argument must be an integer.
// Thereafter, integers and strings must alternate.  This is to
// provide backward compatibility to Navigator 2.0.2 JavaScript
// by avoiding use of the typeof operator.
//
// It is the caller's responsibility to make sure that we do not
// try to copy more characters from s than s.length.
//
// EXAMPLES:
//
// * To reformat a 10-digit U.S. phone number from "1234567890"
//   to "(123)456-7890" make this function call:
//   reformatString("1234567890", "(", 3, ")", 3, "-", 4)
//
// HINT:
//
// If you have a string which is already delimited in one way
// (example: a phone number delimited with spaces as "123 456 7890")
// and you want to delimit it in another way using function reformat,
// call stripCharsNotInBag() or stripBlanks() to remove unwanted 
// characters, THEN call function reformatString to delimit as desired.
//
// EXAMPLE:
//
// reformatString(stripCharsNotInBag ("123 456 7890", digits),
//           "(", 3, ") ", 3, "-", 4)

function reformatString(targetString)
  { 
  var arg;
  var sPos = 0;
  var resultString = "";

  for (var i=1; i<reformatString.arguments.length; i++)
    {
    arg = reformatString.arguments[i];
    if (i%2 == 1) 
      {
      resultString += arg;
      }
    else
      {
      resultString += targetString.substring(sPos, sPos + arg);
      sPos += arg;
      }
    }
  return resultString;
  }


// Returns true if s is valid U.S. phone number (with area code): 10 digits

function isUSPhoneNumber(s)
  { 
  if (isBlank(s)) 
    return false;
  s = stripCharsNotInBag(s, digits);
  return (isInteger(s) && (s.length == digitsInUSPhoneNumber));
  }

function stripTrailingBlanks(s)
  { 
  var i = s.length - 1;
  while ((i >= 0) && (blanks.indexOf(s.charAt(i)) != -1))
     i--;
  return s.substring(0, i+1);
  }

function isValidPhoneNumber(s)
  { 
  if (isBlank(s))
    return false;
    
  for(i=0; i<s.length; i++)
  {
	var c = s.charAt(i);
	if (validPhoneChars.indexOf(c) == -1)
		return false;
  }
return true;
}

function isValidFaxNumber(s)
  { 
  if (isBlank(s))
    return false;
    
  for(i=0; i<s.length; i++)
  {
	var c = s.charAt(i);
	if (validPhoneChars.indexOf(c) == -1)
		return false;
  }
return true;
}
// Returns true if string s is a valid U.S. ZIP code: ##### or #####-####

function isZIPCode(s)
  { 
  if (isBlank(s)) 
    return false;

  s = stripLeadingTrailingBlanks(s);

  if ((isInteger(s)) && (s.indexOf("-") == -1) &&  // #####
      (s.length == digitsInZIPCode1))
    return true;

  if (s.indexOf("-") != 5)  // - in wrong place
    return false;

  s = stripCharsNotInBag(s, digits);

  if (s.length == digitsInZIPCode2)
    return true;   // #####-####
  else
    return false;  // not #####-####
  }


// Returns true if s is valid 2-letter U.S. state abbreviation

function isStateCode(s)
  { 
  if (isBlank(s)) 
    return false;
  return ((USStateCodes.indexOf(s) != -1) &&
          (s.indexOf(USStateCodeDelimiter) == -1))
  }



//function to check valid email address

function isEmail(emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	//alert("Email address seems incorrect (check @ and .'s)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    //alert("The username doesn't seem to be valid.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	  //      alert("Destination IP address is invalid!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	//alert("The domain name doesn't seem to be valid.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   //alert("The address must end in a three-letter domain, or two letter country.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
   //alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}

// Returns true if string is a valid email address: @ and . required,
// at least one char before @, at least one char before and after .

function isEmail(s)
  { 
  if (isBlank(s)) 
    return false;
  
  // there must be >= 1 character before @, so we start
  // 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;
  }



// Returns true if string s is an integer such that a <= s <= b

function isIntegerInRange (s, a, b)
  { 
  if (isBlank(s)) 
    return false;
  if (!isInteger(s)) 
    return false;
  var num = parseInt(s);
  return ((num >= a) && (num <= b));
  }
  
  
  function isIntegerInRange1 (s)
  { 
  if (isBlank(s)) 
    return false;
  if (!isInteger(s)) 
    return false;
//var num = parseInt(s);
  if ((s.length == 5) || (s.length == 9))
	return true;
  }


// Returns index of checked radio button in radio set,
// or -1 if no radio buttons are checked

function getCheckedRadioButton(radioSet)
  { 
  for (var i=0; i<radioSet.length; i++)
    if (radioSet[i].checked)
      return i;
  return -1;
  }


// Returns array containing index(es) of checked checkbox(es) 
// in checkbox set, or -1 if no checkboxes are checked

function getCheckedCheckboxes(checkboxSet)
  {
  var arr = new Array();
  for (var i=0,j=0; i<checkboxSet.length; i++)
    if (checkboxSet[i].checked)
      arr[j++] = i;
  if (arr.length > 0)
    return arr;
  else
    return -1;
  }


// Returns array containing index(es) of checked option(s) 
// in select box, or -1 if no options are selected

function getCheckedSelectOptions(select)
  {
  var arr = new Array();
  for (var i=0,j=0; i<select.length; i++)
    if (select.options[i].selected)
      arr[j++] = i;
  if (arr.length > 0)
    return arr;
  else
    return -1;
  }

function isDate(str) {
  if (str.length != 10) { return false }

  for (j=0; j<str.length; j++) {
    if ((j == 2) || (j == 5)) {
      if (str.charAt(j) != "/") { return false }
    } else {
      if ((str.charAt(j) < "0") || (str.charAt(j) > "9")) { return false }
    }
  }

  var month = str.charAt(0) == "0" ? parseInt(str.substring(1,2)) : parseInt(str.substring(0,2));
  var day = str.charAt(3) == "0" ? parseInt(str.substring(4,5)) : parseInt(str.substring(3,5));
  var begin = str.charAt(6) == "0" ? (str.charAt(7) == "0" ? (str.charAt(8) == "0" ? 9 : 8) : 7) : 6;
  var year = parseInt(str.substring(begin, 10));
  
  if (day == 0) { return false }
  if (month == 0 || month > 12) { return false }
  if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
    if (day > 31) 
    { 
     return false; 
    }
  } else {
    if (month == 4 || month == 6 || month == 9 || month == 11) {
      if (day > 30) { return false }
    } else {
      if (year%4 != 0) {
        if (day > 28) { return false }
      } else {
        if (day > 29) { return false }
      }
    }
  }
  return true;
}

//function to format value in currency fields

function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}




        function Mid(str, start, len)
        /***
                IN: str - the string we are LEFTing
                    start - our string's starting position (0 based!!)
                    len - how many characters from start we want to get

                RETVAL: The substring from start to start+len
        ***/
        {
                // Make sure start and len are within proper bounds
                if (start < 0 || len < 0) return "";

                var iEnd, iLen = String(str).length;
                if (start + len > iLen)
                        iEnd = iLen;
                else
                        iEnd = start + len;

                return String(str).substring(start,iEnd);
        }


// Keep in mind that strings in JavaScript are zero-based, so if you ask
// for Mid("Hello",1,1), you will get "e", not "H".  To get "H", you would
// simply type in Mid("Hello",0,1)

// You can alter the above function so that the string is one-based.  Just
// check to make sure start is not <= 0, alter the iEnd = start + len to
// iEnd = (start - 1) + len, and in your final return statement, just
// return ...substring(start-1,iEnd)

 function Right(str, n)
    /***
              IN: str - the string we are RIGHTing
                    n - the number of characters we want to return
                RETVAL: n characters from the right side of the string
        ***/
        {
                if (n <= 0)     // Invalid bound, return blank string
                   return "";
                else if (n > String(str).length)   // Invalid bound, return
                   return str;                     // entire string
                else { // Valid bound, return appropriate substring
                   var iLen = String(str).length;
                   return String(str).substring(iLen, iLen - n);
                }
        }



        function Left(str, n)
        /***
                IN: str - the string we are LEFTing
                    n - the number of characters we want to return

                RETVAL: n characters from the left side of the string
        ***/
        {
                if (n <= 0)     // Invalid bound, return blank string
                        return "";
                else if (n > String(str).length)   // Invalid bound, return
                        return str;                // entire string
                else // Valid bound, return appropriate substring
                        return String(str).substring(0,n);
        }

 
 


function FormatCurrency(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.										
 
	RETVAL:
		The formatted number!		
 **********************************************************************/
{
	var tmpStr = new String(FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas));

	if (tmpStr.indexOf("(") != -1 || tmpStr.indexOf("-") != -1) {
		// We know we have a negative number, so place '$' inside of '(' / after '-'
		if (tmpStr.charAt(0) == "(")
			tmpStr = "($"  + tmpStr.substring(1,tmpStr.length);
		else if (tmpStr.charAt(0) == "-")
			tmpStr = "-$" + tmpStr.substring(1,tmpStr.length);
			
		return tmpStr;
	}
	else
		return "$" + tmpStr;		// Return formatted string!
}



function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.										
 
	RETVAL:
		The formatted number!		
 **********************************************************************/
{ 
        if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))	
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart > 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}


function FormatDateTime(datetime, FormatType)
/*
	 FomatType takes the following values
		1 - General Date = Friday, October 30, 1998
		2 - Typical Date = 10/30/98
		3 - Standard Time = 6:31 PM
		4 - Military Time = 18:31
*/
{
	var strDate = new String(datetime);

	if (strDate.toUpperCase() == "NOW") {
		var myDate = new Date();
		strDate = String(myDate);
	} else {
		var myDate = new Date(datetime);
		strDate = String(myDate);
	}


	// Get the date variable parts
	var Day = new String(strDate.substring(0,3));
	if (Day == "Sun") Day = "Sunday";
	if (Day == "Mon") Day = "Monday";
	if (Day == "Tue") Day = "Tuesday";
	if (Day == "Wed") Day = "Wednesday";
	if (Day == "Thu") Day = "Thursday";
	if (Day == "Fri") Day = "Friday";
	if (Day == "Sat") Day = "Saturday";	
	
	var Month = new String(strDate.substring(4,7)), MonthNumber = 0;
	if (Month == "Jan") { Month = "January"; MonthNumber = 1; }
	if (Month == "Feb") { Month = "February"; MonthNumber = 1; }
	if (Month == "Mar") { Month = "March"; MonthNumber = 1; }
	if (Month == "Apr") { Month = "April"; MonthNumber = 1; }
	if (Month == "May") { Month = "May"; MonthNumber = 1; }
	if (Month == "Jun") { Month = "June"; MonthNumber = 1; }
	if (Month == "Jul") { Month = "July"; MonthNumber = 1; }
	if (Month == "Aug") { Month = "August"; MonthNumber = 1; }
	if (Month == "Sep") { Month = "September"; MonthNumber = 1; }
	if (Month == "Oct") { Month = "October"; MonthNumber = 1; }
	if (Month == "Nov") { Month = "November"; MonthNumber = 1; }
	if (Month == "Dec") { Month = "December"; MonthNumber = 1; }
	
	var curPos = 11;
	var MonthDay = new String(strDate.substring(8,10));
	if (MonthDay.charAt(1) == " ") {
		MonthDay = "0" + MonthDay.charAt(0);
		curPos--;
	}	
	
	var MilitaryTime = new String(strDate.substring(curPos,curPos + 5));
	
	var Year = new String(strDate.substring(strDate.length - 4, strDate.length));	
	
	document.write(strDate + "");	

	// Format Type decision time!
	if (FormatType == 1)
		strDate = Day + ", " + Month + " " + MonthDay + ", " + Year;
	else if (FormatType == 2)
		strDate = MonthNumber + "/" + MonthDay + "/" + Year.substring(2,4);
	else if (FormatType == 3) {
		var AMPM = MilitaryTime.substring(0,2) >= 12 && MilitaryTime.substring(0,2) != "24" ? " PM" : " AM";
		if (MilitaryTime.substring(0,2) > 12)
			strDate = (MilitaryTime.substring(0,2) - 12) + ":" + MilitaryTime.substring(3,MilitaryTime.length) + AMPM;
		else {
			if (MilitaryTime.substring(0,2) < 10)
				strDate = MilitaryTime.substring(1,MilitaryTime.length) + AMPM;
			else
				strDate = MilitaryTime + AMPM;
		}
	}	
	else if (FormatType == 4)
		strDate = MilitaryTime;


	return strDate;
}



function FormatPercent(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.										
 
	RETVAL:
		The formatted number!		
 **********************************************************************/
{
	var tmpStr = new String(FormatNumber(num*100,decimalNum,bolLeadingZero,bolParens,bolCommas));

	if (tmpStr.indexOf(")") != -1) {
		// We know we have a negative number, so place '%' inside of ')'
		tmpStr = tmpStr.substring(0,tmpStr.length - 1) + "%)";
		return tmpStr;
	}
	else
		return tmpStr + "%";			// Return formatted string!
}

function isNumeric(s)
  {
  if (isBlank(s))
    return false;

  // Search through string's chars one by one until we find a 
  // non-numeric char, then return false; if we don't, return true
  for (var 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;
  }


function isDecimal(str, CharsBeforeDecimal, CharsAfterDecimal)
{
 if (isBlank(str)) 
    return false;
  
 var idxs = str.indexOf(".");
 var idxe = str.lastIndexOf(".");

 //ex= ".000 "
 if ((idxs!=-1) && (idxe!=-1))
 {
	//ex = "000." or ".000" or "87383.7384.847" or "7834..34"
	if( (idxs==0) || (idxs==(str.length-1)) || (idxs!=idxe))
		return false;
	else
	{
	//ex= "23.233"
	 if (idxs==idxe)
	 {
	  var strBeg = str.substring(0,idxs);
	  var strEnd = str.substring(idxs+1, (str.length));
	  
	  if(strBeg.length>CharsBeforeDecimal)
	  	return false; 
	 	
	  if(strEnd.length>CharsAfterDecimal)
		return false; 
	 
	  if (! ( isNumeric(strBeg) && isNumeric(strEnd) ))
	   return false;
	    
	 }
	}
 }
 else
 {	
//ex ="24234324"	
if (str.length > CharsBeforeDecimal)		
	return false;
  if (!isNumeric(str))
   return false;
 
 }
 return true;
}



function funNavigate(surl)
{
	
	
	
	sname=document.location.pathname;
	idx=sname.lastIndexOf("/")
	sname=sname.substr(idx+1)
	document.frmBack.hidgoback.value=surl
	if (sname=="home.asp") 	
		onPageUnload();
	else
		window.location.href=surl
	
	
}

function validate(obj)
{
	
	if ((event.keyCode>=48 && event.keyCode <=57))
	{
		return true;
	}
	else
	{
		return false;
	}	
}

//function will validate for integer values on blur event in text box
function validateIntOnblur(objName,val)
{   
    var iVal = parseInt(val);
    
    if (isNaN(iVal))
	{
	  objName.value ="";
	  objName.focus();
	  return false;
	  
	}
	else{
		if(iVal==0)
		{
		  objName.value ="";
		  objName.focus();
		  return false;
		  
		} 
		else
		{
		    objName.value = iVal;
			return true;
		}	
	}
}

function openWindow(url, w, h) {
    var options = "width=" + w + ",height=" + h + ",";
    options += "resizable=yes,scrollbars=1,status=yes,";
    options += "menubar=no,toolbar=no,location = no,directories=no top=0, left=0";
    window.name = "newwin";
    var newWin = window.open(url, '_new', options);
    newWin.focus();
}

function frmAddItem(objFrm)
{	
	
	if( (objFrm.txt1.value=="") || (objFrm.txt1.value==0))
	{ 
		alert('Qty cannot be empty or zero')
		objFrm.txt1.focus;
		return;
	}
	if (objFrm.selcolor.selectedIndex == -1)
		{
				alert("Please Select Color.");
				objFrm.selcolor.focus;
				return;
		}
	if (objFrm.selsize.selectedIndex == -1)
		{
				alert("Please Select Size.");
				objFrm.selsize.focus;
				return;
		}
	
		
		objFrm.submit()
	
}

var extArray = new Array(".gif", ".jpg", ".png", ".jpeg",".jpe");

function isValidFile(file) {
	allowSubmit = false;
	while (file.indexOf("\\") != -1)
	{
		file = file.slice(file.indexOf("\\") + 1);
	}

	ext = file.slice(file.indexOf(".")).toLowerCase();
	for (var i = 0; i < extArray.length; i++) 
	{
		if (extArray[i] == ext) { 
			allowSubmit = true; 
			break; 
		}
	}

	if (allowSubmit) 
		return true;
	else
		return false;
}


function closeWindow(sUrl){
 var win = eval(window.opener)
 open(sUrl,win.name);
 window.close();   
 }
 
 
function funDetailForm(sUrl)
{
	document.frm.action = sUrl;
	document.frm.submit();
}

<!--
//Begin dHTML Toolltip Timer
var tipTimer;
//End dHTML Toolltip Timer

function locateObject(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=locateObject(n,d.layers[i].document); return x;
}

function hideTooltip(object)
{
if (document.all)
{
	locateObject(object).style.visibility="hidden"
	locateObject(object).style.left = 1;
	locateObject(object).style.top = 1;
return false
}
else if (document.layers)
{
	locateObject(object).visibility="hide"
	locateObject(object).left = 1;
	locateObject(object).top = 1;
	return false
}
else
	return true
}

function showTooltip(object,e, tipContent, backcolor, bordercolor, textcolor, displaytime)
{
	window.clearTimeout(tipTimer)
	
	if (document.all)
		{
			locateObject(object).style.top=document.body.scrollTop+event.clientY+20
			
			locateObject(object).innerHTML='<table style="font-family: Tahoma, Arial, Helvetica, sans-serif; font-size: 11px; border: '+bordercolor+'; border-style: solid; border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; background-color: '+backcolor+'" width="10" border="0" cellspacing="5" cellpadding="5"><tr><td nowrap><font style="font-family: Tahoma, Arial, Helvetica, sans-serif; font-size: 11px; color: '+textcolor+'">'+unescape(tipContent)+'</font></td></tr></table> '

			if ((e.x + locateObject(object).clientWidth) > (document.body.clientWidth + document.body.scrollLeft))
				{	
					locateObject(object).style.left = (document.body.clientWidth + document.body.scrollLeft) - locateObject(object).clientWidth-10;
				}
			else
			{
			locateObject(object).style.left=document.body.scrollLeft+event.clientX
			}
		locateObject(object).style.visibility="visible"
		tipTimer=window.setTimeout("hideTooltip('"+object+"')", displaytime);
		return true;
		}
	else if (document.layers)
		{
		locateObject(object).document.write('<table width="10" border="0" cellspacing="1" cellpadding="1"><tr bgcolor="'+bordercolor+'"><td><table width="10" border="0" cellspacing="0" cellpadding="2"><tr bgcolor="'+backcolor+'"><td nowrap><font style="font-family: Tahoma, Arial, Helvetica, sans-serif; font-size: 11px; color: '+textcolor+'">'+unescape(tipContent)+'</font></td></tr></table></td></tr></table>')
		locateObject(object).document.close()
		locateObject(object).top=e.y+20

		if ((e.x + locateObject(object).clip.width) > (window.pageXOffset + window.innerWidth))
			{
				locateObject(object).left = window.innerWidth - locateObject(object).clip.width-10;
			}
		else
			{
			locateObject(object).left=e.x;
			}
		locateObject(object).visibility="show"
		tipTimer=window.setTimeout("hideTooltip('"+object+"')", displaytime);
		return true;
	}
	else
	{
		return true;
	}
}
//-->
