/**
	formValidation
	version 2.0.5
	
	'R'						- required, any value is valid
	'isEmail'				- is email, must be valid email to validate
	'isDatemm/dd/yyyy'		- is date, must be a valid date, valid formats [mm/dd/yyyy, mm-dd-yyyy]
	'isNum'					- is number
	'inRange1:10'			- in range, must be a number in range
	'isPhoneXXX-XXX-XXXX'	- is phone, must be a valid phone, validates phone entered with various chars and sets value to match format
	'isWordCount<=250'		- is wordcount, must have 250 or less words
	'isCheckBox'			- is a checkbox
	
	CHANGE LOG
	2.0.0   - created form validation to validate each form element based on keywords
	2.0.1   - added extensive email validation, instead of just checking for @
	2.0.2   - added phone validation to use regular expression to match numbers and format
	2.0.3   - added browser check to gaurd against netscape behaving badly with string.replace
	2.0.3.1 - added fix for netscape string.replace
	2.0.3.2	- added isCheckBox to allow for required checkboxes
	2.0.4 - added wordcount
	2.0.5 - added IP_SetRequiredBasedOnValue
*/
/* Browser Check */
function BrowserCheck() {
	var b = navigator.appName
	if (b=="Netscape") this.b = "ns"
	else if (b=="Microsoft Internet Explorer") this.b = "ie"
	else this.b = b
	this.version = navigator.appVersion
	this.v = parseInt(this.version)
	
	this.DOM = (document.getElementById) ? true : false;
	this.Opera = (navigator.userAgent.indexOf("Opera")!=-1);
	this.Konqueror = (navigator.userAgent.indexOf("Konqueror")!=-1);
	this.IE = (this.b=="ie" && this.v>=4)
	this.IE4 = (this.version.indexOf('MSIE 4')>0)
	this.IE5 = (this.version.indexOf('MSIE 5.0')>0)
	this.IE55 = (this.version.indexOf('MSIE 5.5')>0)
	this.IE6 = (this.version.indexOf('MSIE 6.0')>0)
	this.NS = (this.b=="ns" && this.v>=4)
	this.NS4 = (this.b=="ns" && this.v==4)
	this.NS5 = (this.b=="ns" && this.v==5)
	this.NS6  = this.DOM && !this.IE && !this.Konqueror
	this.Mac = (navigator.appVersion.indexOf("Mac") != -1);
	this.IE4M = this.IE4 && this.Mac;
}
var is = new BrowserCheck()  // automatically create the "is" object
/* End Browser Check */


var IP_FV_reqPass = "/images/req_2.gif"
var IP_FV_reqFail = "/images/req_1.gif"
var IP_FV_reqNull = "/images/null.gif"

/* IP_FindObj */
// Example: obj = IP_findObj("image1");
function IP_findObj(theObj, theDoc)
{
  var p, i, foundObj;
  
  if(!theDoc) theDoc = document;
  if( (p = theObj.indexOf("?")) > 0 && parent.frames.length)
  {
    theDoc = parent.frames[theObj.substring(p+1)].document;
    theObj = theObj.substring(0,p);
  }
  if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
  for (i=0; !foundObj && i < theDoc.forms.length; i++) 
    foundObj = theDoc.forms[i][theObj];
  for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++) 
    foundObj = findObj(theObj,theDoc.layers[i].document);
  if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);
  
  return foundObj;
}


/**************/

function IP_initREQ(){
  var i,args=IP_initREQ.arguments;
  for (i=0; i<(args.length); i+=2) {
   val=IP_findObj(args[i]);
   val.arg=args[i+1];
   val.oclassName = (val.className!='')? val.className : '' ;
   IP_checkREQ(val,args[i+1]);
  }
}

