﻿// VARIABLE DECLARATIONS
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var whitespace = " \t\n\r";
var decimalPointDelimiter = "."
var phoneNumberDelimiters = "()- ";
var validUSPhoneChars = digits + phoneNumberDelimiters;
var SSNDelimiters = "- ";
var validSSNChars = digits + SSNDelimiters;
var digitsInSocialSecurityNumber = 9;
var digitsInUSPhoneNumber = 10;
var ZIPCodeDelimiters = "-";
var ZIPCodeDelimeter = "-"
var validZIPCodeChars = digits + ZIPCodeDelimiters
var digitsInZIPCode1 = 5
var digitsInZIPCode2 = 9
// m is an abbreviation for "missing"

var mPrefix = "You did not enter a value into the "
var mSuffix = " field. This is a required field. Please enter it now."

// i is an abbreviation for "invalid"
var inumeric="Your entry must be numeric(e.g. 1,2,3). Please re-enter it now."
var ialphanumeric="Your entry must be alphanumeric(e.g. a,b,c,1,2,3). Please re-enter it now."
var iStateCode = "Please enter a two-character U.S. state abbreviation (e.g. CA for California)."
var iZIPCode = "Please enter a five- or nine-digit U.S. ZIP Code (e.g. 91302 or 91302-2222)."
var iUSPhone = "Please enter a 10-digit U.S. phone number (e.g. (818)598-1888)."
var iSSN = "Please enter a 9-digit U.S. Social Security number (e.g. 123 45 6789)."
var iEmail = "Please enter a valid email address (e.g. info@autoland.com)."
var iDay = "Please enter a date number between 1 and 31."
var iMonth = "Please enter a month number between 1(January) and 12(December)."
var iYear = "Please enter a valid year as a four-digit number(e.g. 2001)."
var iDatePrefix = "The day, month, and year you entered"
var iDateSuffix = "do not form a valid date. Please re-enter a valid combination."
var iAmount="Please re-type your entry." 
var iVIN = "Your entry must be at least 17 digits and alphanumeric(e.g. a,b,c,1,2,3)."
var defaultEmptyOK = false

function makeArray(n) {
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}

var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;

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"

// Check whether string s is empty.
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

// Returns true if string s is empty or 
// whitespace characters only.

function isWhitespace (s)

{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}


// Removes all characters which appear in string bag from string s.
function stripCharsInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

// Removes all 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 whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}

// Removes all whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.
function stripWhitespace (s)

{   return stripCharsInBag (s, whitespace)
}


function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}

// Removes initial (leading) whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripInitialWhitespace (s)

{   var i = 0;

    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    
    return s.substring (i, s.length);
}

// Returns true if character c is an English letter 
// (A .. Z, a..z).
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"))
}

function isSpace (c)
{   return ((c ==" " ))
}

function isComma (c)
{   return ((c=="," ))
}

function isDot (c)
{   return ((c=="." ))
}

function isDollarSign (c)
{   return ((c=="$" ))
}

// Returns true if character c is a letter or digit.
function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}


function isInteger (s)

{   var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}

function isSignedInteger (s)

{   if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}


function isPositiveInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isPositiveInteger.arguments.length > 1)
        secondArg = isPositiveInteger.arguments[1];

     return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) > 0) ) );
}



function isNonnegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

        return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) >= 0) ) );
}


function isNegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNegativeInteger.arguments.length > 1)
        secondArg = isNegativeInteger.arguments[1];

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) < 0) ) );
}


function isNonpositiveInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonpositiveInteger.arguments.length > 1)
        secondArg = isNonpositiveInteger.arguments[1];

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) <= 0) ) );
}

function isFloat (s)

{   var i;
    var seenDecimalPoint = false;

    if (isEmpty(s)) 
       if (isFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isFloat.arguments[1] == true);

    if (s == decimalPointDelimiter) return false;

    for (i = 0; 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 true;
}

function isSignedFloat (s)

{   if (isEmpty(s)) 
       if (isSignedFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedFloat.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedFloat.arguments.length > 1)
            secondArg = isSignedFloat.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isFloat(s.substring(startPos, s.length), secondArg))
    }
}

function isAlphabetic (s)

{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }

    // All characters are letters.
    return true;
}

function isAlphanumeric(s)

{   var i;

     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) || isSpace(c) ) )
        return false;
    }

    // All characters are numbers or letters.
    return true;
}


function reformat (s)

