// This set of function are general includes for validation
// They are designed in pairs the validation and the event function
// the event function will call the validation with the event src



// The following functions initiate the functions needed to validate 
// various text fields.  A function with the following numbers in the
// name indicate:
//	1 - initiates the function for an HTML and SQL check
//	2 - initiates the function to check for a number with the maximum 
//		field length
//	3 - initiates the function to begin each word with a capital
//	4 - initiates the function to check for non-blanks
//	5 - initiates the function to make all characters upper case
//  vs_valid_phone_no - this function checks for numbers and to be sure
//		that numbers fill up every available character in the field

function func1(item){
	if (item.value == 0)
		return true;
	ToCheck = item;
	Validated2 = Check(ToCheck);
	item.value = Validated2;
	return true;
}

function func1ValidNumber(item){
	var strErrorMsg = display_name(item) + " must be a valid number";
	if (item.value == 0)
		return true;
	ToCheck = item;
	Validated2 = Check(ToCheck);
	
	if (isNaN(Validated2)){
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	item.value = Validated2;
	return true;
}

function func13(item){

	ToCheckValue = item.value;
	if (ToCheckValue == "")
		return true;
	ToCheck = item;
	Validated1 = pcase(ToCheckValue);
	item.value = Validated1;
	Validated2 = Check(item);
	item.value = Validated2;
	return true;
}	

function func134(item){
	
	var strErrorMsg = display_name(item) + " can not have a blank value";
	ToCheck = item;
	Validated1 = vs_non_blank(ToCheck);
	if (Validated1 == false){
		item.focus();
		alert(strErrorMsg);
		return false;
	}	
	//alert("I got here 0");
	ToCheckValue = item.value;
	if (ToCheckValue == "")
		return true;
	// ToCheck = item;
	Validated1 = pcase(ToCheckValue);
	item.value = Validated1;
	Validated2 = Check(item);
	item.value = Validated2;
	return true;
}	

function func777(item){
	alert("I got here 1");
	var strErrorMsg = display_name(item) + " can not have a blank value";
	ToCheck = item;

	alert("I got here 2");
	return false;
	
	Validated1 = vs_non_blank(ToCheck);
	if (Validated1 == false){
		item.focus();
		alert(strErrorMsg);
		return false;
	}	

	ToCheckValue = item.value;
	if (ToCheckValue == "")
		return true;
	// ToCheck = item;
	Validated1 = pcase(ToCheckValue);
	item.value = Validated1;
	Validated2 = Check(item);
	item.value = Validated2;
	return true;
}	

function func14(item){

	ToCheck = item;
	Validated1 = vs_non_blank(ToCheck);
	if (Validated1 == false){
		item.focus();
		var strErrorMsg = display_name(item) + " can not have a blank value";
		alert(strErrorMsg);
		return false;
	}	
	Validated2 = Check(ToCheck);
	item.value = Validated2;
	return true;
}	

function func145(item){

	ToCheck = item;
	Validated1 = vs_non_blank(ToCheck);
	if (Validated1 == false){
		item.focus();
		var strErrorMsg = display_name(item) + " can not have a blank value";
		alert(strErrorMsg);
		return false;
	}	
	Validated2 = Check(ToCheck);
	Validated2 = Validated2.toUpperCase();
	item.value = Validated2;
	return true;
}	

function func24(item){

	ToCheck = item;
	Validated1 = vs_non_blank(ToCheck);
	if (Validated1 == false){
		item.focus();
		var strErrorMsg = display_name(item) + " can not have a blank value";
		alert(strErrorMsg);
		return false;
	}
	var strErrorMsg = display_name(item) + " must be a valid number";
	if ((item.value.length != 5) || (isNaN(item.value))){
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	return true;
}

function func245length2(item){

	ToCheck = item;
	Validated1 = vs_non_blank(ToCheck);
	if (Validated1 == false){
		item.focus();
		var strErrorMsg = display_name(item) + " can not have a blank value";
		alert(strErrorMsg);
		return false;
	}
	if ((item.value.length != 2)){
		item.focus();
		var strErrorMsg = display_name(item) + " must be a valid State";
		alert(strErrorMsg);
		return false;
	}	
	Validated2 = Check(ToCheck);
	Validated2 = Validated2.toUpperCase();
	item.value = Validated2;
	return true;
}		

function func24length2(item){

	ToCheck = item;
	Validated1 = vs_non_blank(ToCheck);
	if (Validated1 == false){
		item.focus();
		var strErrorMsg = display_name(item) + " can not have a blank value";
		alert(strErrorMsg);
		return false;
	}
	var strErrorMsg = display_name(item) + " must be a valid number";
	if ((item.value.length != 2) || (isNaN(item.value))){
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	return true;
}	
	
function func24length3(item){

	ToCheck = item;
	Validated1 = vs_non_blank(ToCheck);
	if (Validated1 == false){
		item.focus();
		var strErrorMsg = display_name(item) + " can not have a blank value";
		alert(strErrorMsg);
		return false;
	}
	var strErrorMsg = display_name(item) + " must be a valid number";
	if ((item.value.length != 3) || (isNaN(item.value))){
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	return true;
}		

function func24length4(item){

	ToCheck = item;
	Validated1 = vs_non_blank(ToCheck);
	if (Validated1 == false){
		item.focus();
		var strErrorMsg = display_name(item) + " can not have a blank value";
		alert(strErrorMsg);
		return false;
	}
	var strErrorMsg = display_name(item) + " must be a valid number";
	if ((item.value.length != 4) || (isNaN(item.value))){
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	return true;
}		

function checkdate(item){
//	window.onerror=null // for all other strange errors
	var strErrorMsg = display_name(item) + " must be a date in the format mm/dd/yyyy";
	var err=0
	a=item.value
	if (a.length != 10) err=1
	b = a.substring(0, 2)// month
	c = a.substring(2, 3)// '/'
	d = a.substring(3, 5)// day
	e = a.substring(5, 6)// '/'
	f = a.substring(6, 10)// year

	//basic error checking
	if (b<1 || b>12) err = 1
	if (c != '/') err = 1
	if (d<1 || d>31) err = 1
	if (e != '/') err = 1
	if (f<1920 || f>2061) err = 1
	
	//advanced error checking

	// months with 30 days
	if (b==4 || b==6 || b==9 || b==11){
		if (d==31) err=1
	}

	// february, leap year
	if (b==2){
		// feb
		var g=parseInt(f/4)
		if (isNaN(g)) {
			err=1
		}

		if (d>29) err=1
		if (d==29 && ((f/4)!=parseInt(f/4))) err=1
	}

	if (err==1){
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	return true;
}

function display_name(item) {
	var strDisplay = item.getAttribute("DisplayName");
	if (strDisplay==null || strDisplay=="")
		strDisplay="Field";
	return strDisplay;
} 

function default_value(item) {
	var strDefault = item.defaultValue;
	if (strDefault==null || strDefault=="")
		strDefault="";
	return strDefault;
}

function pcase(str) {

	//returns str in proper-noun case (first letter uppercase)
	strlen = str.length;
	jj = str.substring(0,1).toUpperCase();
	jj = jj + str.substring(1,strlen).toLowerCase();
	for (i = 2; i <= strlen; i++) {
		if (jj.charAt(i)==" " || jj.charAt(i)==".") {
			lefthalf = jj.substring(0,i+1);
			righthalf = jj.substring(i+1,strlen);
			righthalf = righthalf.substring(0,1).toUpperCase()+righthalf.substring(1,strlen);
			jj=lefthalf+righthalf;
		}
	}
	return jj;
}

// This is the HTML & SQL check function

function Del(Word) {
	// This section of code checks for HTML tags
	var Word = Word.value;
	
	gtcheck = Word.indexOf(">");
	len = 0
	while (gtcheck != -1){
		len = Word.length;
		a = Word.indexOf(">");
		b = Word.substring(0,a);
		c = Word.substring(a+1,len);
		Word = b + c;
		gtcheck = Word.indexOf(">");
	}
	
	ltcheck = Word.indexOf("<");
	len = 0
	while (ltcheck != -1){
		len = Word.length;
		h = Word.indexOf("<");
		i = Word.substring(0,h);
		j = Word.substring(h+1,len);
		Word = i + j;
		ltcheck = Word.indexOf("<");
	}
		
	// This section of code checks for quotes
	// The SQL statements can't have quotes within the text fields
	
	quotecheck = Word.indexOf("\"");
	//if (quotecheck == -1)
	//	return Word;
	len = 0
	while (quotecheck != -1){
		len = Word.length;
		e = Word.indexOf("\"");
		f = Word.substring(0,e);
		g = Word.substring(e+1,len);
		Word = f + g;
		quotecheck = Word.indexOf("\"");
	}
		
	// This section of code checks for single quotes
	// The SQL statements can't have single quotes within the text fields
	
	squotcheck = Word.indexOf("\'");
	if (squotcheck == -1)
		return Word;
	len = 0
	while (squotcheck != -1){
		len = Word.length;
		k = Word.indexOf("\'");
		l = Word.substring(0,k);
		m = Word.substring(k+1,len);
		////New code to switch a single quote to a reverse single quote 04/08/2009///
		Word = l + "`" + m;
		/////////////////////////////////////////////////////////////////////////////
		//Word = l + m;
		squotcheck = Word.indexOf("\'");
	}	
	return Word;
}

function Check(item){
	ToCheck = item;
	Checked = Del(ToCheck);
	return Checked;
}

// End HTML & SQL check function

function trim_string() {
	var ichar, icount;
	var strValue = this;
	ichar = strValue.length - 1;
	icount = -1;
	while (strValue.charAt(ichar)==' ' && ichar > icount)
		--ichar;
	if (ichar!=(strValue.length-1))
		strValue = strValue.slice(0,ichar+1);
	ichar = 0;
	icount = strValue.length - 1;
	while (strValue.charAt(ichar)==' ' && ichar < icount)
		++ichar;
	if (ichar!=0)
		strValue = strValue.slice(ichar,strValue.length);
	return strValue;
}

function date_toSimpleForm() {
	var toSimpleForm = new String;
	toSimpleForm = this.toLocaleString();
	toSimpleForm = toSimpleForm.substring(0,toSimpleForm.indexOf(' '));
	return toSimpleForm;
}


function es_non_blank() {
	var item = event.srcElement;
	event.returnValue = vs_non_blank(item);
}
function vs_non_blank(item) {

	item.value=item.value.Trim();
	if (item.value.length==0) {
		return false;
	}
	return true;
}


function es_valid_number() {
	var item = event.srcElement;
	event.returnValue = vs_valid_number(item);
}
function vs_valid_number(item) {
	var strErrorMsg = display_name(item) + " must be a valid number";
	var strDefault = default_value(item);
	if (strDefault.length==0) {
		strDefault="0";
	}
	item.value=item.value.Trim();
	if (item.value.length==0)
		item.value=strDefault;
	var num = ".0123456789";
	for (var intLoop = 0; intLoop < item.value.length; intLoop++) {
		if (num.indexOf(item.value.charAt(intLoop)) == -1) {
			item.focus();
			alert(strErrorMsg);
			return false;
		}
	}
	if (item.value.indexOf(".")!=item.value.lastIndexOf(".")) {
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	return true;
}

function es_valid_phone_number() {
	var item = event.srcElement;
	event.returnValue = vs_valid_number(item);
}
function vs_valid_phone_number(item) {
	var strErrorMsg = display_name(item) + " must be a valid number";
	
	if (item.value=="")
		return true;

	
	if (isNaN(item.value)){
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	return true;
}

// This function checks for a valid number but there is not a field
// length check

function vs_valid_number_nolength(item) {
	var strErrorMsg = display_name(item) + " must be a valid number";
	
	if (item.value=="")
		return true;

	
	if (isNaN(item.value)) {
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	return true;
}


function vs_valid_phone_number4(item) {
	var strErrorMsg = display_name(item) + " must be a valid number";
		
	if ((item.value.length != item.size) || (isNaN(item.value))){
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	return true;
}	


function es_valid_hours() {
	var item = event.srcElement;
	event.returnValue = vs_valid_hours(item);
}
function vs_valid_hours(item) {
	var strErrorMsg = display_name(item);
	if (!vs_valid_number(item))
		return false;
	var itemValue = new Number(item.value);
	if ((itemValue < 0 || itemValue > 80)) {
		item.focus();
		alert(strErrorMsg + " must have a value from 0 to 80 hours");
		return false;
	}
	itemValue *= 4;
	if ((itemValue)!=Math.ceil(itemValue)) {
		item.focus();
		alert(strErrorMsg + " must be a valid quartely increment");
		return false;
	}
	return true;
}


function es_valid_date() {
	var item = event.srcElement;
	event.returnValue = vs_valid_date(item);
}
function vs_valid_date(item) {
	var strErrorMsg = display_name(item);
	if (isNaN(Date.parse(item.value))) {
		item.focus();
		alert(strErrorMsg + " must be a valid Date");
		return false;
	}
	var dtItem = new Date(Date.parse(item.value));
	item.value = dtItem.toSimpleForm();
	return true;
}


function es_item_selected() {
	var item = event.srcElement;
	event.returnValue = vs_item_selected(item);
}
function vs_item_selected(item) {
	var strErrorMsg = display_name(item) + " must be a valid selection";
	if (item.selectedIndex==0) {
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	return true;
}

function es_valid_zip() {
	var item = event.srcElement;
	event.returnValue = vs_valid_zip(item);
}
function vs_valid_zip(item) {
	var strErrorMsg = display_name(item) + " must be of the form 99999-9999";
	item.value=item.value.Trim();
	if (!(/^\d{5}$/.test(item.value) || /^\d{5}-\d{4}$/.test(item.value))) {
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	return true;
}

function es_valid_ssnbr() {
	var item = event.srcElement;
	event.returnValue = vs_valid_ssnbr(item);
}
function vs_valid_ssnbr(item) {
	var strErrorMsg = display_name(item) + " must be of the form 999-99-9999";
	item.value=item.value.Trim();
	if (!(/^\d{3}-\d{2}-\d{4}$/.test(item.value))) {
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	return true;
}


function validateEmail(addr,man,db) {
if (addr == '' && man) {
   if (db) alert('email address is mandatory');
   return false;
}
if (addr == '') return true;
var invalidChars = '\/\'\\ ";:?!()[]\{\}^|';
for (i=0; i<invalidChars.length; i++) {
   if (addr.indexOf(invalidChars.charAt(i),0) > -1) {
      if (db) alert('email address contains invalid characters');
      return false;
   }
}
for (i=0; i<addr.length; i++) {
   if (addr.charCodeAt(i)>127) {
      if (db) alert("email address contains non ascii characters.");
      return false;
   }
}

var atPos = addr.indexOf('@',0);
if (atPos == -1) {
   if (db) alert('email address must contain an @');
   return false;
}
if (atPos == 0) {
   if (db) alert('email address must not start with @');
   return false;
}
if (addr.indexOf('@', atPos + 1) > - 1) {
   if (db) alert('email address must contain only one @');
   return false;
}
if (addr.indexOf('.', atPos) == -1) {
   if (db) alert('email address must contain a period in the domain name');
   return false;
}
if (addr.indexOf('@.',0) != -1) {
   if (db) alert('period must not immediately follow @ in email address');
   return false;
}
if (addr.indexOf('.@',0) != -1){
   if (db) alert('period must not immediately precede @ in email address');
   return false;
}
if (addr.indexOf('..',0) != -1) {
   if (db) alert('two periods must not be adjacent in email address');
   return false;
}
var suffix = addr.substring(addr.lastIndexOf('.')+1);
if (suffix.length != 2 && suffix != 'com' && suffix != 'net' && suffix != 'org' && suffix != 'edu' && suffix != 'int' && suffix != 'mil' && suffix != 'gov' & suffix != 'arpa' && suffix != 'biz' && suffix != 'aero' && suffix != 'name' && suffix != 'coop' && suffix != 'info' && suffix != 'pro' && suffix != 'museum') {
   if (db) alert('invalid primary domain in email address');
   return false;
}
return true;
}



function es_valid_email() {
	var item = event.srcElement;
	event.returnValue = vs_valid_email(item);
}
function vs_valid_email4(item) {
	var strErrorMsg = display_name(item) + " is not a valid Email";
	
//	alert("You made it here");
		
	if (item.value=="") {
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	
	item.value=item.value.Trim();
	item.value = item.value.toLowerCase();
	if (!(/^[\w\_.]+@[a-z\_.]+$/.test(item.value))) {
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	return true;
}

function vs_valid_email(item) {
	var strErrorMsg = display_name(item) + " is not a valid Email";
		
	if (item.value=="")
		return true;
	
	
	item.value=item.value.Trim();
	if (!(/^[\w\.]+@[a-z\.]+$/.test(item.value))) {
		item.focus();
		alert(strErrorMsg);
		return false;
	}
	return true;
}


function moneyFormat(textObj) {
   var newValue = textObj.value;
   var decAmount = "";
   var dolAmount = "";
   var decFlag = false;
   var aChar = "";
   
   // ignore all but digits and decimal points.
   for(i=0; i < newValue.length; i++) {
      aChar = newValue.substring(i,i+1);
      if(aChar >= "0" && aChar <= "9") {
         if(decFlag) {
            decAmount = "" + decAmount + aChar;
         }
         else {
            dolAmount = "" + dolAmount + aChar;
         }
      }
      if(aChar == ".") {
         if(decFlag) {
            dolAmount = "";
            break;
         }
         decFlag=true;
      }
   }
   
   // Ensure that at least a zero appears for the dollar amount.

   if(dolAmount == "") {
      dolAmount = "0";
   }
   // Strip leading zeros.
   if(dolAmount.length > 1) {
      while(dolAmount.length > 1 && dolAmount.substring(0,1) == "0") {
         dolAmount = dolAmount.substring(1,dolAmount.length);
      }
   }
   
   // Round the decimal amount.
   if(decAmount.length > 2) {
      if(decAmount.substring(2,3) > "4") {
         decAmount = parseInt(decAmount.substring(0,2)) + 1;
         if(decAmount < 10) {
            decAmount = "0" + decAmount;
         }
         else {
            decAmount = "" + decAmount;
         }
      }
      else {
         decAmount = decAmount.substring(0,2);
      }
      if (decAmount == 100) {
         decAmount = "00";
         dolAmount = parseInt(dolAmount) + 1;
      }
   }
   
   // Pad right side of decAmount
   if(decAmount.length == 1) {
      decAmount = decAmount + "0";
   }
   if(decAmount.length == 0) {
      decAmount = decAmount + "00";
   }
   
   // Check for negative values and reset textObj
   if(newValue.substring(0,1) != '-' ||
         (dolAmount == "0" && decAmount == "00")) {
      textObj.value = dolAmount + "." + decAmount;

   }
   else{
      textObj.value = '-' + dolAmount + "." + decAmount;
   }
return textObj.value;
}




// build the validation object
function validation_setup() {
	this.func1=func1;
	this.func1ValidNumber=func1ValidNumber;
	this.func13=func13;
	this.func134=func134;
	this.func14=func14;
	this.func145=func145;
	this.func24=func24;
	this.func24length2=func24length2;
	this.func24length4=func24length4;
	this.func24length3=func24length3;
	this.validphoneno = vs_valid_phone_number;
	this.validphoneno4 = vs_valid_phone_number4;
	this.validnumbernolength = vs_valid_number_nolength;
	this.eventNonBlank = es_non_blank;
	this.nonBlank = vs_non_blank;
	this.eventValidNumber = es_valid_number;
	this.validNumber = vs_valid_number;
	this.eventValidHours = es_valid_hours;
	this.validHours = vs_valid_hours;
	this.eventValidDate = es_valid_date;
	this.validDate = vs_valid_date;
	this.eventItemSelected = es_item_selected;
	this.itemSelected = vs_item_selected;
	this.eventValidZip = es_valid_zip;
	this.validZip = vs_valid_zip;
	this.eventValidSSNbr = es_valid_ssnbr;
	this.validSSNbr = vs_valid_ssnbr;
	this.eventValidEmail = es_valid_email;
	this.validEmail = vs_valid_email;
	this.validEmail4 = vs_valid_email4;
	this.moneyFormat = moneyFormat;
	this.checkdate = checkdate;
	return this;
}

// Extend the string object to include a trim function
String.prototype.Trim = trim_string;
// Extend the date object to include a simple form string conversion
Date.prototype.toSimpleForm = date_toSimpleForm;

// Construct the validation object
var NSvalidation = new Object;
NSvalidation = validation_setup();


// This set of function are for processing the key press event
// Used to restrict input on numerics and pure textual fields

function kp_integer() {
	if ((event.keyCode < 48 || event.keyCode > 57))
		event.returnValue = false;
}
function kp_numeric() {
	if ((event.keyCode != 46) && (event.keyCode < 48 || event.keyCode > 57))
		event.returnValue = false;
	if (event.keyCode == 46) {
		if (event.srcElement.value.indexOf(".") > -1)
			event.returnValue = false;
	}
}


function kp_character() {
	if ((event.keyCode < 65 || event.keyCode > 90) && (event.keyCode < 97 || event.keyCode > 122))
		event.returnValue = false;
}
function kp_convert_upper() {
	if ((event.keyCode >= 97 && event.keyCode <= 122))
		event.keyCode -= 32;
}
function kp_convert_lower() {
	if ((event.keyCode >= 65 && event.keyCode <= 90))
		event.keyCode += 32;
}


function kp_setup() {
	this.Integer = kp_integer;
	this.Numeric = kp_numeric;
	this.Character = kp_character;
	this.ConvertUpper = kp_convert_upper;
	this.ConvertLower = kp_convert_lower;
	return this;
}

var keyPressInput = new Object;
keyPressInput = kp_setup();
