
function validateField(field, msg) {
	if (!field.value || field.value == "") {
		alert(msg);
		field.focus();
		return false;
	}
	
	return true;
}

function validateSelect(field, msg) {
	var val = field.options[field.selectedIndex].value;
	if (!val) {
		alert(msg);
		field.focus();
		return false;
	}
	
	return true;	
}


/* ============================================================================ */

function validateUsername(theField){

	var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	var checkStr = theField.value;
	var allValid = true;
	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
			if (ch == checkOK.charAt(j))
				break;
		if (j == checkOK.length)
		{
			allValid = false;
			break;
		}
	}
	if (!allValid)
	{
		//alert("Please enter only letter and numeric characters in the '"+theField.fieldname+"' field.");
		theField.value=0;
		return (false);
	}
	
	// require at least 5 characters in the password field
	if (theField.value.length < 6)
	{
		//alert("Please enter at least 6 characters in the '"+theField.fieldname+"' field.");
		return (false);
	}
	return true;

}

function validateNumeric(theField) {
// checks for valid number
	var tmp = fnCleanDecimal(theField.value);
	if (isNaN(parseFloat(tmp))){
		alert('The field "'+theField.fieldname+'" requires a number.');
		theField.value=0;
		return false
	}
	theField.value=tmp;
	return true;
}

function fnFormat(string, format){
	var string2 = string.value;
	var tmp = fnCleanNumber(string2);
	var newstring = "";
	for (i=0, j=0; i<format.length; i++) {
		if (format.charAt(i) == "#") {
			newstring += tmp.charAt(j);
			j++;
		}
		else {
			newstring += format.charAt(i);
		}
		string.value = newstring;
	}
}

//clean integer
function fnCleanNumber(string) {
	var numbers = "0123456789";
	var newstring = "";
	for (i=0; i<string.length; i++)	{
		if (numbers.indexOf(string.charAt(i)) == -1) {
		}
		else {
			newstring += string.charAt(i); 
		} 
	}
	return (newstring);
}

function onFormatField( e ){
	// format the data in the field
	var dataType = new String (e.datatype);
	var controlType = new String (e.type);

	if (e.maxsize!=null) {
		if (e.value.length>e.maxsize){
			alert("The value in "+e.fieldname+" is too long and will be truncated.");
			e.value=e.value.slice(0,e.maxsize-1);
		}
	}

	// if it is a text input....
	if ((controlType.toUpperCase()=="TEXT")&&(!isBlank(e.value))){

		if (dataType.toUpperCase()=="PHONE"){
			fnPhoneNo(e);
		}else if (dataType.toUpperCase()=="ZIPCODE"){
			fnZipCode(e);
		}else if (dataType.toUpperCase()=="STRING"){
			e.value = e.value;
		}else if (dataType.toUpperCase()=="DOMAINNAME"){
			e.value = e.value;
		}else if (dataType.toUpperCase()=="NUMERIC"){
			validateNumeric(e);
		}else if (dataType.toUpperCase()=="IP"){
			validateNumeric(e);
		}else if (dataType.toUpperCase()=="EMAIL"){
			validateEmail(e);
		}
	}
}

function trimZeroes(theField) {
	var num;
	if (theField.value.length == 2 && theField.value.charAt(0) == "0"){
		num = theField.value.charAt(1);
		theField.value = num;
	}
}


function isValidEmail(theField) {
  var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
  if(reg.test(theField.value) == false) {
	  return false;
   }
	return true;
}

function validateEmail(theField) {
//generates error message
	if (!isValidEmail(theField)){
		alert('The field Email requires an email address \nin the form userid@company.com');
		return false;
	}
	return true;
}

function isBlank(s){
// utility function
// returns true if contains only whitespace characters
	if( s=="undefined" ) return true;

	for( var i=0; i < s.length; i++ ){
		var c=s.charAt(i);
		if (( c != ' ')&&( c != '\n') &&(c != '\t' )) return false;
	}
	return true;
}