function IP_setREQImage(name,setType){
imageObj = document.images[name+'REQ']
  if(setType==1){
     imageObj.src = IP_FV_reqPass
  }else if(setType==0){
     imageObj.src = IP_FV_reqFail
  }else if(setType==-1){
     imageObj.src = IP_FV_reqNull
  }
}
function IP_checkREQ(formElement,reqText){
    if(formElement.arg!=reqText && reqText!=undefined){formElement.arg=reqText;}

    formElement.validated = IP_validateFormElement(formElement,formElement.arg)

    if(!formElement.disabled){
    if(formElement.validated==''){
      if(formElement.value){
      IP_setREQImage(formElement.id,1);
	  formElement.className = formElement.oclassName;
    }else{
    IP_setREQImage(formElement.id,-1);
    }
    }else{
      IP_setREQImage(formElement.id,0);
    }
    }else{
      IP_setREQImage(formElement.id,-1);
    }

}
/****************************************************/
/* 'RisEmail'										*/
/* 'RisDatemm/dd/yyyy'								*/
/* 'RisNum'											*/
/* 'RinRange1:10'									*/
/* 'R'												*/
/* 'isPhoneXXX-XXX-XXXX'							*/
/****************************************************/
function IP_validateFormElement() { //v4.2
  var i,p,df,dd,dt,td,vd,q,nm,test,num,min,max,errors='',args=IP_validateFormElement.arguments;
  for (i=0; i<(args.length-1); i+=2) { test=args[i+1]; val=args[i];
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=IP_validateEmail(val);
        if(p.length)errors+= nm+' must contain a valid e-mail address.\n'+p;
      } else if (test.indexOf('isDate')!=-1) { p=test.indexOf('isDate');
      df=test.substring(p+6); dd=(df.indexOf('-')>0)? '-' : '/'; dt=val.split(dd);
      switch(df){ case 'mm-dd-yyyy': case 'mm/dd/yyyy': td = new Date(dt[2],dt[0],dt[1]); vd = (td.getDate()==dt[1]&&td.getMonth()==dt[0]&&td.getFullYear()==dt[2]); break; case 'dd-mm-yyyy': case 'dd/mm/yyyy': td = new Date(dt[2],dt[1],dt[0]); vd = (td.getDate()==dt[0]&&td.getMonth()==dt[1]&&td.getFullYear()==dt[2]); break;}
    if(!vd) errors += nm+' must contain a valid Date '+ df +'\n';
    } else if (test.indexOf('isPhone')!=-1) { p=test.indexOf('isPhone');
		df=test.substring(p+7); vd='';
		vd = IP_validatePhonebyRegExp(val,df,args[i]); //IP_validatePhone(val,df);
		if(vd.length) errors += nm+' must contain a valid Phone # '+ df +'\n'+vd;
	} else if (test.indexOf('isWordCount')!=-1) { p=test.indexOf('isWordCount');
		df=test.substring(p+11); vd='';
		vd = IP_validateWordCount(val,df,args[i]); 
		if(vd.length) errors += nm + ' ' + vd;
	} else if (test.indexOf('isCheckBox')!=-1) {
				if(!args[i].checked) errors += nm+' must be checked.\n';
	} else if (test!='R') {
		if (test=='')return '';
        if (isNaN(val)) errors+= nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (val<min || max<val) errors+= nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R')  errors += nm+' is required.\n'; }
  } if (!errors) errors=''; 
  return errors;
}
var IP_badEmailChars = [' ','\\','/','='];
function IP_validateEmail(eml){
	var p,q,r,err="";
		p=eml.indexOf('@');
        if (p<1) err+= '        e-mail must contain a name followed by an @.\n';
		if (p==(eml.length-1)) err+= '        e-mail must contain an @ followed by a domain.\n';
		q=eml.indexOf('.');r=eml.lastIndexOf('.');
		if (q<0) err+= '        e-mail must contain a period(.).\n';
		if (q==0 || (q+1)==p) err+= '        e-mail must contain a valid name followed by an @.\n';
 		if ((r<p || r==(eml.length-1))&&(q>0)) err+= '        e-mail must contain at least 1 period (.) as part of the domain.\n';
		for(var i=0; i<IP_badEmailChars.length; i++){
			if(eml.indexOf(IP_badEmailChars[i])>0) err+= '        e-mail cannot contain a ('+IP_badEmailChars[i]+').\n';
		}
	return err;
}
function IP_validatePhonebyRegExp(p,v,i){
	var err='';
	var pres = /\d{3,4}/gi;
	var vres = /X{3,4}/gi;
	//alert("Testing RegExp( "+ v +" )")
	//var re = new RegExp(res,'gi');
	v = (v=="")? '(XXX) XXX-XXXX' : v;
	var m = p.match(pres);
	var n = v.match(vres);
	
	if(m == null){
		err = '        A valid phone number was not found.\n';
	}else{
		if(m.length != n.length){
			err = '        A valid phone number must match this format: '+v+'\n';
		}else{
			for(var j=0; j<m.length; j++){
				if(m[j].length != n[j].length){
					err = '        '+m[j]+' must match '+n[j]+'\n';
				}
			}
			var validated = '';
			if(err==''){
			if(is.IE){
				if(n.length == 2){
					vres = /X{3}([\s-\.]?)X{4}/gi;
					validated = v.replace(vres,m[0]+'$1'+m[1]);
				}else if(n.length == 3){
					vres = /(\(?)X{3}(\)?[\s-\.]?)X{3}([\s-\.]?)X{4}/gi;
					validated = v.replace(vres,'$1'+m[0]+'$2'+m[1]+'$3'+m[2]);
				}
				i.value = validated;
			}else if(is.NS){
				var mnsi = 0;
				var mns = m.join("");
				for(var n=0; n<v.length; n++){
					if(v.charAt(n) == "X"){
						validated += mns.charAt(mnsi++);
					}else{
						validated += v.charAt(n);
					}
				}
				//alert(validated);
				i.value = validated;
			}
			
			}
		}
	}
	return err;
}
function IP_validateWordCount(p,v,i){
	var alertText = '';
	var err='';
	var numWords = 0;
	var arrWords;
	var pl = v.lastIndexOf('=');
	var test = v.substr(0,pl+1);
	if( pl!=-1){
		numWords = new Number(v.substr(pl + 1));
	}
	p = p.replace(/^\s*/gi,'');
	p = p.replace(/\s*$/gi,'')
	arrWords = p.split(' ');
	
	//alertText += "Number of Words: " + numWords + "\n";
	//alertText += "Number of Words found: " + arrWords.length + "\n";
	//alertText += "Test rule: " + test + "\n";
	
	switch(test){
		case "<=":
			if(!(arrWords.length <= numWords)){
				err = 'must have ' + numWords + ' words or less.';
			}
			break;
		case ">=":
			if(!(arrWords.length >= numWords)){
				err = 'must have ' + numWords + ' words or more.';
			}
			break;
		case "==":
			if(!(arrWords.length == numWords)){
				err = 'must have ' + numWords + ' words.';
			}
			break;
	}
	
	//alert(alertText);
	return err;
}