{   var arg;
    var sPos = 0;
    var resultString = "";

    for (var i = 1; i < reformat.arguments.length; i++) {
       arg = reformat.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
           resultString += s.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return resultString;
}


function isUSPhoneNumber (s)
{   if (isEmpty(s)) 
       if (isUSPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isUSPhoneNumber.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInUSPhoneNumber)
}



function isZIPCode (s)
{  if (isEmpty(s)) 
       if (isZIPCode.arguments.length == 1) return defaultEmptyOK;
       else return (isZIPCode.arguments[1] == true);
   return (isInteger(s) && 
            ((s.length == digitsInZIPCode1) ||
             (s.length == digitsInZIPCode2)))
}

function isStateCode(s)
{   if (isEmpty(s)) 
       if (isStateCode.arguments.length == 1) return defaultEmptyOK;
       else return (isStateCode.arguments[1] == true);
    return ( (USStateCodes.indexOf(s) != -1) &&
             (s.indexOf(USStateCodeDelimiter) == -1) )
}

function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}


function isYear (s)
{   if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 4) && (parseInt(s) > 1935) && (parseInt(s) < 2026) );
}


function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;
    //alert(s);
    var num 
    if (s=="08")
    {
     num=8;
    } 
    else
    {
     if (s=="09")
     {
      num=9;
     }
     else
     {
      num = parseInt(s);
     }
    }
    
   // alert(num);
    return ((num >= a) && (num <= b));
}


function isMonth (s)
{   if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}


function isDay (s)
{   if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 1, 31);
}


function daysInFebruary (year)
{   // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}


function isDate (year, month, day)
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.
    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = parseInt(year,10);
    var intMonth = parseInt(month,10);
    var intDay = parseInt(day,10);

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}

function isAmount(s)
{   var i;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);

        if (! (isComma(c) || isDigit(c) || isDot(c) ))
        { 
           return false;  
        }
    }
    return true;
}

function isDollarAmount(s)
{   var i;
	var amt;
	
	amt = "";
	
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);

        if (! (isComma(c) || isDigit(c) || isDot(c) || isDollarSign(c) ))
        { 
           return false;  
        }
        
        if (isDigit(c) || isDot(c))
        {
           amt = amt + c;
        }
    }
    
    if (amt == 0 || amt > 1000000)
	{
		return false;
	}
    
    return true;
}

function prompt (s)
{   window.status = s
}


// Display data entry prompt string s in status bar.

function promptEntry (s)
{   window.status = pEntryPrompt + s
}

function warnEmpty (theField, s)
{   theField.focus()
    alert(mPrefix + s + mSuffix)
    return false
}

function warnInvalid (theField, s)
{   theField.focus()
    //theField.select()
    alert(s)
    return false
}

/* FUNCTIONS TO INTERACTIVELY CHECK VARIOUS FIELDS. */

function checkString (theField, s, emptyOK)
{   
    if (checkString.arguments.length == 2) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (isWhitespace(theField.value)) 
       return warnEmpty (theField, s);
    else return true;
}

function checkSring(theField, s, emptyOK)
{   
    if ((emptyOK == true) && (isEmpty(theField.value))) 
       return true;
    if ((emptyOK == false) && (isEmpty(theField.value))) 
       return warnEmpty (theField, s);
    else
       return true;
}

function checkAlphanumeric(theField, s, emptyOK)
{   
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (isWhitespace(theField.value))
      { 
       return warnEmpty (theField, s);
      }
    if (isAlphanumeric(theField.value))
       return true;
    else
       return warnInvalid (theField, s + ialphanumeric);  
}

function checkAmount(theField, s, emptyOK)
{
   if ((emptyOK == true) && (isEmpty(theField.value))) return true;
   if (isEmpty(theField.value))
   {
       return warnInvalid (theField, s+iAmount);    
   }
   if (isAmount(theField.value)) {
       return true;        
   }
   else {
       return warnInvalid (theField, s+iAmount); 
   }
} 

function checknumeric(theField, s, emptyOK)
{   
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (isNaN(theField.value) || isEmpty(theField.value))
       return warnInvalid (theField, s + inumeric);  
    else
       return true;       
}


function checkStateCode (theField,s, emptyOK)
{   
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  theField.value = theField.value.toUpperCase();
       if (!isStateCode(theField.value, false)) 
          return warnInvalid (theField, s+iStateCode);
       else return true;
    }
}

function reformatZIPCode (ZIPString)
{   if (ZIPString.length == 5) return ZIPString;
    else return (reformat (ZIPString, "", 5, "-", 4));
}


function checkZIPCode (theField,s,emptyOK)
{   
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    { var normalizedZIP = stripCharsInBag(theField.value, ZIPCodeDelimiters)
      if (!isZIPCode(normalizedZIP, false)) 
         return warnInvalid (theField, s+iZIPCode);
      else 
      {  // if you don't want to insert a hyphen, comment next line out
         theField.value = reformatZIPCode(normalizedZIP)
         return true;
      }
    }
}

