var nbsp = 160;    // non-breaking space char
var node_text = 3; // DOM text node-type
var emptyString = /^\s*$/
var glb_vfld;      // retain vfld for timer thread

function openPane(myLink,windowName,wi,he) {
    if(! window.focus)return;
    var myWin=window.open("",windowName,"resizable=yes,height="+he+",width="+wi+",left=10,top=10,dependent=yes,scrollbars=yes,");
    myWin.focus();
    myLink.target=windowName;
}

function CapWords(what) {
        var tmpStr, tmpChar, preString, postString, strlen;
        tmpStr = what.value;
        if (tmpStr.match(/[A-Z][A-Z][A-Z]/)) {
                tmpStr = tmpStr.toLowerCase();
        }
        stringLen = tmpStr.length;
        if (stringLen > 0) {
                for (i = 0; i < stringLen; i++) {
                        if (i == 0) {
                                tmpChar = tmpStr.substring(0,1).toUpperCase();
                                postString = tmpStr.substring(1,stringLen);
                                tmpStr = tmpChar + postString;
                        } else {
                                tmpChar = tmpStr.substring(i,i+1);
                                if ((tmpChar == "-" || tmpChar == " ") && i < (stringLen-1)) {
                                        tmpChar = tmpStr.substring(i+1,i+2).toUpperCase();
                                        preString = tmpStr.substring(0,i+1);
                                        postString = tmpStr.substring(i+2,stringLen);
                                        tmpStr = preString + tmpChar + postString;
                                }
                        }
                }
        }
        what.value = tmpStr;
}

function checkOther(which,t) {
	if (t == "") {
		t = "value";
	}
	if (which[which.selectedIndex].value == 'other') {
		var ans = prompt("Please enter other "+t);
		if (ans != "") {
			which[which.selectedIndex].text = ans;
			which[which.selectedIndex].value = ans;
		}
	}
}

function Mod10(ccNumb) {
	var valid = "0123456789"  		// Valid digits in a credit card number
	var len = ccNumb.length;  		// The length of the submitted cc number
	var iCCN = parseInt(ccNumb);  		// integer of ccNumb
	var sCCN = ccNumb.toString();  		// string of ccNumb
	sCCN = sCCN.replace (/^\s+|\s+$/g,'');  // strip spaces
	var iTotal = 0;  			// integer total set at zero
	var bNum = true;  			// by default assume it is a number
	var bResult = false;  			// by default assume it is NOT a valid cc
	var temp;  				// temp variable for parsing string
	var calc;  				// used for calculation of each digit

	// Determine if the ccNumb is in fact all numbers
	for (var j=0; j<len; j++) {
		temp = "" + sCCN.substring(j, j+1);
		if (valid.indexOf(temp) == "-1"){ bNum = false;}
	}

	// if it is NOT a number, you can either alert to the fact, or just pass a failure
	if (!bNum) {
		bResult = false;
	}

	// Determine if it is the proper length 
	if((len == 0)&&(bResult)) {  				// nothing, field is blank AND passed above # check
		bResult = false;
	} else {  						// ccNumb is a number and the proper length - let's see if it is a valid card number
		if(len >= 15) {  					// 15 or 16 for Amex or V/MC
			for(var i=len;i>0;i--) {  				// LOOP throught the digits of the card
				calc = parseInt(iCCN) % 10;  			// right most digit
				calc = parseInt(calc);  				// assure it is an integer
				iTotal += calc;  					// running total of the card number as we loop - Do Nothing to first digit
				i--;  						// decrement the count - move to the next digit in the card
				iCCN = iCCN / 10;                               	// subtracts right most digit from ccNumb
				calc = parseInt(iCCN) % 10 ;    			// NEXT right most digit
				calc = calc *2;                                	// multiply the digit by two

				switch(calc) {
					case 10: calc = 1; break;      			//5*2=10 & 1+0 = 1
					case 12: calc = 3; break;			//6*2=12 & 1+2 = 3
					case 14: calc = 5; break;			//7*2=14 & 1+4 = 5
					case 16: calc = 7; break;			//8*2=16 & 1+6 = 7
					case 18: calc = 9; break;			//9*2=18 & 1+8 = 9
					default: calc = calc;				//4*2= 8 &   8 = 8  -same for all lower numbers
				}                                               
				iCCN = iCCN / 10;  					// subtracts right most digit from ccNum
				iTotal += calc;  					// running total of the card number as we loop
			}  										// END OF LOOP
			if ((iTotal%10)==0) {  					// check to see if the sum Mod 10 is zero
				bResult = true;  					// This IS (or could be) a valid credit card number.
			} else {
				bResult = false;  					// This could NOT be a valid credit card number
			}
		}
	}
	// change alert to on-page display or other indication as needed.
	//if(bResult) {
		//alert("This IS a valid Credit Card Number.");
	//}
	//if(!bResult) {
		//alert("The credit card number you entered \nmay have been input incorrectly.\nPlease re-enter your card number.");
	//}
	return bResult; 					// Return the results
}

