// Form Objects
var formObjects		= new Array();		// Array of Form Objects

// Error Message Variables
var errors			= "";					// Error Message String for Alerts
var language		= new Array();

// Initialize Error Messages
language["header"]	= "The following error(s) occured:"
language["start"]	= "->";
language["field"]	= " ";
language["require"]	= " is required";
language["min"]		= " and must consist of at least ";
language["max"]		= " and must not contain more than ";
language["minmax"]	= " and no more than ";
language["chars"]	= " characters";
language["num"]		= " and must contain a number";
language["dropbox"]	= "Please select ";
language["radio"]	= "Please select ";
language["check"]	= "Please select ";
language["email"]	= " must contain a valid e-mail address";
language["cc"] 		= "Please enter a valid credit card number.\n-> You may have dashes in the field. Be sure to remove them.";

// -----------------------------------------------------------------------------
// define - Call this function in the beginning of the page. I.e. onLoad.
// n = html name of the input field (Required)
// type= string, num, email (Required)
// field=name of input field as it will appear in error messages (Required)
// -----------------------------------------------------------------------------

function define (HTMLname, type, field) {

//value = eval("form[0]." + HTMLname + ".value;");
//alert(value);
n = new formResult(type, HTMLname, field); //,document.forms[0]
formObjects[eval(formObjects.length)] = n;
}


// -----------------------------------------------------------------------------
// define - Validate checks the formObject array for valid data
// -----------------------------------------------------------------------------

function validate (formid) {

if (formObjects.length > 0) {
	errorObject = "";
	for (i = 0; i < formObjects.length; i++) {
	if (formObjects[i] != null) {
		var length = 0;
		var value = "";
		
		validateObject = new Object();
		validateObject.form = formObjects[i].form;
		validateObject.HTMLname = formObjects[i].HTMLname;
		validateObject.Errorname = formObjects[i].Errorname;
		validateObject.type = formObjects[i].type;
	
		switch(validateObject.type) {
		case "string":
			value  =  eval("formid." + validateObject.HTMLname + ".value;");
			length =  eval("formid." + validateObject.HTMLname + ".value.length;");
		break;

		case "block":
			value  =  eval("formid." + validateObject.HTMLname + ".value;");
			length =  eval("formid." + validateObject.HTMLname + ".value.length;");
		break;
	
		case "num": 
		    value  =  eval("formid." + validateObject.HTMLname + ".value;");
			length =  eval("formid." + validateObject.HTMLname + ".value.length;");
		break;
	
		case "select":
			validateObject.index = eval("formid." +  validateObject.HTMLname + ".selectedIndex;");
			value =  eval("formid." + validateObject.HTMLname + "[" + validateObject.index + "].value;");
		break;
	
		case "radio":
			var numChecked=0;
			var num = eval("formid." + validateObject.HTMLname + ".length;");
			var rdo = false;
		
			for (rdoCount=0; rdoCount < num; rdoCount++) {
				rdo = eval("formid." + validateObject.HTMLname + "[" + rdoCount + "].checked")
				if (rdo) {
					numChecked++;
					value = eval("formid." + validateObject.HTMLname + "[" + rdoCount + "].value;");  
				}
			}
			if (numChecked == 0) validateObject.checked = false;
			else validateObject.checked = true;		
		break;
	
		case "check":
			var chk = false;
			chk = eval("formid." + validateObject.HTMLname + ".checked")
			if (chk) {
				validateObject.checked = true;
			}
		break;
	
		case "cc":
			value  =  eval("formid." + validateObject.HTMLname + ".value;");
			length =  eval("formid." + validateObject.HTMLname + ".value.length;");
		break;
		
		case "email":
			value  =  eval("formid." + validateObject.HTMLname + ".value;");
			length =  eval("formid." + validateObject.HTMLname + ".value.length;");
		break;
	}

	validateObject.val = value;
	validateObject.len = length;
	
	//alert("Field: " + validateObject.HTMLname + "\nValue: " + validateObject.val + "\nLength: " + validateObject.len);
		
	if (validateObject.type == "string" || validateObject.type == "num" || validateObject.type == "block") { 
		if ((validateObject.type == "num" && validateObject.len <= 0) || (validateObject.type == "num" && isNaN(validateObject.val))) { errors += language['start'] + language['field'] + validateObject.Errorname + language['require'] + language['num'] + "\n"; }
		if ((validateObject.type == "string" || validateObject.type == "block") && validateObject.len <= 0) { errors += language['start'] + language['field'] + validateObject.Errorname + language['require'] + "\n"; }
		else { if (validateObject.type == "string") changeCase(eval("formid." + validateObject.HTMLname));
		       if (validateObject.type == "block" ) eval("formid." + validateObject.HTMLname); }
		//if ( validateObject.val == "" ) { alert("blank");}			//if ( isNaN(formObjects[i].val)) { alert("number:" + formObjects[i].form.value); }	
		//if ( validateObject.len == "0") { alert("blank"); errors += language['start'] + language['field'] + validateObject.Errorname + language['require'] + language['num'] + "\n"; }
	} 
	if (validateObject.type == "select" && validateObject.index <= 0) { errors += language['start'] + language['field'] + language['dropbox'] + validateObject.Errorname + "\n"; }
	if (validateObject.type == "radio" && !validateObject.checked) { errors += language['start'] + language['field'] + language['dropbox'] + validateObject.Errorname + "\n"; }
	if (validateObject.type == "check" && !validateObject.checked) { errors += language['start'] + language['field'] + language['dropbox'] + validateObject.Errorname + "\n"; }
	if (validateObject.type == "email" && !emailCheck(validateObject.val)) { errors += language['start'] + language['field'] + validateObject.Errorname + language['email'] + "\n"; }
	if (validateObject.type == "cc" && !ccCheck(validateObject.val)) { errors += language['start'] + language['field'] + language['cc'] + "\n"; }
	}
	}
}
if (errors) {
	alert(language["header"].concat("\n" + errors));
	errors = "";
	//returnVal = false;
	return false;
} else { 
	//returnVal = true; 
	return true;
	//formid.submit(); return false;
}
} // end function validate


