//General Javascript Functions

function IsNumeric(strString)
   //  check for valid numeric strings
{
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
}

function ValidateNumeric(e,sExclude) {
  if (e.keyCode) 
  		keycode=e.keyCode;
  else keycode=e.which;
  		character=String.fromCharCode(keycode);
  if (character == sExclude) 
  		e.returnValue = false;
  if (!IsNumeric(character)) 
  		e.returnValue = false;
}

function OpenHelpWindow(sPageIdentifier)
{
		//strPage = "/home/Library/dsp_HelpPage.cfm?Page=" + sPageIdentifier;			
		strPage = "scripts/dsp_Help.cfm?Page=" + sPageIdentifier;
		window.open(strPage,'HelpWindow','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no,copyhistory=yes,width=500,height=270')
}

function CheckTab(el) {
  // Run only in IE
  // and if tab key is pressed
  // and if the control key is pressed
  if ((document.all) && (9==event.keyCode)) {
    
	 if (event.shiftKey) {
		 // Cache the selection
	    el.selection=document.selection.createRange(); 
	    setTimeout("ProcessTab('" + el.id + "',true)",0)
	 } else {
	    // Cache the selection
   	 el.selection=document.selection.createRange(); 
	    setTimeout("ProcessTab('" + el.id + "',false)",0)  
	 }
  }
}

//function ProcessTab(id) {
//	alert("This is" + String.fromCharCode(9) + " a tab!");
  // Insert tab character in place of cached selection
//  document.all[id].selection.text=String.fromCharCode(9)
  // Set the focus
//  document.all[id].focus()
//}

function ProcessTab(id,shiftVal) {

if (shiftVal==false) { 
// tab only

	// Insert tab character in place of cached selection
	if (document.all[id].selection.text.length!=0) {
		// more than one char selected
		xSelection=document.all[id].selection.text
		xSelection=String.fromCharCode(9)+xSelection
		
		for (var x=0;x<xSelection.length;x++) {
			if ((xSelection.charCodeAt(x)==10) && (xSelection.charCodeAt(x-1)==13)) {
			// theres a 13 and 10 charcode in succession = newline
			xSelection=xSelection.substring(0,x+1)+String.fromCharCode(9)+xSelection.substring(x+1,xSelection.length)
			} // if charcodeat
		} // for
		document.all[id].selection.text=xSelection
	} else {
		document.all[id].selection.text=String.fromCharCode(9)
	}

} else { 
// shift and tab

	// Remove tab character in place of cached selection
	if (document.all[id].selection.text.length!=0) {
		// more than one char selected
		xSelection=document.all[id].selection.text
		if (xSelection.charCodeAt(0)==9)
			xSelection=xSelection.substring(1,xSelection.length)
			
			for (var x=0;x<xSelection.length;x++) {
				if ((xSelection.charCodeAt(x)==9) && (xSelection.charCodeAt(x-1)==10) && (xSelection.charCodeAt(x-2)==13)) {
				// theres a 13,10 and 9(tab) charcode in succession = newline with tab
				xSelection=xSelection.substring(0,x)+xSelection.substring(x+1,xSelection.length)
				} // if charcodeat
			} // for
			document.all[id].selection.text=xSelection
			
	} else {
		alert ("Please select text when using Shift+Tab")
	}
	
}

	// Set the focus
	document.all[id].focus()

}

/// Count characters in text field function
function textCounter(field, countfield, maxlimit ) {

  if ( eval(field + ".value.length") > maxlimit )
  {
    eval(field + ".value =" + field + ".value.substring( 0, " + maxlimit + ")");
    alert( 'Textarea value can only be ' + maxlimit + ' characters in length.' );
    return false;
  }
  else
  {
    eval(countfield + ".value =" + maxlimit + "-" + field + ".value.length");
  }
}

///Generic Function to Show/Hide "Other" text field when drop down has "Other" option 
///*** Other option value must be "Other" for this to work, as well as use of <span id="Other<field>" style="display: 'none'"> tags, 
///where <field> is a numerical value for which <span> to hide/show
function ShowHideOther(field,value) {	
	if (value == "Other") {	
		currOther = document.getElementById("Other" + String(field));
		currOther.style.display="";
   } else {
		currOther = document.getElementById("Other" + String(field));
		currOther.style.display="none";
	}
}

//Script for pop-up Window links from SoEditor
function ShowPopUp(sPage,sHeight,sWidth,sToolbar) {
	if (!sToolbar) {
		sToolbar = "yes";
	}
	window.open(sPage,"PopUpWindow","toolbar=" + sToolbar + ",location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,width="+sWidth+",height="+sHeight)
}

