/*
This is a library of functions that can validate:
Dates
Email
Zipcode
Integers
SSN's
TaxID's
PhoneNumber

Also formating of fields onChange:
TrimWhitespace
Zipcode
SSN
TaxID
Phonenumber

*/


/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate2(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

// HISTORY
// ------------------------------------------------------------------
// May 17, 2003: Fixed bug in parseDate() for dates <1970
// March 11, 2003: Added parseDate() function
// March 11, 2003: Added "NNN" formatting option. Doesn't match up
//                 perfectly with SimpleDateFormat formats, but 
//                 backwards-compatability was required.

// ------------------------------------------------------------------
// These functions use the same 'format' strings as the 
// java.text.SimpleDateFormat class, with minor exceptions.
// The format string consists of the following abbreviations:
// 
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
//              | NNN (abbr.)        |
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Day of Week  | EE (name)          | E (abbr)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | a                  |
//
// NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
// Examples:
//  "MMM d, y" matches: January 01, 2000
//                      Dec 1, 1900
//                      Nov 20, 00
//  "M/d/yy"   matches: 01/20/00
//                      9/2/00
//  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
// ------------------------------------------------------------------

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x) {return(x<0||x>9?"":"0")+x}

// ------------------------------------------------------------------
// isDate ( date_string, format_string )
// Returns true if date string matches format of format string and
// is a valid date. Else returns false.
// It is recommended that you trim whitespace around the value before
// passing it to this function, as whitespace is NOT ignored!
// ------------------------------------------------------------------
function isDate(val,format) {
	var date=getDateFromFormat(val,format);
	if (date==0) { return false; }
	return true;
	}

// -------------------------------------------------------------------
// compareDates(date1,date1format,date2,date2format)
//   Compare two date strings to see which is greater.
//   Returns:
//   1 if date1 is greater than date2
//   0 if date2 is greater than date1 of if they are the same
//  -1 if either of the dates is in an invalid format
// -------------------------------------------------------------------
function compareDates(date1,dateformat1,date2,dateformat2) {
	var d1=getDateFromFormat(date1,dateformat1);
	var d2=getDateFromFormat(date2,dateformat2);
	if (d1==0 || d2==0) {
		return -1;
		}
	else if (d1 > d2) {
		return 1;
		}
	return 0;
	}

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}
	
// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
	}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
	}
	
// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=1;
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";
	
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				}
			}
		else if (token=="MMM"||token=="NNN"){
			month=0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					if (token=="MMM"||(token=="NNN"&&i>11)) {
						month=i+1;
						if (month>12) { month -= 12; }
						i_val += month_name.length;
						break;
						}
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="EE"||token=="E"){
			for (var i=0; i<DAY_NAMES.length; i++) {
				var day_name=DAY_NAMES[i];
				if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
					i_val += day_name.length;
					break;
					}
				}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;hh--;}
		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return 0; }
			}
		else { if (date > 28) { return 0; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return 0; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh=hh-0+12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	var newdate=new Date(year,month-1,date,hh,mm,ss);
	return newdate.getTime();
	}

// ------------------------------------------------------------------
// parseDate( date_string [, prefer_euro_format] )
//
// This function takes a date string and tries to match it to a
// number of possible date formats to get the value. It will try to
// match against the following international formats, in this order:
// y-M-d   MMM d, y   MMM d,y   y-MMM-d   d-MMM-y  MMM d
// M/d/y   M-d-y      M.d.y     MMM-d     M/d      M-d
// d/M/y   d-M-y      d.M.y     d-MMM     d/M      d-M
// A second argument may be passed to instruct the method to search
// for formats like d/M/y (european format) before M/d/y (American).
// Returns a Date object or null if no patterns match.
// ------------------------------------------------------------------
function parseDate(val) {
	var preferEuro=(arguments.length==2)?arguments[1]:false;
	generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');
	monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d');
	dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');
	var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');
	var d=null;
	for (var i=0; i<checkList.length; i++) {
		var l=window[checkList[i]];
		for (var j=0; j<l.length; j++) {
			d=getDateFromFormat(val,l[j]);
			if (d!=0) { return new Date(d); }
			}
		}
	return null;
	}




function emailCheck (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 email address username doesn't seem to be valid. Please Check.")
    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("The email destination IP address is invalid! Please Check.")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("The domain of your email address name doesn't seem to be valid. Please check your email address before continuing.")
    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>4) {
   // the address must end in a two letter or three letter word.
   alert("The email 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 email address is missing a hostname!"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}


/**
 * DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters;
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone){
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length == minDigitsInIPhoneNumber);
}

function SSNValidation(ssn) {
var matchArr = ssn.match(/^(\d{3})-?\d{2}-?\d{4}$/);
var numDashes = ssn.split('-').length - 1;
	if (matchArr == null || numDashes == 1) {
		alert('Invalid SSN. Must be 9 digits in the ###-##-#### format.');
		msg = "does not appear to be valid";
		return false;
	}
	else 
		if (parseInt(matchArr[1],10)==0) {
			alert("Invalid SSN: SSN's can't start with 000.");
			msg = "does not appear to be valid";
			return false;
		}
		else {
	   }
 return true;	   
}

function validateZIP(field) {
var valid = "0123456789-";
var hyphencount = 0;

	if (field.length!=5 && field.length!=10) {
		alert("Please enter 5 digit or 5 digit+4 zip code.");
		return false;
	}
	for (var i=0; i < field.length; i++) {
	temp = "" + field.substring(i, i+1);
		if (temp == "-") hyphencount++;
		if (valid.indexOf(temp) == "-1") {
			alert("Invalid characters in zip code. Please try again.");
			return false;
		}
		if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
			alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'. Please try again.");
			return false;
	   }
	}
}

//Used onload to set elements for onblur formating
function InitPage()
{
        ME=document.forms[0];
        ME.elements[0].focus();
} 



//New validate SSN or TaxID function
function ValSSN(ctl, num, desc, fReq )
{
        rTxt = "";
        if( eval(ctl) )
        {
          ssn = GetNumbers(ctl.value);
          if( ssn == "" )
          {
            if (fReq)
              rTxt = desc + " is blank";
          }
          else
          {
            if( !IsNumStr(ssn) )
                rTxt = desc + " has invalid characters.";
            else if(ssn.length != num)
                rTxt = desc + " must be " + num + " digits long.";
          }
        }

        if (rTxt!="")
          rTxt = A1+(ctl.name)+Foc + rTxt + A2;
}

//Need this for new functiona
function IsNumStr(s)
{
        return !s.match(/\D/);
}

//Check to see if it is a white space for the trimwhitespace
function IsWhiteSpace( c )
{
        return( (' ' == c) || ('\t' == c) || ('\n' == c) );
}

// This function trims whitespace from the beginning and end of a string.
function trimwhitespace( Ctrl )
{
        var index;
        var end;
        var result = Ctrl.value;

        if( result.length == 0 )
                return;

        // Trim the rightside
        index = result.length-1;
        while( index >= 0 )
        {
                // If it's not whitespace we're done
                if( IsWhiteSpace(result.charAt(index)) )
                        index -= 1;
                else
                        break;
        }

        end = index+1;
        index = 0;

        if( end > 0 )
        {
                // Trim the left side
                while( index < result.length )
                {
                        // If it's not whitespace we're done
                        if( IsWhiteSpace(result.charAt(index)) )
                                index += 1;
                        else
                        break;
                }
        }

        Ctrl.value = result.substring( index, end );
}

//Gets all the numbers out of a field to do formatting
function GetNumbers(dt)
{
        numbers = dt.replace( /[^0-9]/g, "" );
        return numbers;
}

//Formats SSN onblur
function FormatSSN(Ctrl)
{
        trimwhitespace( Ctrl );
        var SSN = GetNumbers( Ctrl.value );
        Ctrl.value = "";

        // Keep us from going too far...
        if( SSN.length > 9 )
                SSN = SSN.substring(0, 9);

        if( SSN.length >= 3 )
        {
                Ctrl.value = SSN.substring(0,3) + "-";
                SSN = SSN.substring(3, SSN.length);

                if( SSN.length >= 2 )
                        Ctrl.value += SSN.substring(0,2) + "-";
                SSN = SSN.substring(2, SSN.length);
        }

        Ctrl.value += SSN;
}


function CheckEmail(Ctrl){
	var email = Ctrl.value
	if (email.indexOf("@")<2)
		{
		alert("Please make sure you have typed your email address correctly. Please check the prefix and the '@' sign.");
		return false;
		}
	//var At 
	//var SubAt
	//var LenEmail
	//At = (email.indexOf("@")+2);
	//LenEmail = email.length;
	//SubAt = email.substring(At,LenEmail);
	//if (!(SubAt.indexOf(".")>=0))
		//{
		//alert("Please make sure you have typed your email address correctly. Please check the suffix and the '.' sign.");
		//return false;
		//}
	var temp
	//Check for blank charaters
	for (var i=0; i < email.length; i++) {
	temp = "" + email.substring(i, i+1);
	 if( IsWhiteSpace(temp) )
              {
		   alert("Please make sure you have typed your email address correctly. Remove all blank characters.");
			return false;
		   }       
	}
}

function FormatPhoneNumber(Ctrl)
{
        trimwhitespace( Ctrl );
        var PhoneNumber = GetNumbers( Ctrl.value );
        Ctrl.value = "";

        // Keep us from going too far...
        if( PhoneNumber.length > 10 )
                PhoneNumber = PhoneNumber.substring(0, 10);

        if( PhoneNumber.length >= 3 )
        {
                Ctrl.value = "(" + PhoneNumber.substring(0,3) + ")";
                PhoneNumber = PhoneNumber.substring(3, PhoneNumber.length);

                if( PhoneNumber.length >= 3 )
                        Ctrl.value += PhoneNumber.substring(0,3) + "-";
                PhoneNumber = PhoneNumber.substring(3, PhoneNumber.length);
        }
		
        Ctrl.value += PhoneNumber;
}

function FormatZip(Ctrl)
{
        trimwhitespace( Ctrl );
        var Zip = GetNumbers( Ctrl.value );
        Ctrl.value = "";

        // Keep us from going too far...
        if( Zip.length > 9 )
                Zip = Zip.substring(0, 9);

        if( Zip.length >= 6 )
        {
                Ctrl.value = Zip.substring(0,5) + "-";
                Zip = Zip.substring(5, Zip.length);
        }

        Ctrl.value += Zip;
}


//Formats Federal Tax ID onblur
function FormatTaxID(Ctrl)
{
        trimwhitespace( Ctrl );
        var SSN = GetNumbers( Ctrl.value );
        Ctrl.value = "";

        // Keep us from going too far...
        if( SSN.length > 9 )
                SSN = SSN.substring(0, 9);

        if( SSN.length >= 2 )
        {
                Ctrl.value = SSN.substring(0,2) + "-";
                SSN = SSN.substring(2, SSN.length);
        }

        Ctrl.value += SSN;
}



//Need this global so it can be closed by closeDep()
var win

var isMac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;
var Emac = ((document.all)&&(isMac)) ? true : false;


//centered popup
function NewWindow(mypage, myname, w, h, scroll) {
	if (!isMac && !Emac){
		closeDep()
	}
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable=yes'
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

//top left popup
function popUp(mypage, myname, w, h, scroll){
	if (!isMac && !Emac){
		closeDep()
	}
	winprops = 'height='+h+',width='+w+',top=50,left=50,scrollbars='+scroll+',resizable'
    win = window.open(mypage, myname, winprops);
} 

//Close popup
function closeDep(){
	if (!isMac && !Emac){
		if (win && win.open && !win.closed) win.close();
	}
	
}


function validRequired(formField,fieldLabel)
{
	var result = true;
	
	if (formField.value == "")
	{
		alert('Please enter a value for the "' + fieldLabel +'" field.');
		formField.focus();
		result = false;
	}
	
	return result;
}


function allDigits(str)
{
	return inValidCharSet(str,"0123456789");
}

function inValidCharSet(str,charset)
{
	var result = true;
	
	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0)
		{
			result = false;
			break;
		}
	
	return result;
}

function isValidExpDate(formField,fieldLabel,required)
{
	var result = true;
	var formValue = formField;

	if (required && !validRequired(formField,fieldLabel))
		result = false;
  
 	if (result && (formField.length>0))
 	{
 		var elems = formValue.split("/");
 		
 		result = (elems.length == 2); // should be two components
 		var expired = false;
 		
 		if (result)
 		{
 			var month = parseInt(elems[0],10);
 			var year = parseInt(elems[1],10);
 			
 			if (elems[1].length == 2)
 				year += 2000;
 			
 			var now = new Date();
 			
 			var nowMonth = now.getMonth() + 1;
 			var nowYear = now.getFullYear();
 			
 			expired = (nowYear > year) || ((nowYear == year ) && (nowMonth > month));
 			
			result = allDigits(elems[0]) && (month > 0) && (month < 13) &&
					 allDigits(elems[1]) && ((elems[1].length == 2) || (elems[1].length == 4));
 		}
 		
  		if (!result)
 		{
 			alert('Please enter a date in the format MM/YY for the "' + fieldLabel +'" field.');
			
		}
		else if (expired)
		{
 			result = false;
 			alert('The date for "' + fieldLabel +'" has expired.');
			
		}
	} 
	
	return result;
}

function isValidCreditCardNumber(formField,ccType,fieldLabel,required)
{
	var result = true;
 	var ccNum = formField.value;

	if (required && !validRequired(formField,fieldLabel))
		result = false;
 
  	if (result && (formField.value.length>0))
 	{ 
 		if (!allDigits(ccNum))
 		{
 			alert('Please enter only numbers (no dashes or spaces) for the "' + fieldLabel +'" field.');
			formField.focus();
			result = false;
		}	

		if (result)
 		{ 
 			
 			if (!LuhnCheck(ccNum) || !validateCCNum(ccType,ccNum))
 			{
 				alert('Please enter a valid card number for the "' + fieldLabel +'" field.');
				formField.focus();
				result = false;
			}	
		} 

	} 
	
	return result;
}

function LuhnCheck(str) 
{
  var result = true;

  var sum = 0; 
  var mul = 1; 
  var strLen = str.length;
  
  for (i = 0; i < strLen; i++) 
  {
    var digit = str.substring(strLen-i-1,strLen-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) != 0)
    result = false;
    
  return result;
}



function GetRadioValue(rArray)
{
	for (var i=0;i<rArray.length;i++)
	{
		if (rArray[i].checked)
			return rArray[i].value;
	}
	
	return null;
}


function validateCCNum(cardType,cardNum)
{
	var result = false;
	cardType = cardType.toUpperCase();
	
	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first4digs = cardNum.substring(0,4);

	switch (cardType)
	{
		case "VISA":
			result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4");
			break;
		case "AMEX":
			var validNums = "47";
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case "MC":
			var validNums = "12345";
			result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0);
			break;
		case "DISC":
			result = (cardLen == 16) && (first4digs == "6011");
			break;
		case "DINERS":
			var validNums = "068";
			result = (cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
	}
	return result;
}

function CheckCard(Name,CardType,CardNumber,expmonth,expyear,cvv){
	if(Name.value==""){
		alert("You must enter credit card name.");
		Name.focus();
		return false;
	}
	if(CardType.value==""){
		alert("You must select a credit card type.");
		CardType.focus();
		return false;
	}
	if(CardNumber.value==""){
		alert("You must enter a credit card number.");
		CardNumber.focus();
		return false;
	}
	if (!isValidCreditCardNumber(CardNumber,CardType.value,"Credit Card Number",true)){
		CardNumber.focus()
		return false;
	}
	if(expmonth.value==""){
		alert("You must select a credit card expiration month.");
		expmonth.focus();
		return false;
	}
	if(expyear.value==""){
		alert("You must select a credit card expiration year.");
		expyear.focus();
		return false;
	}
	//create MM/YY string from 2 drop down date fields
	var ExpDate = expmonth.value+"/"+expyear.value;
	if (!isValidExpDate(ExpDate,"Card Expiration",true)){
		expmonth.focus()
		return false;
	}
	
	
	var SecurityLength;
	
	if(CardType.value.toUpperCase() != "AMEX"){
		SecurityLength = 3;
	}else{
		SecurityLength = 4;
	}
	
	if(cvv.value == ""){
		alert("You must enter the credit card "+SecurityLength+" digit security code other wise known as the CID. ");
		cvv.focus();
		return false;
	}
	
	if(!isInteger(cvv.value)){
		alert("You can only enter digits for your card security code or CID.");
		cvv.value = "";
		cvv.focus();
		return false;
	}
	
	if(cvv.value.length != SecurityLength){
		alert("Your card security code or CID must be "+SecurityLength+" digits long.");
		cvv.focus();
		return false;
	}
	
	return true;
}

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 ValidateDecimal(num,field){
	nv=/^\s*\d+\.?\d{0,2}\s*$/; //Reg Exp for money decimal format
	if (!num.match(nv)){
		alert("You can only enter "+field+" in number formats i.e. 7.0 or 7");
		return false;
	}
	return true;
}

//This is a credit card mod 10 validator that does not require card type
function checkCC(s) {

  var i, n, c, r, t;

  // First, reverse the string and remove any non-numeric characters.

  r = "";
  for (i = 0; i < s.length; i++) {
    c = parseInt(s.charAt(i), 10);
    if (c >= 0 && c <= 9)
      r = c + r;
  }

  // Check for a bad string.

  if (r.length <= 1)
    return false;

  // Now run through each single digit to create a new string. Even digits
  // are multiplied by two, odd digits are left alone.

  t = "";
  for (i = 0; i < r.length; i++) {
    c = parseInt(r.charAt(i), 10);
    if (i % 2 != 0)
      c *= 2;
    t = t + c;
  }

  // Finally, add up all the single digits in this string.

  n = 0;
  for (i = 0; i < t.length; i++) {
    c = parseInt(t.charAt(i), 10);
    n = n + c;
  }

  // If the resulting sum is an even multiple of ten (but not zero), the
  // card number is good.

  if (n != 0 && n % 10 == 0)
    return true;
  else
    return false;
}

function submitOnce(formName) 
{ 
    this.formName=(formName) ? formName:0; 

    if (document.forms && document.getElementsByTagName) 
    { 
        var subFields=eval('document.forms["'+this.formName+'"].getElementsByTagName("input");'); 

        var subFieldsLen=subFields.length; 
        for (k=0; k<subFieldsLen; k++) 
        { 
            if (subFields[k].getAttribute("type").toLowerCase() == "submit") subFields[k].disabled=true; 
            if (subFields[k].getAttribute("type").toLowerCase() == "reset") subFields[k].disabled=true; 
        } 
    } 
} 




/******************************************************* 
SELECT ALL (HIGHLIGHT FIELD) 
*******************************************************/ 
function selectAll(formField) 
{ 
    temp=eval(formField); 
    temp.focus(); 
    temp.select(); 
} 




/******************************************************* 
SINGLE-SELECT CHECKBOXES 
This gives checkboxes the "one-at-a-time" functionality of radio buttons. 
*******************************************************/ 
function radioButton(formName) 
{ 
    this.formName=(formName) ? formName:0; 
     
    this.select=function(what) 
    { 
        if (document.forms && document.getElementsByTagName) 
        { 
            var raFields=eval('document.forms["'+this.formName+'"].getElementsByTagName("input");'); 

            var raFieldsLen=raFields.length; 
            for (i=0; i<raFieldsLen; i++) 
            { 
                if (raFields[i].getAttribute("type").toLowerCase() == "checkbox") raFields[i].checked=false; 
                what.checked=true; 
            } 
        } 
    } 
} 



/******************************************************* 
CHECKBOXES 
By Ryan Parman 
- Click and Drag functionality by Peter Bailey, http://www.peterbailey.net 
- Must be initialized as an object, then (optionally) attach an onload to the BODY tag, 
      either objName.enableMouseover(), or objName.enableClickDrag(), but not both. 
- Use objName.check(), objName.clear(), or objName.toggle(). 
*******************************************************/ 
function checkbox(nameOfForm) 
{ 
    // Store variables. 
    this.nameOfForm=(nameOfForm) ? nameOfForm:0; 
    this.toggleOnOff=1; 

    // Can be used externally, but meant for internal use only. 
    this.set=function(bool) 
    { 
        if (document.forms && document.getElementsByTagName) 
        { 
            var theFields=eval('document.forms["'+this.nameOfForm+'"].getElementsByTagName("input");'); 

            var theFieldsLen=theFields.length; 
            for (i=0; i<theFieldsLen; i++) 
            { 
                if (theFields[i].getAttribute("type").toLowerCase() == "checkbox") theFields[i].checked=bool; 
            } 
        } 
        else alert('Not Supported'); 
    } 

    // Basic functions to use externally. 
    this.check=function() { this.set(true); } 
    this.clear=function() { this.set(false); } 

    // Just a nifty little feature. 
    this.toggle=function() 
    { 
        if (this.toggleOnOff) { this.set(true); this.toggleOnOff=0; } 
        else if (!this.toggleOnOff) { this.set(false); this.toggleOnOff=1; } 
    } 

    // Call this during BODY onLoad to add mouseover functionality to the form. 
    this.enableMouseover=function() 
    { 
        if (document.forms && document.getElementsByTagName) 
        { 
            var moFields=eval('document.forms["'+this.nameOfForm+'"].getElementsByTagName("input");'); 

            var moFieldsLen=moFields.length; 
            for (i=0; i<moFieldsLen; i++) 
            { 
                if (moFields[i].getAttribute("type").toLowerCase() == "checkbox") 
                { 
                    onMO=moFields[i]; 
                    onMO.onmouseover=this.change; 
                } 
            } 
        } 
    } 

    this.change=function() { this.checked=(this.checked) ? false:true; } 

    // By Peter Bailey, www.peterbailey.net 
    // Slight modifications by Ryan Parman, www.skyzyx.com 
    this.enableClickDrag=function(sameNameOnly) 
    { 
        // Abort if browser can't do script 
        if (document.all && !document.attachEvent) return true; 
        else if (!document.all && !document.addEventListener) return true; 
        //else if (document.all && !document.addEventListener) return true; // For retarded-ass Opera 7... 

        // Initialize Variables/properties 
        var f=eval('document.forms["'+this.nameOfForm+'"]'); 
        var dragObj=this; 
        this.checked=false; 
        this.mousedown=false; 
        this.validClick=false; 
        this.same=Boolean( sameNameOnly ); 

        // Attach Events 
        if ( document.attachEvent ) 
        { 
            f.attachEvent( "onmousedown", function() { downHandler( event.srcElement, dragObj ) } ); 
            f.attachEvent( "onmouseover", function() { overHandler( event.srcElement, dragObj ) } ); 
            document.attachEvent( "onmouseup", function() { upHandler( event.srcElement, dragObj ) } ); 
        } 
        else 
        { 
            f.addEventListener( "mousedown", function( e ) { downHandler( e.target, dragObj ) }, false ); 
            f.addEventListener( "mouseover", function( e ) { overHandler( e.target, dragObj ) }, false ); 
            document.addEventListener( "mouseup", function( e ) { upHandler( e.target, dragObj ) }, false ); 
        } 

        // Handler for form.onMouseDown event 
        function downHandler(elem, o) 
        { 
            if (elem.type=="checkbox") 
            { 
                o.validClick=true; 
                o.firstCB=elem; 
                o.mousedown=true; 
                o.checked=!elem.checked 
                if (o.same) o.name=elem.name; 
            } 
        } 

        // Handler for document.onMouseUp event 
        function upHandler(elem, o) 
        { 
            if (o.validClick && o.firstCB) 
            { 
                o.firstCB.checked=o.checked; 
                o.mousedown=false; 
                o.checked=!o.checked; 
                o.validClick=false; 
                if (elem===o.firstCB) elem.checked=o.checked; 
            } 
        } 

        // Hanlder for form.onMouseOver event 
        function overHandler(elem, o) 
        { 
            if (elem.type=="checkbox" && o.mousedown) 
            { 
                if (o.same && elem.name == o.name) elem.checked=o.checked; 
                else if (!o.same) elem.checked=o.checked; 
            } 
        } 
    } 
} 

	function HideEmail(email,emailHost,contact,subject){
			if(contact == ""){
				contact = email + "@" + emailHost;
			}
			if(subject != ""){
				subject = "?subject=" + subject; 
			}
			document.write("<a href=" + "mail" + "to:" + email + "@" + emailHost + subject + ">" + contact + "</a>");
		
		}

//This selects a dropdown item given the [form].[element].options and the text of the option to select
function SelectOption(output,selecttext){
	  for(var i=0;i<output.length;i++) {
		if(output[i].text==selecttext){
		  output[i].selected=true;
		}
	 }
}