function trim(str) {
	return str.replace(/^\s+|\s+$/g, '')
};

function setFocusDelayed() {
	glb_vfld.focus()
}

function setfocus(vfld) {
	// save vfld in global variable so value retained when routine exits
	glb_vfld = vfld;
	setTimeout( 'setFocusDelayed()', 100 );
}

function msg(fld, msgtype, message) {
	// setting an empty string can give problems if later set to a 
	// non-empty string, so ensure a space present. (For Mozilla and Opera one could 
	// simply use a space, but IE demands something more, like a non-breaking space.)
	var dispmessage;
	if (emptyString.test(message)) 
		dispmessage = String.fromCharCode(nbsp);    
	else  
		dispmessage = message;

	if (document.getElementById) {
		var elem = document.getElementById(fld);
		//alert("Element: "+elem);
		if (elem) {
			if (elem.firstChild)
				elem.firstChild.nodeValue = dispmessage;  
			//else alert(fld+" wasn't found in msg()");
			if (elem.className)
				elem.className = msgtype;   // set the CSS class to adjust appearance of message
		}
			//else alert(fld+" was not found in msg()");
	}
};

// -----------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)
// -----------------------------------------

var proceed = 2;  

function commonCheck (vfld, ifld, reqd) {
	if (!document.getElementById) 
		return true;  // not available on this browser - leave validation to the server
	var elem = document.getElementById(ifld);
	if (elem) {
		if (!elem.firstChild)
			return true;  // not available on this browser 
		if (elem.firstChild.nodeType != node_text)
			return true;  // ifld is wrong type of node  
	}
	if (!reqd) return proceed;
		if (emptyString.test(vfld.value)) {
			if (reqd) {
				msg (ifld, "error", "required");  
				setfocus(vfld);
				return false;
			} else {
				msg (ifld, "warn", "");   // OK
				return true;  
			}
		}
	return proceed;
}

// -----------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// -----------------------------------------

function validatePresent(vfld, ifld) {
	var stat = commonCheck (vfld, ifld, true);
	if (stat != proceed) return stat;

	msg (ifld, "warn", "");  
	return true;
};

function validatePass(vfld,v2fld,ifld) {
	if (vfld.value != v2fld.value) {
		//alert("Please confirm your password.");	// Something is wrong here
		msg (ifld, "error", "You must correctly confirm your password.");
		return false;
	} else if (vfld.value == "") {
		msg (ifld, "error", "You must specify a password.");
		return false;
	}

	msg (ifld, "warn", "");  
	return true;
};


// -----------------------------------------
//            validateSelect
// Validate select has value
// Returns true if so 
// -----------------------------------------

function validateSelect (vfld, ifld, other, t) {
	if (t == undefined || t == "") {
		t = "value";
	}
	if (vfld) {
		if (vfld.options[vfld.selectedIndex].value == "" || vfld.options[vfld.selectedIndex].value == "undefined") {
			if (other != "") {
				if (trim(other.value) == "") {
					msg (ifld, "error", "You must select a "+t);  
					return false;
				}
			} else {
				msg (ifld, "error", "You must select a "+t);  
				return false;
			}
		}
	} else {
		alert("Could not find "+vfld);
		return false;
	}
	msg (ifld, "warn", "");
	return true;
};

// -----------------------------------------
//               validateAlias
// Validate if strictalphanum
// Returns true if so (and also if could not be executed because of old browser)
// -----------------------------------------