//Script for showing printing pop-up pages
function PrintPage(sPage) {
	window.open("/intranet/layouts/dsp_PrintPage.cfm?PrintMe=1&Page="+sPage,"PrintPage","toolbar=yes,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,width=800,height=500")
}

function PrintPageNew(sPage) {
	window.open("/intranet/layouts/dsp_PrintPageNew.cfm?PrintMe=1&Page="+sPage,"PrintPage","toolbar=yes,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,width=800,height=500")
}

//Newer version to allow dynamic pages to be printed - must update PageTitle include to use this function
function PrintPagev3(sPage,sVars) {
	window.open("/intranet/layouts/dsp_PrintPageNew.cfm?PrintMe=1&Page="+sPage+sVars,"PrintPage","toolbar=yes,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,width=800,height=650")	
}

///Function: FormatPhone
///Purpose: Format phone numbers as xxx-xxx-xxxx, also validates for all numeric values
///Input: Phone field to check, passed as '<formname>.<fieldname>' 
///Output: Formatted phone number back to same field value 
///Prerequisites: None 
///Conditions: None 
///Added by: Marc Giguere 
///Date Added: 6-16-2004
///Notes: RegEx credit to Steven Smith (found at regexlib.com) 
function FormatPhone(sPhone){

	var re= /\D/;
	// test for this format: (xxx)xxx-xxxx
	//var re2 = /^\({1}\d{3}\)\d{3}-\d{4}/; 
	// test for this format: xxx-xxx-xxxx
	var re2 = /^[2-9]\d{2}-\d{3}-\d{4}$/;
	
	var num = sPhone.value;
	
	var newNum;
	if (num != "" && re2.test(num)!=true){
	   if (num != ""){
	     while (re.test(num)){
	     		num = num.replace(re,"");
	     }
	   }
		
		 if (num.length != 10){
		    alert('Please enter a 10 digit phone number');
		    sPhone.select();
			sPhone.focus();
		 } else {
		     // for format (xxx)xxx-xxxx
		     //newNum = '(' + num.substring(0,3) + ')' + num.substring(3,6) + '-' + num.substring(6,10);
		     // for format xxx-xxx-xxxx
		     newNum = num.substring(0,3) + '-' + num.substring(3,6) + '-' + num.substring(6,10);
		     sPhone.value=newNum;
		 }
	} 

}