function formResult(type, HTMLname, field) { //,form
//this.form = form;
this.type = type;
this.HTMLname = HTMLname;
this.Errorname  = field;
}

function undefine(HTMLname){
if (formObjects.length > 0) {
	errorObject = "";
	for (i = 0; i < formObjects.length; i++) {
		if( formObjects[i] != null ) {
		if( formObjects[i].HTMLname == HTMLname ) {
			//formObjects[i].type == "";
			//formObjects[i].HTML == "";
			formObjects[i] = null;
		}
		}
	}
}
}


function setSelect(form, strCaption) {
for (i = 0; i < form.length; i++ ) {
	if ( form[i].value == strCaption ) {
		form[i].selected = true;
		break;
	} 
}
}

function setRadio(form, strValue) {
for (i = 0; i < form.length; i++ ) {
	if ( form[i].value == strValue) {
		form[i].checked = true;
		break;
	} 
}
}

// Email Check Functions

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 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;
}


// Credit Card Validation Functions

function extractDigits(mixedString) {
   var digitsOnly = '';
   var thisDigit = '';
   for (var i = 0; i < mixedString.length; i++) {
      thisDigit = mixedString.charAt(i);
      if (thisDigit >= '0' && thisDigit <= '9')
         digitsOnly = digitsOnly + thisDigit;
   }
   return digitsOnly;
}

function checkMod10(ccNumber) {
   var translateMap = '0246813579';
   var digitSum = 0;
   var translateFlag = ((ccNumber.length % 2) == 0);
   for (var i = 0; i < ccNumber.length; i++) {
       digitSum += parseInt(translateFlag ?
            translateMap.charAt(ccNumber.charAt(i)) :
            ccNumber.charAt(i) , 10)
      translateFlag = !translateFlag;
   }
   return (digitSum % 10) == 0;
}
 

function validCardType(ccNumber) {
   var cardLengths = new Array (
         'v', 13, 'v', 16, 'm', 16,
         'a', 15, 'c', 14, 'd', 16);
   var cardDigits = new Array (
         'v', '4', 'm', '51', 'm', '52', 'm', '53' ,
         'm', '54', 'm', '55', 'a', '34', 'a', '37',
         'c', '300', 'c', '301', 'c', '302', 'c', '303',
         'c', '304', 'c', '305', 'c', '36', 'c', '38',
         'd', '6011');
   var validCard = false;
   var correctLength = false;
   var cardType = '' ;
   for (var i = 0; i < cardDigits.length - 1; i += 2) {
      if (cardDigits[i + 1] == ccNumber.substr(0, cardDigits[i + 1].length)) {
         validCard = true;
         cardType = cardDigits[i];
         break;
      }
   }
   if (validCard) {
      var cardLen = ccNumber.length;
      for (var i = 0; i < cardLengths.length - 1; i += 2) {
         if ((cardType == cardLengths[i]) && (cardLen == cardLengths[i + 1])) {
            correctLength = true;
            break;
         }
      }
      validCard = correctLength;
   }
   return validCard;
}
 
function ccCheck(ccNumber) {
   var ccDigits = extractDigits(ccNumber);
   if (checkMod10(ccDigits) && validCardType(ccDigits)) {
      //alert('Card number valid.');
      return true;
   } else {
      //alert('Invalid credit card number'); 
      return false;
   }
}


//Radio Button Check: Assumes use of radio as a toggle - i.e. use current address or use 
// new address with new text form elements
//
function chkRadioAddress(rdo, num) {

var numChecked=0;

	for (rdoCount=0; rdoCount < num; rdoCount++) {
		if (rdo[rdoCount].checked) { 
			numChecked++;
		} 
	}
	if (numChecked == 0) {
	 	alert ("Please select a billing address");
		return false;
		//errors += language['start'] + language['field'] + rdo.HTMLname + "is required" + "\n";
	}
return true;	
}

function changeCase(frmObj) {
var index;
var tmpStr;
var tmpChar;
var preString;
var postString;
var strlen;
tmpStr = frmObj.value.toLowerCase();
strLen = tmpStr.length;
if (strLen > 0)  {
for (index = 0; index < strLen; index++)  {
if (index == 0)  {
tmpChar = tmpStr.substring(0,1).toUpperCase();
postString = tmpStr.substring(1,strLen);
tmpStr = tmpChar + postString;
}
else {
tmpChar = tmpStr.substring(index, index+1);
if (tmpChar == " " && index < (strLen-1))  {
tmpChar = tmpStr.substring(index+1, index+2).toUpperCase();
preString = tmpStr.substring(0, index+1);
postString = tmpStr.substring(index+2,strLen);
tmpStr = preString + tmpChar + postString;
         }
      }
   }
}
frmObj.value = tmpStr;
}