function reformatUSPhone (USPhone)
{   return (reformat (USPhone, "(", 3, ") ", 3, "-", 4))
}

function checkUSPhone (theField,s, emptyOK)
{   
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  var normalizedPhone = stripCharsInBag(theField.value, phoneNumberDelimiters)
       if (!isUSPhoneNumber(normalizedPhone, false)) 
          return warnInvalid (theField, s + ": " + iUSPhone);
       else 
       {  // if you don't want to reformat as (123) 456-789, comment next line out
          theField.value = reformatUSPhone(normalizedPhone)
          return true;
       }
    }
}

function checkEmail (theField,s, emptyOK)
{   if (checkEmail.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else if (!isEmail(theField.value, false)) 
       return warnInvalid (theField, s+iEmail);
    else return true;
}

function checkYear (theField,s,emptyOK)
{   if (checkYear.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isYear(theField.value, false)) 
       return warnInvalid (theField, s + iYear);
    else return true;
}

function checkMonth (theField, emptyOK)
{   if (checkMonth.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isMonth(theField.value, false)) 
       return warnInvalid (theField, iMonth);
    else return true;
}

function checkDay (theField, emptyOK)
{   if (checkDay.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isDay(theField.value, false)) 
       return warnInvalid (theField, iDay);
    else return true;
}

function checkVIN(theField,s,emptyOK)
{  
	if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if ( (!isAlphanumeric(theField.value, false)) || theField.value.length < 17 ){
       return warnInvalid (theField, s);       
    }   
	if (theField.value.indexOf(" ") != -1) {		
        return warnInvalid(theField, 'The Vin Number cannot have any white spaces');
    }    
    return true;
}

function checkDate(yearField, monthField, dayField, labelString,emptyOK, OKtoOmitDay)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    
    if (checkDate.arguments.length == 5) OKtoOmitDay = false;
    if ((emptyOK == true) && 
		(isEmpty(yearField.value)) && 
		(isEmpty(monthField.value)) && 
		(isEmpty(dayField.value))) 
	{
		return true;
	}
    
    if (!isMonth(monthField.value))
    {
		return warnInvalid(monthField, labelString + iMonth);
	}
	
    if ((OKtoOmitDay == true) && 
		isEmpty(dayField.value)) 
	{
		return true;
	}
    else 
	{
		if (!isDay(dayField.value))
		{
			return warnInvalid (dayField, labelString+iDay);
		}
		
		if (!isYear(yearField.value)) 
		{
			return warnInvalid (yearField,labelString+iYear);
		}
    
		if (isDate (yearField.value, monthField.value, dayField.value))
		{
			return true;
		}
	}
		
    alert (iDatePrefix + labelString + iDateSuffix)
    return false
}


function getRadioButtonValue (radio)
{   for (var i = 0; i < radio.length; i++)
    {   if (radio[i].checked) { break }
    }
    return radio[i].value
}

function checkSelectList(theField,label)
{
 if (theField.selectedIndex==0)
    {
    alert(label + " was not selected. Please select one.");
    theField.focus();
    return false;
    }
 else
    return true ;
}

function checkRadioButton(theField,label)
{
 
   var index=""
   index=theField.length ;
   if (isNaN(index))
   {
    index="ZeroLength" ;
   }
    if (index=="ZeroLength")
    {
     if (theField.checked) 
		{
		 return true;
		}
    }
    else
    {
		for (var i = 0; i < index; i++)
		{   if (theField[i].checked) 
		    {
		     return true;
		     break ;
		    }
		}
	}
    alert(label + " was not selected. Please select one.");
    return false;
    
}

function checkImageSize(theImageField, intMaxWidth, intMaxHeight, strErrorMessage){
	var myImage = new Image();
	var strFileName;
	var intImageWidth;
	var intImageHeight;
	var blnReturnValue;
	
	strFileName = theImageField.value;
	strFileName = strFileName.toUpperCase();
	
	if (strFileName == ''){return true;}
	
	if ((strFileName.indexOf('.JPG') >= 0 || strFileName.indexOf('.GIF') >= 0) == false){
		alert("Your image must be a .JPG or .GIF format file.");
		theImageField.focus();
		return false;
	}
	
	if (IsNetscape()){strFileName = "file:///" + strFileName;}			
	myImage.src = strFileName;		
		
	intImageWidth = myImage.width;	
	intImageHeight = myImage.height;		
	
	if ((intImageWidth > intMaxWidth) || (intImageHeight > intMaxHeight))
	{
		if (strErrorMessage != "")
		{
			alert(strErrorMessage);
			theImageField.focus();
		}
		blnReturnValue = false;
	}
	else
	{
		blnReturnValue = true;
	}
	
	myImage.Flush;
	myImage = null;
	return blnReturnValue;
}