///Function: Generic Form Validation
///Purpose: This script can validate any form
///Input: Form to be checked, passed as "document.<formname>"
///Output: True/False for submittal of form
///Prerequisites: Hidden form field with name "required" that has comma separated list of fields to be checked
///Conditions: Only checks that one checkbox is checked, only one radio button is selected, and that text areas are not blank.
///Added by: Marc Giguere 
///Date Added: 6-16-2004
///Date Update: 9-15-2005
///Change Log: 09/15/05 - MG - Added ability to do text areas, passwords, and file fields...
function validateForm(what,coloroverride,bImg) {

	var tmpValue = -1;
	var valid = true;
	var fieldtofix = "";
	var highlight = "";
	var friendlyname = "";
	//Make sure that we got a value for doing the color override...
	if(coloroverride != '') {
		var colorchangecheck = coloroverride;
	} else {
		var colorchangecheck = 0;	
	}
	
	//Check if we're using images for highlight?
	if(!bImg) {
		bImg = 0;
	}
	
	var checkBoxes = false;
	var checkboxChecked = false;
	
	var radioButtons = false;
	var radioChecked = false;
	
	var reqfields=document.getElementById('Required').value.split(',');
	
	// CHeck that we have elements to verify :)
	if (reqfields.length <= 0) {
		return valid;
	}
	
	MainLoop:
	for(i=0;i<reqfields.length;i++) {
	
		/// Check if this is new format where we pass in field name and "friendly name"
		reqcheck = reqfields[i].indexOf("|");
		if (reqcheck > 0) {
			tmpvar = reqfields[i].split('|');			
			reqfields[i] = tmpvar[0];
			friendlyname = tmpvar[1];
		} else {
			friendlyname = reqfields[i];
		}
	 
		//Get Type of field
		myType = eval("what." + reqfields[i] + ".type");
		
		//Check individual field length for fields with same name (ie: radio and checkboxes) 
		myLen = eval("what." + reqfields[i] + ".length");
		
		
		//This field has more than one name valued that is the same, but ignore this check for select boxes
		if(myLen > 0 && (myType != 'select-one' && myType != 'select-multiple')) {

			SecondLoop:
			for(var j = 0; j < myLen; j++) {
			
				if(radioChecked == true) {
					break;
				}
				
				if(checkboxChecked == true) {
					break;
				}
				
				myType = eval("what." + reqfields[i] + "[" + j + "].type");
		
				//Only check for radio/checkboxes as other fields shouldn't ever share same name
				if (myType == 'radio') {
					radioButtons = true;
					if (eval("what." + reqfields[i] + "[" + j + "].checked")) 
						radioChecked = true;						
					//else 
					//	if (fieldtofix == '') 
					//	fieldtofix = reqfields[i];
					//	highlight = 0;
				}
				
				if (myType == 'checkbox') {
					checkBoxes = true;					
					if (eval("what." + reqfields[i] + "[" + j + "].checked")) 
						checkboxChecked = true;						
					//else 
					//	if (fieldtofix == '') 
					//		fieldtofix = reqfields[i];
					//		highlight = 0;
				}			  
				
			}//End SecondLoop For
		
			// Done w/loop, check if we have to alert
			//alert(reqfields[i]);
			if ((myType == 'radio' && radioChecked == false) || (myType == 'checkbox' && checkboxChecked == false)) {
				if (fieldtofix == '')
					fieldtofix = reqfields[i];
					highlight = 0;
					valid = false;
			}
		
		//Single Named fields checks, only if we still are ok and didn't find a multi-checkbox/radio problem
		} else if (valid) {
		
	        if (myType == 'radio') {			  		
	            radioButtons = true;
	      	   if (document.getElementById(reqfields[i]).checked) {
						radioChecked = true;
					} else {
						valid = false;
						if (fieldtofix == '') {
							fieldtofix = reqfields[i];
							highlight = 0;
						}
					}
	        }
			  
	        if (myType == 'checkbox') {
	            checkBoxes = true;
	            if (document.getElementById(reqfields[i]).checked) {
						checkboxChecked = true; 
					} else {
						valid = false;
						if (fieldtofix == '') {
							fieldtofix = reqfields[i];
							highlight = 0;
						}
					}
	        }
			  
	        if (myType == 'text') {
			  		tmpValue = document.getElementById(reqfields[i]).value;
					if (colorchangecheck) {
						if (bImg == 1) {
							document.getElementById(reqfields[i]).style.background="background-image: url('/images/form_bg.png') repeat-x top left";
						} else {
							document.getElementById(reqfields[i]).style.backgroundColor = '#FFFFFF';
							document.getElementById(reqfields[i]).style.color = '#000000';
						}
					}

	            if (tmpValue == '') {
						valid = false;
						if (fieldtofix == '') {
							fieldtofix = reqfields[i]; 
							highlight = 1;
						}
					}
			  }
			  
			   if (myType == 'textarea') {
			  		tmpValue = document.getElementById(reqfields[i]).value;
					if (colorchangecheck) {
						if (bImg == 1) {
							document.getElementById(reqfields[i]).style.background="background-image: url('/images/form_bg.png') repeat-x top left";
						} else {
							document.getElementById(reqfields[i]).style.backgroundColor = '#FFFFFF';
							document.getElementById(reqfields[i]).style.color = '#000000';
						}
					}
	            if (tmpValue == '') {
						valid = false;
						if (fieldtofix == '') {
							fieldtofix = reqfields[i]; 
							highlight = 1;
						}
					}
			  }
			  
			   if (myType == 'password') {
			  		tmpValue = document.getElementById(reqfields[i]).value;
					if (colorchangecheck) {
						if (bImg == 1) {
							document.getElementById(reqfields[i]).style.background="background-image: url('/images/form_bg.png') repeat-x top left";
						} else {
							document.getElementById(reqfields[i]).style.backgroundColor = '#FFFFFF';
							document.getElementById(reqfields[i]).style.color = '#000000';
						}
					}
	            if (tmpValue == '') {
						valid = false;
						if (fieldtofix == '') {
							fieldtofix = reqfields[i]; 
							highlight = 1;
						}
					}
			  }
			  
			   if (myType == 'file') {
			  		tmpValue = document.getElementById(reqfields[i]).value;
					if (colorchangecheck) {
						if (bImg == 1) {
							document.getElementById(reqfields[i]).style.background="background-image: url('/images/form_bg.png') repeat-x top left";
						} else {
							document.getElementById(reqfields[i]).style.backgroundColor = '#FFFFFF';
							document.getElementById(reqfields[i]).style.color = '#000000';
						}
					}
	            if (tmpValue == '') {
						valid = false;
						if (fieldtofix == '') {
							fieldtofix = reqfields[i]; 
							highlight = 1;
						}
					}
			  }
			  
	        if (myType == 'select-one' || myType == 'select-multiple') {
			  		tmpValue = document.getElementById(reqfields[i]).selectedIndex;
			  		if (colorchangecheck) {
						if (bImg == 1) {
							document.getElementById(reqfields[i]).style.background="background-image: url('/images/form_bg.png') repeat-x top left";
						} else {
							document.getElementById(reqfields[i]).style.backgroundColor = '#FFFFFF';
							document.getElementById(reqfields[i]).style.color = '#000000';
						}
					}
	            if (tmpValue == '' || tmpValue == '-1') {
						valid = false;
						if (fieldtofix == '') {
							fieldtofix = reqfields[i]; 
							highlight = 1;
						}
					}
			  }
			  
		}
				
    if (!valid) {
	 	break;
	 }
	 
	 }
	
    if ((checkBoxes && !checkboxChecked)) valid = false;
	 
	if ((radioButtons && !radioChecked)) valid = false;
	
	 
    if (!valid)		
	 	if (highlight) {			
			if (bImg == 1) {
				document.getElementById(fieldtofix).style.background="background-image: url('/images/form_bg_req.png') repeat-x top left";	
			} else {
			  	document.getElementById(reqfields[i]).style.backgroundColor = '#FF0000';
			  	document.getElementById(reqfields[i]).style.color = '#FFFFFF';
			}
			document.getElementById(reqfields[i]).focus();
         		alert('You have not completely filled out the form.\n\nPlease verify that all required fields are filled\nand/or at least one option is selected.\n\nPlease correct the ' + friendlyname + ' field, which is highlighted.');		  		  
		} else {
			//alert(fieldtofix);
			alert('You have not completely filled out the form.\n\nPlease verify that all required fields are filled\nand/or at least one option is selected.\n\nPlease correct the ' + friendlyname + ' field.');
		}
    return valid;
}


