/** 2000 **/
// List of enterable states
states = new Array('AK','AL','AR','AZ','CA','CO','CT','DC','DE','FL','GA','HI','IA','ID','IL','IN','KS','KY','LA','MA','MD','ME','MI','MN','MO','MS','MT','NC','ND','NE','NH','NJ','NM','NV','NY','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VA','VT','WA','WI','WV','WY');

/*	UTILITY FUNCTIONS	*/
// Method to place focus
function putFocus(obj) { if(window.focus)obj.focus() }

// Method to select text within field object
function putSelection(obj) {
	putFocus(obj);
	if(obj.select)obj.select();
}

// Method to return the value of a form object or string
function getValue(obj) {
	if (typeof obj=="object") { return obj.value; }
	return obj;
}

// Method to check if a string is blank - white spaces considered blanks
function isBlanks(e) {
	if (e.length==0) { return true }
	for (var i=0; i<e.length; i++) {
		if (e.charAt(i)!=" ") { return false } //Make sure each char is not white space
    }
	return true;
}

// Method to check if values of drop list form are blank
function isBlank(e) {
     var msg = "";
     for (var i = 0;i< e.length;i++)
     {
        var f = e.elements[i];
        if (f.type == "select-one") {
           if (f.selectedIndex <= 0)
           {
                msg += "Please select a "+f.name+"\n";
           }
        }
     }
     if (msg)
     {
         alert(msg);
         return false;
     }

}

// Method to check if values of zip code text box form are blank
function isBlankt(e) {
     var msg = "";
     for (var i = 0;i< e.length;i++)
     {
        var f = e.elements[i];
        if (f.value== "") {
                msg += "Please enter a "+f.name+" code\n";
         }
     }
     if (msg)
     {
         alert(msg);
         return false;
     }
}

// Method to remove dashes from a string
// Parameter: string
function removeDashes(str) {
	newStr="";
	isDash=str.indexOf('-');
	if (isDash!=-1) {
		beg=str.substring(0,isDash);
		end=str.substring(isDash+1,str.length);
		newStr=beg+""+end;
		if(newStr.indexOf('-')!=-1)removeDashes(newStr);
	}
	else {
		newStr=str;
	}
	return newStr;
}

// Method to trim white space from a string
// Parameters:
//	-form object or string
//	-direction: "left|right|all"
// If dir not specified, routine trims both left and right sides only
function trim(str,dir) {
	end=0;
	begin=0;
	newStr="";
	currStr=getValue(str);
	chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ*(+\\&!$);-/,%_><?.:#@\'=\"';

	if (!isBlanks(currStr)) {
		// loop forward through all the characters in the string
		for(var i=0; i<currStr.length; i++) {
			// see if this input character is blank or not an EBCDIC character
			if(chars.indexOf(currStr.charAt(i))!=-1) {
				// found the first non-blank character, note it and break from this loop
				begin=i;
				break;
			}
		}
	// loop backwards through the string
		for(var j=currStr.length-1; j>0; j--) {
		// see if string is blank or not an EBCDIC char
			if(chars.indexOf(currStr.charAt(j))!=-1) {
			// found the last non-blank character, note it and break
				end=j;
				break;
			}
		}
	// if direction is specified
		if (dir!=null && dir!="") {
			dir = dir.charAt(0).toUpperCase();

		// trim the right side only
			if (dir=="R") { newStr=currStr.substring(0,end+1) }

		// trim the left side only
			else if (dir=="L") { newStr=currStr.substring(begin,currStr.length) }

		// trim all spaces
			else if (dir=="A") {
			  // if there are white spaces
				if(currStr.indexOf(" ")!=-1) {
					n = currStr.indexOf(" ");
					strEnd = currStr.substring(n+1,end+1);
					newStr=currStr.substring(begin,n)+strEnd;
				// trim again if more spaces found
					if(newStr.indexOf(" ")!=-1)trim(newStr,dir);
				}
				else if (currStr.indexOf(' ')==-1) {
					newStr=currStr.substring(begin,end+1);
				}
			}
		}
	// or just trim both sides
		else { newStr=currStr.substring(begin,end+1) }
	}
	return newStr;
}
/*	END UTILITY FUNCTIONS	*/


/*	VALIDATION FUNCTIONS	*/

// Check if pull-down is selected
// Parameters:
//	-form field object,
//	-field name description,
//	-minimum index to be selected (first option index is 0)
function isSelected(obj,str,min) {
    if(obj.selectedIndex < min)	{
		alert("Please select a value for "+str);
		putFocus(obj)
		return false;
	}
	return true;
}