function IsNetscape()
{
	var intLayers;

	intLayers = (document.layers) ? 1 : 0;

	if (intLayers == 0)
		return false;
	else
		return true;
}

function checkTextAreaSize(theField, maxFieldSize, strLabel)
{
	if (theField.value.length > maxFieldSize)
	{
		alert(strLabel + ': This field cannot be longer than ' + maxFieldSize + ' characters. Please re-type or edit your entry.');
		theField.select();
		return false;
	}
	else
	{
		return true;
	}
}

function checkFieldSize(theField, intMaxLength)
{
	if(theField.value.length > intMaxLength)
	{
		theField.value = theField.value.substring(0, intMaxLength);
	}
}

var separator = ",";  // use comma as 000's separator
var decpoint = ".";  // use period as decimal point
var percent = "%";
var currency = "$";  // use dollar sign for currency

function formatNumber(number, format) {  // use: formatNumber(number, "format")
	if (number - 0 != number) return null;  // if number is NaN return null
	var useSeparator = format.indexOf(separator) != -1;  // use separators in number
	var usePercent = format.indexOf(percent) != -1;  // convert output to percentage
	var useCurrency = format.indexOf(currency) != -1;  // use currency format
	var isNegative = (number < 0);
	number = Math.abs (number);
	if (usePercent) number *= 100;
	format = strip(format, separator + percent + currency);  // remove key characters
	number = "" + number;  // convert number input to string

	// split input value into LHS and RHS using decpoint as divider
	var dec = number.indexOf(decpoint) != -1;
	var nleftEnd = (dec) ? number.substring(0, number.indexOf(".")) : number;
	var nrightEnd = (dec) ? number.substring(number.indexOf(".") + 1) : "";

	// split format string into LHS and RHS using decpoint as divider
	dec = format.indexOf(decpoint) != -1;
	var sleftEnd = (dec) ? format.substring(0, format.indexOf(".")) : format;
	var srightEnd = (dec) ? format.substring(format.indexOf(".") + 1) : "";

	// adjust decimal places by cropping or adding zeros to LHS of number
	if (srightEnd.length < nrightEnd.length) {
		var nextChar = nrightEnd.charAt(srightEnd.length) - 0;
		nrightEnd = nrightEnd.substring(0, srightEnd.length);
		if (nextChar >= 5) nrightEnd = "" + ((nrightEnd - 0) + 1);  // round up

		// patch provided by Patti Marcoux 1999/08/06
		while (srightEnd.length > nrightEnd.length) {
			nrightEnd = "0" + nrightEnd;
		}

		if (srightEnd.length < nrightEnd.length) {
			nrightEnd = nrightEnd.substring(1);
			nleftEnd = (nleftEnd - 0) + 1;
		}
	} else {
		for (var i=nrightEnd.length; srightEnd.length > nrightEnd.length; i++) {
			if (srightEnd.charAt(i) == "0") nrightEnd += "0";  // append zero to RHS of number
			else break;
		}
	}

	// adjust leading zeros
	sleftEnd = strip(sleftEnd, "#");  // remove hashes from LHS of format
	while (sleftEnd.length > nleftEnd.length) {
		nleftEnd = "0" + nleftEnd;  // prepend zero to LHS of number
	}

	if (useSeparator) nleftEnd = separate(nleftEnd, separator);  // add separator
		var output = nleftEnd + ((nrightEnd != "") ? "." + nrightEnd : "");  // combine parts
		output = ((useCurrency) ? currency : "") + output + ((usePercent) ? percent : "");
		if (isNegative) {
			// patch suggested by Tom Denn 25/4/2001
			output = (useCurrency) ? "(" + output + ")" : "-" + output;
		}

	return output;
}

function strip(input, chars) {    // strip all characters in 'chars' from input
	var output = "";  // initialise output string
	for (var i=0; i < input.length; i++){
		if (chars.indexOf(input.charAt(i)) == -1) output += input.charAt(i);
	}
	return output;
}

function separate(input, separator) {  // format input using 'separator' to mark 000's
	input = "" + input;
	var output = "";  // initialise output string
	for (var i=0; i < input.length; i++) {
		if (i != 0 && (input.length - i) % 3 == 0) output += separator;
		output += input.charAt(i);
	}
	return output;
}