function parseDec(val,places,sep) {

	// This function takes two arguments:
	//   (string || number)  val
	//            (integer)  places
	//             (string)  sep
	// val is the numeric string or number to parse
	// places represents the number of decimal
	// places to return at the end of the parse.
	// sep is an optional string to be used to separate
	// the whole units from the decimal units (default: '.')

	val = '' + val;
		// Implicitly cast val to (string)
	
	if (!sep) {
		sep = '.';
		// If separator isn't specified, then use a decimal point '.'
	}
	
	if (!places) { places = 0; }
	places = parseInt(places);
		// Make sure places is an integer
	
	if (!parseInt(val)) {
		// If val is null, zero, NaN, or not specified, then
		// assume val to be zero.  Add 'places' number of zeros after
		// the separator 'sep', and then return the value.  We're done here.
		val = '0';
		if (places > 0) {
			val += sep;
			while (val.substring((val.indexOf(sep))).length <= places) {
				val += '0';
			}
		}
		return val;
	}
	
	if ((val.indexOf('.') > -1) && (sep != '.')) {
		val = val.substring(0,val.indexOf('.')) + sep + val.substring(val.indexOf('.')+1);
			// If we're using a separator other than '.' then convert now.
	}
		
	if (val.indexOf(sep) > -1) {
		// If our val has a separator, then cut our value
		// into pre and post 'decimal' based upon the separator.
		pre = val.substring(0,val.indexOf(sep));
		post = val.substring(val.indexOf(sep)+1);
	} else {
		// Otherwise pre gets everything and post gets nothing.
		pre = val;
		post = '';
	}
	
	if (places > 0) {
		// If we're dealing with a decimal then...
		
		post = post.substring(0,(places+1));
			// We care most about the digit after 'places'
		
		if (post.length > places) {
			// If we have trailing decimal places then...
			
			//alert (parseInt(post.substring(post.length - 1)));

			if ( parseInt(post.substring(post.length - 1)) > 4 ) {
				post = '' + Math.round(parseInt(post) / 10);
				//post = '' + post.substring(0,post.length - 2) + (1/Math.pow(10,places));
				//post = ('' + post.substring(0,post.length - 2)) + (parseInt(post.substring(post.length - 1)) + 1);
			} else {
				post = '' + Math.round(parseInt(post));
			}
		}
		
		if (post.length > places) {
			post = '' + Math.round(parseInt(post.substring(0,places)));
		} else if (post.length < places) {
			while (post.length < places) {
				post += '0';
			}
		}
	
	} else {

		if (parseInt((post.substring(0,1))) > 4) {
			pre = '' + (parseInt(pre) + 1);
		} else {
			pre = '' + (parseInt(pre));	
		}
		post = '';
	}
	
	sep = (post.length > 0) ? sep : '';
		// Should we use a separator?

	val = pre + sep + post;
		// Rebuild val

	return val;
}