function validateAlias (vfld, ifld, reqd) {
	var stat = commonCheck (vfld, ifld, reqd);
	if (stat != proceed) return stat;

	var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
	var als = /^[a-zA-Z0-9_-]+$/
	var vet = /^.*myvetra.com\//
	if (vet.test(tfld)) {
		msg (ifld, "warn", "Please leave out the 'myvetra.com\/'");
		tfld = tfld.replace(/^.*myvetra.com\//,"");
		vfld.value = tfld;
	}
	if (!als.test(tfld)) {
		msg (ifld, "error", "not a valid web alias (only letters and numbers)");
		var wrds = vfld.value.split(" ");
		if (wrds.length > 1) {
			var newrd = "";
			for (var i=0; i<wrds.length; i++) {
				newrd += wrds[i].substring(0,1).toUpperCase() + wrds[i].substring(1,wrds[i].length);
			}
			vfld.value = newrd;
		}
		setfocus(vfld);
		return false;
	}
	else
		msg (ifld, "warn", "");
	return true;
};


// -----------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// -----------------------------------------

function validateEmail (vfld, ifld, reqd) {
	var stat = commonCheck (vfld, ifld, reqd);
	if (stat != proceed) return stat;

	var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
	var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
	if (!email.test(tfld)) {
		msg (ifld, "error", "not a valid e-mail address");
		setfocus(vfld);
		return false;
	}

	var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
	if (!email2.test(tfld)) 
		msg (ifld, "warn", "Unusual e-mail address - check if correct");
	else
		msg (ifld, "warn", "");
	return true;
};


// -----------------------------------------
//            validatePhone
// Validate telephone number
// Permits spaces, hyphens, brackets and leading +
// -----------------------------------------

function validatePhone (vfld, ifld, reqd) {
	var stat = commonCheck (vfld, ifld, reqd);
	if (stat != proceed) return stat;
	//alert("["+stat+"]["+proceed+"] Validating Phone");

	var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
	var telnr = /^\+?[0-9 ()-.]+[0-9]$/
	if (!telnr.test(tfld)) {
		msg (ifld, "error", "not a valid telephone number. Characters permitted are digits, space () - . and leading +");
		setfocus(vfld);
		return false;
	}

	var numdigits = 0;
	var digitlist = "";
	for (var j=0; j<tfld.length; j++) {
		if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') {
			digitlist = digitlist + tfld.charAt(j);
			numdigits++;
		}
	}

	if (numdigits<6) {
		msg (ifld, "error", "" + numdigits + " digits - too short");
		setfocus(vfld);
		return false;
	}

	if (numdigits>14)
		msg (ifld, "warn", numdigits + " digits - check if correct");
	else { 
		if (numdigits<10)
			msg (ifld, "warn", "Only " + numdigits + " digits - check if correct");
		else
			msg (ifld, "warn", "");
	}

	if (numdigits==10) {
		vfld.value = "("+digitlist.substring(0,3)+") "+digitlist.substring(3,6)+"-"+digitlist.substring(6);
	}
	return true;
};


// -----------------------------------------
//             validateExpdate
// Validate creditcard's expiration date
// Returns true if OK 
// ExpireMonth
// ExpireYear
// MASTER
// -----------------------------------------

function wipeC(what) {
return;
	//var reggy = /\*/;
	//if (reggy.test(what.form.card_num.value)) {
		//what.form.card_num.value = "";
	//}
	//if (reggy.test(what.form.card_code.value)) {
		//what.form.card_code.value = "";
	//}
}

function checkDt(what) {
return;
	if (what.form.cc_exp_mm.value != "" && what.form.cc_exp_yy.value != "") {
		validateExpdate(what.form.cc_exp_mm.value, what.form.cc_exp_yy.value, 'inf_cc_exp');
	}
}

function validateExpdate (expmm, expyy, ifld) {
	var errors = "";
	var stat = commonCheck (expmm, ifld);
	if (stat != proceed) return stat;
	var mm = trim(expmm.value);
	var yy = trim(expyy.value);
	var numerr = 0;
	var isN=/[0-9]{1,4}/;
	if (!isN.test(yy)) {
		errors = errors + "Year ("+yy+") is invalid.\n";
		numerr++;
	}
	if (!isN.test(mm)) {
		errors = errors + "Month is invalid.\n";
		numerr++;
	}
	
	var now = new Date();
	var yr = now.getFullYear();
	var mo = 1 + now.getMonth();

	if (yy.length < 3) {
		yr -= 2000;
		if (yr == yy) {	
			if (mm < mo) {
				errors += "Must expire in the future.\n";
				numerr++;
			} else {
				// ok here
				msg (ifld, "warn", "");
				return true;
			}
		} else if (yr > yy) {
			errors += "Must expire in the future.\n";
			numerr++;
		} else {
			// ok here
			msg (ifld, "warn", "");
			return true;
		}
	} else if (yy.length < 5) {
		if (yy < yr) {
			errors += "Must expire in the future.\n";
			numerr++;
		} else if (yy == yr) {
			if (mm < mo) {
				errors += "Must expire in the future.\n";
				numerr++;
			} else {
				// okay here
				msg (ifld, "warn", "");
				return true;
			}
		} else if ((yy - yr) > 100) {
			errors += "Number too large.\n";
			numerr++;
		} else {
			// okay here
			msg (ifld, "warn", "");
			return true;
		}
	} else {
		errors += "Number too long.\n";
		numerr++;
	}

	if (numerr) {
		msg(ifld, "error", errors);
		return false;
	}
	msg (ifld, "warn", "");
	return true;
};