// Check if element is an Alpha character
// Parameters:
//	-form field object,
//	-field name description,
//	-spaces allowed (true|false),
//	-dashes and dots allowed (true|false),
//	-is field required (true|false)
function isAlpha(e,msg,spaces,dotsNdashes,isRequired) {
	s=(spaces)?" ":"";
	d=(dotsNdashes)?"-.,":"";
	alpha="abcdefghijklmnopqrstuvwxyz"+s+d;
	objVal=getValue(e);
	// if field required and blank
	if (isBlanks(objVal) && isRequired) {
		alert("Your "+msg+" is required");
		e.value="";
		putFocus(e);
		return false;
	}
	else if (isBlanks(objVal) && !isRequired) { return true; }
	// test for non-alpha chars
	//for (var i=0; i<objVal.length; i++) {
	//	temp=objVal.toLowerCase().substring(i,i+1);
	//	if (alpha.indexOf(temp)==-1) {
	//		alert("The "+msg+" field has an invalid character: "+objVal.substring(i,i+1));
	//		putSelection(e);
	//		return false;
	//	}
	//}
	//trim field
	e.value=trim(e);
	return true;
}

// Check if element is Numeric character
// Parameters:
//	-form field object,
//	-field name description,
//	-minimum amount numbers allowed,
//	-maximum amount numbers allowed,
//	-field name description,
//	-spaces allowed (true|false),
//	-dashes and parentheses allowed (true|false),
//	-is field required (true|false)
function isNumeric(obj,msg,min,max,spaces,dashParens,isRequired) {
	s=(spaces)?" ":"";
	d=(dashParens)?"(-)":"";
	digits="0123456789"+s+d;
    objVal=getValue(trim(obj));
	// is blank and required
	if (isRequired && isBlanks(objVal)) {
		alert("The "+msg+" field must have at least "+min+" numbers");
		obj.value="";
		putFocus(obj);
		return false;
	}
	else if (!isRequired && isBlanks(objVal)) { return true }
	// is meeting max/min requirements
	if (objVal.length<min || objVal.length>max) {
		minmax=(min==max)?max:"between "+min+"-"+max;
		alert("The "+msg+" field must be "+minmax+" characters long");
		putSelection(obj);
		return false;
	}
	// make sure chars are numeric
	for (var i=0; i<objVal.length; i++) {
		temp=objVal.substring(i,i+1);
		if (digits.indexOf(temp)==-1) {
			alert("The "+msg+" field has an invalid number: "+objVal.substring(i,i+1));
			putSelection(obj);
			return false;
		}
	}
	//trim field
	obj.value=trim(obj);
	return true;
}

// Check if element is valid State
// Parameters:
//	-form object,
//	-is field required (true|false)
function isState(e,isRequired) {
	isSt8=false;
	st8 = getValue(trim(e));
	// make sure filed is alpha
	if (!isAlpha(e,"State",false,false,isRequired)) { return false }
	if (isBlanks(st8) && !isRequired) { return true }

	//only valid if 2 chars that match state array
	if (st8.length==2) {
		for(n=0; n<states.length; n++) {
			if(st8.toUpperCase() == states[n]) { isSt8=true; break; }
		}
	}
	if (!isSt8) {
		alert("Invalid State");
		putSelection(e);
		return false;
	}
	//capitalize valid state
	e.value=e.value.toUpperCase();
	return true;
}

// Check if element is email address
// Parameters:
//	-form field object
function isEmail(e) {
	email = getValue(e);
	//don't allow blank entries
	if (isBlanks(email)) {
		alert("Please supply your E-mail");
		e.value="";
		putFocus(e);
		return false;
	}
	// make sure field contains and '@' and a '.'
	else if (email.indexOf('@')!=-1 && email.indexOf('.')!=-1) {
		// make sure the '@' is before the last occurence of the '.'
		if (email.indexOf('@') > email.lastIndexOf('.')) {
			alert("Invalid E-mail address");
			putSelection(e);
			return false;
		}
		else if (email.lastIndexOf('.') > email.indexOf('@')) {
			e.value=trim(e);
			return true;
		}
	}
	alert("Invalid E-mail address");
	putSelection(e);
	return false;
}