function parseMoney(val,sep) {

	// Specialized version of parseDec useful for
	// parsing money-related data.  Arguments:
	//   (string || number)  val
	//             (string)  sep
	// val is the monetary value to be parsed,
	// sep is an optional decimal separator (default: '.')
	
	return parseDec(val,2,sep);
}

function sepToDec(val,sep) {

	val = '' + val;

	if ((val.indexOf(sep) > -1) && (sep != '.')) {
		val = val.substring(0,val.indexOf(sep)) + '.' + val.substring(val.indexOf(sep)+1);
	}
	
	return val;
}

function decToSep(val,sep) {

	val = '' + val;
	sep = '' + sep;

	if ((val.indexOf('.') > -1) && (sep.length > 0)) {
		val = val.substring(0,val.indexOf('.')) + sep + val.substring(val.indexOf('.')+1);
	}

	return val;
}

//Original:  Richard Gorremans (RichardG@spiritwolfx.com) -->
//Web Site:  http://www.spiritwolfx.com -->

//This script and many more are available free online at -->
//The JavaScript Source!! http://javascript.internet.com -->

//Begin
// Check browser version
var isNav4 = false, isNav5 = false, isIE4 = false
var strSeperator = "/"; 
// If you are using any Java validation on the back side you will want to use the / because 
// Java date validations do not recognize the dash as a valid date separator.
var vDateType = 3; // Global value for type of date format
//                1 = mm/dd/yyyy
//                2 = yyyy/dd/mm  (Unable to do date check at this time)
//                3 = dd/mm/yyyy
var vYearType = 4; //Set to 2 or 4 for number of digits in the year for Netscape
var vYearLength = 2; // Set to 4 if you want to force the user to enter 4 digits for the year before validating.
var err = 0; // Set the error code to a default of zero
if(navigator.appName == "Netscape") {
if (navigator.appVersion < "5") {
isNav4 = true;
isNav5 = false;
}
else
if (navigator.appVersion > "4") {
isNav4 = false;
isNav5 = true;
   }
}
else {
isIE4 = true;
}
function DateFormat(vDateName, vDateValue, e, dateCheck, dateType) {
	vDateType = dateType;
	// vDateName = object name
	// vDateValue = value in the field being checked
	// e = event
	// dateCheck 
	// True  = Verify that the vDateValue is a valid date
	// False = Format values being entered into vDateValue only
	// vDateType
	// 1 = mm/dd/yyyy
	// 2 = yyyy/mm/dd
	// 3 = dd/mm/yyyy
	//Enter a tilde sign for the first number and you can check the variable information.
	if (vDateValue == "~") {
		alert("AppVersion = "+navigator.appVersion+" \nNav. 4 Version = "+isNav4+" \nNav. 5 Version = "+isNav5+" \nIE Version = "+isIE4+" \nYear Type = "+vYearType+" \nDate Type = "+vDateType+" \nSeparator = "+strSeperator);
		vDateName.value = "";
		vDateName.focus();
		return true;
	}
	var whichCode = (window.Event) ? e.which : e.keyCode;
	// Check to see if a seperator is already present.
	// bypass the date if a seperator is present and the length greater than 8
	if (vDateValue.length > 8 && isNav4) {
		//If validating date, check it now
		if (dateCheck) {
			if (!dateValid(vDateValue)) {
				alert("Invalid Date\nPlease Re-Enter");
				vDateName.value = "";
				vDateName.focus();
				vDateName.select();
				return false;
			}
		//Otherwise make sure there is a separator and assume its ok date
		} else {
			if ((vDateValue.indexOf("-") >= 1) || (vDateValue.indexOf("/") >= 1))
			return true;
		}
	}
	
	//Eliminate all the ASCII codes that are not valid
	var alphaCheck = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/-";
	if (alphaCheck.indexOf(vDateValue) >= 1) {
		if (isNav4) {
			vDateName.value = "";
			vDateName.focus();
			vDateName.select();
			return false;
		} else {
			vDateName.value = vDateName.value.substr(0, (vDateValue.length-1));
			return false;
	   }
	}

	//Ignore the Netscape value for backspace. IE has no value
	if (whichCode == 8) {
		return false;
	} else {
		//Create numeric string values for 0123456789/
		//The codes provided include both keyboard and keypad values
		var strCheck = '47,48,49,50,51,52,53,54,55,56,57,58,59,95,96,97,98,99,100,101,102,103,104,105';
		if (strCheck.indexOf(whichCode) != -1) {
			if (isNav4) {
				if (((vDateValue.length < 6 && dateCheck) || (vDateValue.length == 7 && dateCheck)) && (vDateValue.length >=1)) {
					alert("Invalid Date\nPlease Re-Enter");
					vDateName.value = "";
					vDateName.focus();
					vDateName.select();
					return false;
				}
				if (vDateValue.length == 6 && dateCheck) {
					var mDay = vDateName.value.substr(2,2);
					var mMonth = vDateName.value.substr(0,2);
					var mYear = vDateName.value.substr(4,4)
					//Turn a two digit year into a 4 digit year
					if (mYear.length == 2 && vYearType == 4) {
						var mToday = new Date();
						//If the year is greater than 30 years from now use 19, otherwise use 20
						var checkYear = mToday.getFullYear() + 30; 
						var mCheckYear = '20' + mYear;
						if (mCheckYear >= checkYear)
							mYear = '19' + mYear;
						else
							mYear = '20' + mYear;
						}
						var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
						if (!dateValid(vDateValueCheck)) {
							alert("Invalid Date\nPlease Re-Enter");
							vDateName.value = "";
							vDateName.focus();
							vDateName.select();
							return false;
						}
						return true;
					} else {
						// Reformat the date for validation and set date type to a 1
						if (vDateValue.length >= 8 && dateCheck) {
							// mmddyyyy
							if (vDateType == 1)  {
								var mDay = vDateName.value.substr(2,2);
								var mMonth = vDateName.value.substr(0,2);
								var mYear = vDateName.value.substr(4,4)
								vDateName.value = mMonth+strSeperator+mDay+strSeperator+mYear;
							}
							// yyyymmdd
							if (vDateType == 2) {
								var mYear = vDateName.value.substr(0,4)
								var mMonth = vDateName.value.substr(4,2);
								var mDay = vDateName.value.substr(6,2);
								vDateName.value = mYear+strSeperator+mMonth+strSeperator+mDay;
							}
							// ddmmyyyy
							if (vDateType == 3) {
								var mMonth = vDateName.value.substr(2,2);
								var mDay = vDateName.value.substr(0,2);
								var mYear = vDateName.value.substr(4,4)
								vDateName.value = mDay+strSeperator+mMonth+strSeperator+mYear;
							}
							//Create a temporary variable for storing the DateType and change
							//the DateType to a 1 for validation.
							var vDateTypeTemp = vDateType;
							vDateType = 1;
							var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
							if (!dateValid(vDateValueCheck)) {
								alert("Invalid Date\nPlease Re-Enter");
								vDateType = vDateTypeTemp;
								vDateName.value = "";
								vDateName.focus();
								vDateName.select();
								return false;
							}
							vDateType = vDateTypeTemp;
							return true;
						} else {
							if (((vDateValue.length < 8 && dateCheck) || (vDateValue.length == 9 && dateCheck)) && (vDateValue.length >=1)) {
								alert("Invalid Date\nPlease Re-Enter");
								vDateName.value = "";
								vDateName.focus();
								vDateName.select();
								return false;
				         	}
      					}
					}
				   
				// Non isNav Check 
				} else {

					if (vDateValue.length < 8) {
						alert("Invalid Date\nPlease Re-Enter");
						vDateName.value = "";
						vDateName.focus();
						return true;
					}
					// Reformat date to format that can be validated. mm/dd/yyyy
					if (vDateValue.length >= 8 && dateCheck) {
						
						//Check if seperator already included, if so do direct validation of date
						if ((vDateValue.indexOf("-") >= 1) || (vDateValue.indexOf("/") >= 1)) {
						
							if (!dateValid(vDateValue)) {
								alert("Invalid Date\nPlease Re-Enter");								
								vDateName.value = "";
								vDateName.focus();
								vDateName.select();
								return false;
							} else {
								return true;
							}
							
						}
						
						// Additional date formats can be entered here and parsed out to
						// a valid date format that the validation routine will recognize.
						// mm/dd/yyyy
						if (vDateType == 1) {
							var mMonth = vDateName.value.substr(0,2);							
							var mDay = vDateName.value.substr(2,2);
							var mYear = vDateName.value.substr(6,4);
						}
						// yyyy/mm/dd	
						if (vDateType == 2) {
							var mYear = vDateName.value.substr(0,4)
							var mMonth = vDateName.value.substr(5,2);
							var mDay = vDateName.value.substr(8,2);
						}
						// dd/mm/yyyy
						if (vDateType == 3) {
							var mDay = vDateName.value.substr(0,2);
							var mMonth = vDateName.value.substr(3,2);
							var mYear = vDateName.value.substr(6,4)
						}
						if (vYearLength == 4) {
							if (mYear.length < 4) {
								alert("Invalid Date\nPlease Re-Enter");
								vDateName.value = "";
								vDateName.focus();
								return true;
						   }
						}
						// Create temp. variable for storing the current vDateType
						var vDateTypeTemp = vDateType;
						// Change vDateType to a 1 for standard date format for validation
						// Type will be changed back when validation is completed.
						vDateType = 1;
						// Store reformatted date to new variable for validation.
						var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
						if (mYear.length == 2 && vYearType == 4 && dateCheck) {
							//Turn a two digit year into a 4 digit year
							var mToday = new Date();
							//If the year is greater than 30 years from now use 19, otherwise use 20
							var checkYear = mToday.getFullYear() + 30; 
							var mCheckYear = '20' + mYear;
							if (mCheckYear >= checkYear) {
								mYear = '19' + mYear;
							} else {
								mYear = '20' + mYear;
								vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
							}
							// Store the new value back to the field.  This function will
							// not work with date type of 2 since the year is entered first.							
							// mm/dd/yyyy							
							if (vDateTypeTemp == 1) {
								vDateName.value = mMonth+strSeperator+mDay+strSeperator+mYear;
							}
							// dd/mm/yyyy
							if (vDateTypeTemp == 3) {
								vDateName.value = mDay+strSeperator+mMonth+strSeperator+mYear;
							}
						} 
						if (!dateValid(vDateValueCheck)) {
							alert("Invalid Date\nPlease Re-Enter");
							vDateType = vDateTypeTemp;
							vDateName.value = "";
							vDateName.focus();
							return true;
						}
						vDateType = vDateTypeTemp;
						return true;
					} else {
						if (vDateType == 1) {
							if (vDateValue.length == 2) {
								vDateName.value = vDateValue+strSeperator;
							}
							if (vDateValue.length == 5) {
								vDateName.value = vDateValue+strSeperator;
						   }
						}
						if (vDateType == 2) {
							if (vDateValue.length == 4) {
								vDateName.value = vDateValue+strSeperator;
							}
							if (vDateValue.length == 7) {
								vDateName.value = vDateValue+strSeperator;
						   }
						} 
						if (vDateType == 3) {
							if (vDateValue.length == 2) {
								vDateName.value = vDateValue+strSeperator;
							}
							if (vDateValue.length == 5) {
								vDateName.value = vDateValue+strSeperator;
						   }
						}
						return true;
				   }
				}
				if (vDateValue.length == 10 && dateCheck) {
					if (!dateValid(vDateName)) {
						// Un-comment the next line of code for debugging the dateValid() function error messages
						//alert(err);  
						alert("Invalid Date\nPlease Re-Enter");
						vDateName.focus();
						vDateName.select();
				   }
				}
				return false;
			} else {
				// If the value is not in the string return the string minus the last
				// key entered.
				if (isNav4) {
					vDateName.value = "";
					vDateName.focus();
					vDateName.select();
					return false;
				} else {
					alert("removing char...");
					vDateName.value = vDateName.value.substr(0, (vDateValue.length-1));
					return false;
		    }
   		}
	}
}