function IP_validateForm(theForm){
var errors='',p='', e=1;
  for(i=0;i<theForm.length; i++){
    if(!theForm.elements[i].disabled){
    if(theForm.elements[i].validated!=undefined && (theForm.elements[i].validated!='')){errors += '    '+ e++ +'. '+ theForm.elements[i].validated;
	theForm.elements[i].className='inputError'}else{theForm.elements[i].className=theForm.elements[i].oclassName;}}
  }
  if(e>1){p='s';}
  if (errors!='') {alert('The form ('+theForm.name+') could not be processed\nfor the following reason'+p+':\n\n'+errors);}
  return(errors=='');
}

function IP_enableFormElements() {
  var i,x,formObj,a=IP_enableFormElements.arguments;
  for(i=1;i<a.length;i++){if ((x=IP_findObj(a[i]))!=null){x.disabled = !(a[0]);if(a[0]){IP_checkREQ(x,x.arg);}else{x.value=''; IP_setREQImage(x.name,-1);}}}
}

function IP_SetRequiredBasedOnValue() {
	var a=IP_SetRequiredBasedOnValue.arguments;
	var v = (a.length==3)? a[3] : 'R';
	if(a[0].value == a[1])
		IP_initREQ(a[2], v);
	else
		IP_initREQ(a[2], '');
}
/*
document.write("<font size=2>");
for(var e in is){
	document.write("is."+e+"= "+is[e]+"<br>");
}
document.write("</font>");
*/