// -----------------------------------------
//            validateCheckbox
// Validate that the correct number of checkboxes has been checked.
// Returns true if valid (and also if could not be executed because 
// of old browser)
// -----------------------------------------

function validateCheckbox  (vfld,   // checkboxes to be validated
				ifld,   // id of element to receive info/error msg
				nr,     // number of checkboxes to be checked. >=2
				cond)   // condition: -1 = less than or equal to nr
					//             0 = equal to nr (default)
					//             1 = greater than or equal to nr
{
	if (!nr || nr<2) {
		alert('Programming error in validateCheckbox: nr<2'); 
		// for nr=1 use radio buttons or validateConfirm
		return true;
	}
	if (!cond) cond = 0;

	var stat = commonCheck2(vfld, ifld);
	if (stat != proceed) return stat;

	// count how many boxes have been checked by the reader
	var count = 0;
	for (var j=0; j<vfld.length; j++)
		if (vfld[j].checked) count++;

	if (count==nr) return true;
	if (count<nr && cond==-1) return true;
	if (count>nr && cond==1)  return true;

	// if we get here then the validation has failed

	var suffix='';
	if (count>1) suffix='es';

	var errorMsg;

	if (count<nr) errorMsg = 'Only ' + count + ' box' + suffix + ' checked: ' + nr + ' required';
	if (count>nr) errorMsg = '' + count + ' boxes checked: maximum ' + nr + ' allowed';
	if (count==0) errorMsg = 'No boxes checked: ' + nr + ' required';

	msg (ifld, "error", errorMsg);
	return false;
}


// -----------------------------------------
//            validateConfirm 
// Usually one doesn't want to validate if 1 checkbox of a set has been
// checked, because in this case one would use radio buttons instead.
// But sometimes one wants a reader to check a single box to confirm that 
// he or she agrees to something. That is covered by this routine.
//
// Returns true if valid (and also if could not be executed because 
// of old browser)
// -----------------------------------------

function validateConfirm   (vfld,   // checkbox to be validated
				ifld)   // id of element to receive info/error msg
{
	var stat = commonCheck2(vfld, ifld);
	if (stat != proceed) return stat;
	if (vfld.checked) return true;
	// if we get here then the validation has failed

	var errorMsg = 'Please read the above message and confirm you agree to it';
	msg (ifld, "error", errorMsg);
	return false;
}

// validate radio buttons
function validateRadio (vfld,ifld,t,val) {
	myOption = -1;
	var mgg = "";
	for (var goog in vfld.parentNode) {
		mgg += "|"+goog+" ";
	}

	if(vfld) {
		var radioLength = vfld.length;
		if(radioLength == undefined)
			if(vfld.checked)
				myOption = -2;
		for(var i = 0; i < radioLength; i++) {
			if(vfld[i].checked) {
				myOption = i;
			}
		}
	}

	if (t == undefined || t == "") {
		t = "Required";
	}
	if (myOption == -1) {
		msg (ifld, "error", t);
		return false;
	}
	if (val != undefined && val != "") {
		if (myOption == -2) {
			var chkval = vfld.value;
		} else {
			var chkval = vfld[myOption].value;
		}
		if (chkval != val) {
			msg (ifld, "error", t);
			return false;
		}
	}

	msg (ifld,"warn","");
	return true;
}


function validateCode(vfld, ifld, dig) {
        var stat = commonCheck (vfld, ifld, true);
        if (stat != proceed) return stat;

	if (vfld.value.length < 3) {
		msg (ifld, "error", "Must be at least 3 digits.");
		return false;
	}

        msg (ifld, "warn", "");
        return true;
};

function validateCard(vfld, ifld) {
        var stat = commonCheck (vfld, ifld, true);
        if (stat != proceed) return stat;

	if (!Mod10(vfld.value)) {
		msg (ifld, "error", "Must input valid card number");
		return false;
	}

        msg (ifld, "warn", "");
        return true;
};

function validateABA(vfld, ifld) {
        var stat = commonCheck (vfld, ifld, true);
        if (stat != proceed) return stat;

	if (vfld.value.length != 9) {
		msg (ifld, "error", "ABA number must be 9 digits");
		return false;
	}

        msg (ifld, "warn", "");
        return true;
};

function manClick(val) {
        document.forms.navform.navButton.value = val;
        document.forms.navform.submit();
};

function money(val) {
	return val.toFixed(2);
};