function dateValid(objName) {
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
// var err = 0;
var strMonthArray = new Array(12);
strMonthArray[0] = "Jan";
strMonthArray[1] = "Feb";
strMonthArray[2] = "Mar";
strMonthArray[3] = "Apr";
strMonthArray[4] = "May";
strMonthArray[5] = "Jun";
strMonthArray[6] = "Jul";
strMonthArray[7] = "Aug";
strMonthArray[8] = "Sep";
strMonthArray[9] = "Oct";
strMonthArray[10] = "Nov";
strMonthArray[11] = "Dec";
//strDate = datefield.value;
strDate = objName;
if (strDate.length < 1) {
return true;
}
for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
strDateArray = strDate.split(strSeparatorArray[intElementNr]);
if (strDateArray.length != 3) {
err = 1;
return false;
}
else {
strDay = strDateArray[0];
strMonth = strDateArray[1];
strYear = strDateArray[2];
}
booFound = true;
   }
}
if (booFound == false) {
if (strDate.length>5) {
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(2, 2);
strYear = strDate.substr(4);
   }
}
//Adjustment for short years entered
if (strYear.length == 2) {
strYear = '20' + strYear;
}
strTemp = strDay;
strDay = strMonth;
strMonth = strTemp;
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
for (i = 0;i<12;i++) {
if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
intMonth = i+1;
strMonth = strMonthArray[i];
i = 12;
   }
}
if (isNaN(intMonth)) {
err = 3;
return false;
   }
}
intYear = parseInt(strYear, 10);
if (isNaN(intYear)) {
err = 4;
return false;
}
if (intMonth>12 || intMonth<1) {
err = 5;
return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
err = 6;
return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
err = 7;
return false;
}
if (intMonth == 2) {
if (intday < 1) {
err = 8;
return false;
}
if (LeapYear(intYear) == true) {
if (intday > 29) {
err = 9;
return false;
   }
}
else {
if (intday > 28) {
err = 10;
return false;
      }
   }
}
return true;
}
function LeapYear(intYear) {
if (intYear % 100 == 0) {
if (intYear % 400 == 0) { return true; }
}
else {
if ((intYear % 4) == 0) { return true; }
}
return false;
}
//  End -->