function validateForm(f,errs){
// carry out form validation
// displays errors
// returns true if everything is ok
	var msg;
	var empty_fields= "";
	var errors = "";
	var value = 0;
	var blah;
	var origPassword="";

	if (errs!=null){
	  errors = errors + errs;
	 }

	for (var i=0; i < f.length ; i++ ){
		var e = f.elements[i];
		if(e.fieldname=="Password"){
			origPassword=e.value;
		}
		if ((e.type=="text") || (e.type=="password") || (e.type=="username") || (e.type=="textarea") || (e.type=="select-one") || (e.type=="radio") || (e.type=="password")){
			value = e.value;

			//first check if the field is empty
			if (eval(e.required) && ((value==null)||(value=="")||isBlank(value)) && (!( e.type=="select-one"))){
				empty_fields += "\n         " + e.fieldname;
				continue;
			}

			//Check for email addresses
			if ((e.datatype == "email") && (!((value==null)||(value=="")||isBlank(value)))){
				if (!(isValidEmail(e)))
					errors +=" - Please enter a valid email address in "+e.fieldname+" (i.e., yourname@yourcompany.com).\n";
			}

			if ((e.datatype == "username") && (!((value==null)||(value=="")||isBlank(value)))){
				if (!(validateUsername(e)))
					errors +=" - "+e.fieldname+" may only contain letters and numbers, and must be at least 6 characters long.\n";
			}

			if(e.datatype == "password"){
			// check if both password fields are the same
				if (e.value != origPassword)
				{
					//alert(e.value + " " + origPassword);
					errors +=" The confirmation password did not match the original password.\n";
				}
			}

			//Now check for fields that are numeric
			if (eval(e.required) && (!((value==null) || (value=="") || isBlank(value)))){

				//check for integer
				if ((e.datatype=="integer") && (!((e.type=="select-one") || (e.type=="radio")))){
					//check integer if min/max not set
					var q,tmp,prob;
					prob = '0';
					tmp=(e.value);
					var numbers = "0123456789";
					for(q=0; q<tmp.length; q++){
						if (numbers.indexOf(tmp.charAt(q)) == -1){
							prob='1';
						}
					}
					if (prob=='1'){
						errors += " - " + e.fieldname + " must be an integer.\n";
					}
					prob = '0';
				}
				//check for decimal value
				if ((e.datatype=="numeric") && (!((e.type=="select-one") || (e.type=="radio")))){
					//check numeric if min/max not set
					var q,tmp,prob;
					prob = '0';
					tmp=(e.value);
					var numbers = "0123456789.";
					for(q=0; q<tmp.length; q++){
						if (numbers.indexOf(tmp.charAt(q)) == -1){
							prob='1';
						}
					}
					if (prob=='1'){
						errors += " - " + e.fieldname + " must be numeric.\n";
					}
					prob = '0';
				}
				//check min/max
				if (((e.datatype=="numeric")||(e.datatype="integer"))&&((e.min!=null)||(e.max!=null))){

					if ( ( e.type=="text")|| ( e.type=="textarea" ) ){
						value=parseFloat(e.value)
					}
					else if ( e.type=="select-one"){
						value=parseFloat(e.selectedIndex)
					}

					var v =  value;

					if (isNaN(v)|| ((e.min != null) && ( v < e.min)) || ((e.max != null) && ( v > e.max))){
						errors += " - The field " + e.fieldname;

						if (!(e.type=="select-one")) {
							errors += " must be a number";
							if (e.min != null){
								errors += " that is greater than " + e.min;
							}
						}
						else if (e.type=="select-one"){
							if (e.min != null){
								errors += " must have a value selected";
							}
						}
						else if (e.max != null && e.min != null){
							errors += " and is less than " + e.max;
						}
						else if (e.max != null ){
							errors += " that is less than " + e.max;
						}
						errors += ".\n";
					}
				}
			}
		} //end if e.type
	} //end for

	// display errors
	if (!empty_fields && !errors){
		if (f.customValidation){
			return(f.customValidation(f))
		}
		else
		{
			return true;
		}
	}

	msg  = "_______________________________________________\n\n";
	msg += "   P L E A S E    N O T E:\n";
	msg += "   This form contains errors. Please correct\n";
	msg += "   the errors and then re-submit the form.\n";
	msg += "_______________________________________________\n\n";

	if (empty_fields){
		msg += " - The following required fields are empty:" + empty_fields + "\n";
		if (errors) msg += "\n";
	}

	msg += errors;
	alert(msg);
	return false;
//	return confirm(msg+"\nSave anyway?");
}

	function doValid(){
		var f = document.form1;
		var msg = '';
		
		f.nameFirst.datatype="string";
		f.nameFirst.required="true";
		f.nameFirst.fieldname="First Name";

		f.nameLast.datatype="string";
		f.nameLast.required="true";
		f.nameLast.fieldname="Last Name";
		
		f.address.datatype="string";
		f.address.required="true";
		f.address.fieldname="Address";

		f.city.datatype="string";
		f.city.required="true";
		f.city.fieldname="City";

        if (validateForm(f,msg)){
	        f.submit();
        }

	}
	function getFormGroup(name) {return document.getElementsByName(name);}
	function getRadio(name) {
		elements = getFormGroup(name);
		if (elements)/* loop over all the radio buttons */
		for (i = 0; i < elements.length; i++)
			if (elements[i].checked)
			return elements[i];/* either no group by that name was foundor none were selected */
		return null;
		}
		function getRadioValue(name) {
			element = getRadio(name);
			if (element)
			return element.value;/* there must not have been a radio buttonselected */
			return '';
			}


	function countryChange(){
		switcher=getRadioValue("country");
		if(switcher==2){
			document.getElementById('US').style.display = 'block';
			document.getElementById('US1').style.display = 'block';
			document.getElementById('Canada').style.display = 'none';
			document.getElementById('Canada2').style.display = 'none';
			document.getElementById('Other').style.display = 'none';
			document.getElementById('Other1').style.display = 'none';
			document.getElementById('Other2').style.display = 'none';
		}else if(switcher==1){
			document.getElementById('US').style.display = 'none';
			document.getElementById('US1').style.display = 'none';
			document.getElementById('Canada').style.display = 'block';
			document.getElementById('Canada2').style.display = 'block';
			document.getElementById('Other').style.display = 'none';
			document.getElementById('Other1').style.display = 'none';
			document.getElementById('Other2').style.display = 'none';
		}else{
			document.getElementById('US').style.display = 'none';
			document.getElementById('US1').style.display = 'none';
			document.getElementById('Canada').style.display = 'none';
			document.getElementById('Canada2').style.display = 'none';
			document.getElementById('Other').style.display = 'block';
			document.getElementById('Other1').style.display = 'block';
			document.getElementById('Other2').style.display = 'block';
		}
	}

var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	if(input.value.length >= len && !containsElement(filter,keyCode)) {
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input)+1) % input.form.length].focus();
	}
	function containsElement(arr, ele) {
		var found = false, index = 0;
		while(!found && index < arr.length)
			if(arr[index] == ele)
				found = true;
			else
				index++;
		return found;
	}
	function getIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
			if (input.form[i] == input)index = i;
			else i++;
		return index;
	}
	return true;
}