// Check if element follows credit card format
// Parameters:
//	-cardNum: entered card number
//	-cardType: card type selection list form element
function isCredit(cardNum,cardType) {
	val=getValue(cardNum);
	newVal=removeDashes(val); 	// remove any dashes
	newVal=trim(newVal,"all"); 	// trim all white spaces
	cardNum.value=newVal; 		// reset field w/trimmed contents

	// make sure card # is a number
	if (!isNumeric(cardNum,"Credit Card Number",13,16,false,false,true)) { return false }

	// make sure card value is mod10 checksum
	checkSum=0;
	cardVal=cardNum.value;
	oddoeven=cardVal.length & 1;
	for (n=0; n<cardVal.length; n++) {
		digit = parseInt(cardVal.charAt(n));
		if (!((n & 1) ^ oddoeven)) {
			digit *= 2;
			if (digit>9)digit-=9;
		}
		checkSum += digit;
	}
	if ((checkSum % 10) != 0) {
		alert("Invalid Credit Card Number");
		putSelection(cardNum);
		return false;
	}
	card=cardType.options[cardType.selectedIndex].text;
	cardID=card.charAt(0).toUpperCase();

	// specific card specs
	if (cardID=="V") {
		ccPrefx="4"; count=1;
		if (cardVal.length != 13 && cardVal.length != 16) {
			alert("Invalid "+card+" Card");
			putSelection(cardNum);
			return false;
		}
	}
    if (cardID=="M") { ccLen=16; count=2; ccPrefx=new Array("51","52","53","54","55"); }
    if (cardID=="A") { ccLen=15; count=2; ccPrefx=new Array("34","37"); }
    if (cardID=="D") { ccLen=16; count=4; ccPrefx="6011"; }

	// test card number against card specs
	if (cardID!="V") {
		if (cardVal.length != ccLen) {
			alert("Invalid "+card+" Card");
			putSelection(cardNum);
			return false;
		}
	}
	if (cardID=="V"||cardID=="D") {
		if (cardVal.substring(0,count) != ccPrefx) {
			alert("Invalid "+card+" Card");
			putSelection(cardNum);
			return false;
		}
	}
	if (cardID=="M"||cardID=="A") {
		for (i=0; i<ccPrefx.length; i++) {
			if (cardVal.substring(0,count)==ccPrefx[i]) { return true }
		}
		alert("Invalid "+card+" Card");
		putSelection(cardNum);
		return false;
	}
	return true;
}

// Check if month, day and year fields follow mmddyyyy date format
// Parameters:
//	-m: month field object
//	-d: day field object
//	-y: year field object
//  -cutOff: year integer which is too low to be acceptable
function isDate(m,d,y,cutOff) {
	//Make sure they're numbers
	if (!isNumeric(m,"Month",1,2,false,false,true)) { return false }
	if (!isNumeric(d,"Day",1,2,false,false,true)) { return false }
	if (!isNumeric(y,"year",4,4,false,false,true)) { return false }

	month=getValue(m); day=getValue(d);	year=getValue(y);
	// validate month
	if(month<1 || month>12){
		alert("The month is out of range");
		putSelection(m);
		return false;
	}

	// add leading zeros to month/day below 10
	if (month.length<2 && (parseInt(month)<10 && parseInt(month)!=0)) {
		month="0"+month;
	}
	if (day.length<2 && (parseInt(day)<10 && parseInt(day)!=0)) {
		day="0"+day;
	}

	// validate days based on months with 30 days
	if((month=='09') || (month=='04') || (month=='06') || (month=='11')){
		if(day<1 || day>30) {
			alert("The day is out of range");
			putSelection(d);
			return false;
		}
	}
	// months with 31 days
	else if (month=='01'||month=='03'||month=='05'||month=='07'||month=='08'||month=='10'||month=='12') {
		if(day<1 || day>31) {
			alert("The day is out of range");
			putSelection(d);
			return false;
		}
	}
	// leap year validation
	else if (month=='02') {
		febDay = (isLeapYear(year)) ? 29 : 28;
		if (day<1 || day>febDay) {
			alert("The day is out of range.");
			putSelection(d);
			return false;
		}
	}

	if (parseInt(year)<=cutOff) {
		alert("The year is out of range");
		putSelection(y);
		return false;
	}
	m.value=month;
	d.value=day;
	return true;
}

// Method to check for leap year
// Parameter: 4-digit year
function isLeapYear(yr) {
	if (((yr%4) == 0) && (((yr%100) != 0) || ((yr%400) == 0))) {
		return true;
	}
	return false;
}

// Check if form element is follows drivers license format
// Parameter: form field object
function isLicense(e) {
	dlVal=getValue(e);
	dlVal=removeDashes(dlVal);// remove all dashes
	dlTrim=trim(dlVal,'all'); // trim all white spaces
	// make sure not blank
	if (isBlanks(dlVal)) {
		alert("You must supply a valid Driver's License");
		e.value="";
		putFocus(e);
		return false;
	}
	// test length of license
	if (dlTrim.length<5 || dlTrim.length>20) {
		alert("Invalid Driver's License");
		e.value=dlTrim;
		putSelection(e);
		return false;
	}
	// accept only alpha/numeric chars, and blank spaces
	chars="abcdefghijklmnopqrstuvwxyz1234567890 ";
	for(var i=0; i<dlVal.length; i++) {
		if(chars.indexOf(dlVal.toLowerCase().charAt(i))==-1) {
			alert("Invalid Driver's License character: "+dlVal.charAt(i));
			putSelection(e);
			return false;
		}
	}
	e.value=trim(e,'all');
	return true;
}