///Function: Basic Email Validation
///Purpose: This script can validate any email field to ensure a properly formatted email is provided 
///Input: Email field to be checked, pass in as string
///Output: True/False for submittal of form
///Added by: Marc Giguere/Thomas Kumpik 
///Date Added: 7-20-2004 
///Change Log:
///	MG - 11/17/05 - Changed RegEx lib to more robust version

function IsEmailValid(sEmail)
{

	// Use Regular Expressions for Email Verification
	// Credit Reg-Ex Check: Gavin Sharp (http://www.glensharp.com/gavin/)
	REEmail = /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/
	
	if (!sEmail.match(REEmail))		
		return false;
	return true;
}

//Passes in object instead of direct string...
function IsEmailValidNew(sEmail)
{

	// Use Regular Expressions for Email Verification
	// Credit Reg-Ex Check: Gavin Sharp (http://www.glensharp.com/gavin/)
	REEmail = /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/
	
	//Check if blank, if so, ignore for now
	if (sEmail.value == '') {
		return true;
	} else {
		if (!sEmail.value.match(REEmail)) {
			alert("Please enter a valid email address.");		
			sEmail.select();
			return false;
		} else {
			return true;
		}
	}
}

///Function: Basic validation for the PdfForm
///Purpose: This script validates that a username and valid email were entered 
///Input: none
///Output: True/False for submittal of form
///Added by: Daniel Thompson 
///Date Added: 1-26-2011 
///Change Log:
function validateWhitePaperForm() {
	var alertMessage = '';
	var error = 0;
	var username = document.forms["WhitePaperForm"]["username"].value;
	var email = document.forms["WhitePaperForm"]["email"].value;
	
	//check that username is not empty
	if(username == null || username == '') {
		alertMessage += "Please enter a username.\n";
		error += 1;
	}
	
	// Use Regular Expressions for Email Verification
	// Credit Reg-Ex Check: Gavin Sharp (http://www.glensharp.com/gavin/)
	REEmail = /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/
	
	if(!email.match(REEmail)) {
		alertMessage += "Please enter a valid email address.";
		error += 1;
	}
	
	//if either form field failed validation, alert message with needed corrections
	if(error > 0){
		alert(alertMessage);	
		return false;
	}
	else{
		return true;	
	}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

/*============================================================================*/

/*

This routine checks the credit card number. The following checks are made:

1. A number has been provided
2. The number is a right length for the card
3. The number has an appropriate prefix for the card
4. The number has a valid modulus 10 number check digit if required

If the validation fails an error is reported.

The structure of credit card formats was gleaned from a variety of sources on 
the web.

Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below

Author:     John Gardner
Date:       1st November 2003
Updated:    26th Feb. 2005      Additional cards added by request

*/

/*
   If a credit card number is invalid, an error reason is loaded into the 
   global ccErrorNo variable. This can be be used to index into the global error  
   string array to report the reason to the user if required:
   
   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);
*/

var ccErrorNo = 0;
var ccErrors = new Array ()

ccErrors [0] = "Unknown card type";
ccErrors [1] = "No card number provided";
ccErrors [2] = "Credit card number is in invalid format";
ccErrors [3] = "Credit card number is invalid or does not match card type selected.";
ccErrors [4] = "Credit card number has an inappropriate number of digits";

function checkCreditCard (cardnumber, cardname) {

     
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "15,16", 
               prefixes: "3,1800,2131",
               checkdigit: true};
  cards [7] = {name: "Enroute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return ccErrors[ccErrorNo]; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return ccErrors[ccErrorNo]; 
  }
  
  // Check that the number is numeric, although we do permit a space to occur  
  // every four digits. 
  var cardNo = cardnumber
  var cardexp = /^([0-9]{4})\s?([0-9]{4})\s?([0-9]{4})\s?([0-9]{1,4})$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return ccErrors[ccErrorNo]; 
  }
    
  // Now remove any spaces from the credit card number
  cardexp.exec(cardNo);
  cardNo = RegExp.$1 + RegExp.$2 + RegExp.$3 + RegExp.$4;
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return ccErrors[ccErrorNo]; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
   
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return ccErrors[ccErrorNo]; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the 
  // length if all else was hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return ccErrors[ccErrorNo]; 
  };   
  
  // The credit card is in the required format.
  return 0;
}

function TrimString (str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

/*============================================================================*/
