/*
	Validate Field Values 
*/

var errFieldIntro= "> ";		// Error errMsg_FIELDEMPTY Intro
var errFieldEnd  = " "; 		// Error errMsg_FIELDEMPTY End
var errLineSep   = "<br/>"; 		// Error errMsg_FIELDEMPTY Line Intro


function ErrMess(Msg) {
	return errFieldIntro + Msg + errFieldEnd;
}

function ProcessErrMess(deferrMsg, errMsg) {
	if (errMsg != '') {
		if (typeof deferrMsg != "undefined" && deferrMsg !='' ) 
			return ErrMess(deferrMsg)
		else
			return ErrMess(errMsg)
	}
	return ""
}

function ValidateFieldValue(Field, errMsg_FIELDEMPTY, 
					FieldValueType, errMsg_FIELDVALUE, 
					FieldLength, errMsg_FIELDLENGTH	) 
{
	if ((Field.value == "") || (Field.value == "[SELECT]")) return ErrMess(errMsg_FIELDEMPTY);
	if (typeof FieldLength == 'number') 
		if (Field.value.length != FieldLength) return ErrMess(errMsg_FIELDLENGTH); 
	if (typeof FieldValueType != "undefined") {
		var fval = Field.value;
		switch (FieldValueType) {
			case 'num':	if (isNaN(fval)) return ErrMess(errMsg_FIELDVALUE);
						return ""
			case 'int': if (isNaN(fval)) return ErrMess(errMsg_FIELDVALUE);
						if (Math.floor(fval)!=fval) return ErrMess(errMsg_FIELDVALUE);
						return ""
			case 'email': 
				var errMsg = validateEmail(fval)
				return ProcessErrMess(errMsg_FIELDVALUE, errMsg)
			/* 
			Disabled by Mishel (Feb 17, 2003)
			case 'phone': 
				var errMsg = validatePhone(fval)
				return ProcessErrMess(errMsg_FIELDVALUE, errMsg)
			case 'phoneint': 
				var errMsg = validatePhoneInt(fval)
				return ProcessErrMess(errMsg_FIELDVALUE, errMsg)
			*/
			case 'postalcode': 
				var errMsg = validatePostalCode(fval)
				return ProcessErrMess(errMsg_FIELDVALUE, errMsg)
			default: break;
		}
	} 
	return "";


}

function CountGroupOptions() {
	var total = 0;
	for (var idx = 0; idx < arguments.length; idx++) {
		if (arguments[idx].checked == true) total += 1; 
	}
	return total
}

function CountGroupOptionsByName(Form, NameFilter) {
	var total = 0;
	var er=0
	for (ix=0; ix<Form.elements.length; ix++) {
		if (Form.elements[ix].name.indexOf(NameFilter)>=0) {
			try {
				if (Form.elements[ix].checked == true) total += 1; 
			}
  			catch(e) { er++; }
		}
	}
	return total
}

function FirstCheckedOptions(radio_chkbox) {
	var max = radio_chkbox.length;
	for (var idx = 0; idx < max; idx++) {
		if (radio_chkbox[idx].checked == true) return idx
	}
	return -1;
}

function CountCheckedOptions(radio_chkbox) {
	var max = radio_chkbox.length;
	var total = 0;
	for (var idx = 0; idx < max; idx++) {
		if (radio_chkbox[idx].checked == true) total += 1; 
	}
	return total
}

function ListFrmFields (Form, NameFilter) {
	document.write(Form.name+'...Elements : '+Form.elements.length+'<br/>');
	var sName = ''
	if (typeof NameFilter!='undefined') { sName = NameFilter;}
	N = Form.elements.length;
	shtml=''
	for (ix=0;ix<N;ix++) {
		max=Form.elements(ix).maxLength
		max=( (max=2147483647)?'undef':max )
		if (sName=='' || Form.elements(ix).name.indexOf(sName)>=0) {
			shtml += ix+'..'+Form.elements(ix).name+'...'+
					 ' [size='+Form.elements(ix).size+' / max='+max+'] ' +
					 '<br/>'
		}
	}
	document.write(shtml);

}

function validatePostalCode(codestr) {
var regPCode = /[A-Za-z][0-9][A-Za-z](.*)[0-9][A-Za-z][0-9]/
	
	if (codestr.length==0) return 'Invalid Postal Code';
	var matchArray=codestr.match(regPCode)
	if (matchArray==null) {
		return 'Invalid Postal Code';
	} else {
		return '';
	}
}

function validatePhone(phonestr) {
var digits = 0;
var specChar = " ().-"
var deferrmess = "Please enter phone number in the format (555) 555-5555";

	if (phonestr=="") return '';
	for (var i=0; i < phonestr.length; i++) {
		var theChar = phonestr.charAt(i);
		if ((theChar >= "0") && (theChar <= "9")) { digits++; continue; }
		if (specChar.indexOf(theChar) >= 0) continue;
		return deferrmess
	}	
	if (digits == 10) 
		return "";	
	else
		return deferrmess
}

function validatePhoneInt(phonestr) {
var digits = 0;
var specChar = " ().-"
var deferrmess = "Please enter a phone number in the format 1 (555) 555-5555";

	if (phonestr=="") return '';
	for (var i=0; i < phonestr.length; i++) {
		var theChar = phonestr.charAt(i);
		if ((theChar >= "0") && (theChar <= "9")) { digits++; continue; }
		if (specChar.indexOf(theChar) >= 0) continue;
		alert('1')
		return deferrmess;
	}	
	if ((digits == 11) || (digits == 10) )
		return ""
	else
		return deferrmess
}


function validateEmail (emailStr) {
// check if the e-mail address fits the user@domain format.
var emailPat=/^(.+)@(.+)$/		
/* all special characters. don't 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 +")*$")

/* 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 isn't a valid e-mail address. 
	return "E-mail - (check @ and .'s)"
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    return "E-mail - Invalid username."
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
	// the e-mail address is at an IP address : make sure the IP address is valid.
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        return "E-mail - Destination IP address is invalid!"
	    }
    }
    return ""
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	return "E-mail - Domain name not valid."
}

/* 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>5) {
   // the address must end in a two letter or three letter word.
   return "E-mail - Address must end in a domain, or country."
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   return "E-mail - Missing a hostname!"
}

// If we've gotten this far, everything's valid!
return "";
}

