var BeginningWhiteSpaceRegExp = /^\s+/;
var EndingWhiteSpaceRegExp = /\s+$/;

function CheckField(Required,WhichField,FieldType,DisplayName,ReqLength,Numeric) {
	var RegExp;
	var TestVal;
	var MatchChar;
	var ErrMsg = 'None';
		
	//Replace any whitespace at beginning and end of string with nothing	
	if (FieldType == 'Text' || FieldType == 'Alpha'  || FieldType == 'Date' || FieldType == 'Money' ||
		FieldType == 'MoneyWhole' || FieldType == 'Phone' || FieldType == 'Email' || FieldType == 'Password') {
		TestVal = WhichField.value.replace(BeginningWhiteSpaceRegExp,'');
		TestVal = TestVal.replace(EndingWhiteSpaceRegExp,'');
	} else { 
		if (WhichField.selectedIndex == -1 || WhichField.options[WhichField.selectedIndex].value == 0) {
			TestVal = '';
		} else {	
			TestVal = WhichField.options[WhichField.selectedIndex].text;
		}
	}
	if (TestVal == '' && Required == true) {
		ErrMsg = DisplayName + ' must be entered';
	} 
	
	
	//If required check has been passed, continue with field type edits 
	
	if (ErrMsg == 'None' && TestVal != '') {	
		
		//Check required length 	
		if (ReqLength > 0) {
			if (TestVal.length != ReqLength) {
				ErrMsg = DisplayName + ' must be ' + ReqLength + ' characters';
			}
		}  
	
		//For money, remove all commas and one decimal, then set to Numeric to force numeric check
		if (FieldType == 'Money') {
			RegExp = /,/g;
			TestVal = TestVal.replace(RegExp,'');
			RegExp = /\./;
			TestVal = TestVal.replace(RegExp,'');
			Numeric = true;
		}
		
		//For money whole dollars, remove all commas then set to Numeric to force numeric check
		if (FieldType == 'MoneyWhole') {
			RegExp = /,/g;
			TestVal = TestVal.replace(RegExp,'');
			Numeric = true;
		}


		//Numeric check - match on any non-numeric character. If found, return Error.
		if (Numeric == true) {
			RegExp = /\D/;
			MatchChar = TestVal.match(RegExp);
			if (MatchChar != null) {
				ErrMsg = DisplayName + ' must be numeric';
			}
		}
	
		//Alpha check - match on any non A-Z character. If found, return Error.
		if (FieldType == 'Alpha') {
			RegExp = /[^A-Z]/;
			TestVal = TestVal.toUpperCase();
			MatchChar = TestVal.match(RegExp);
			if (MatchChar != null) {
				ErrMsg = DisplayName + ' must be alphabetic';
			}
		}
	
		//Check for valid date
		if (FieldType == 'Date') {
			if (CheckDate(TestVal) == 'Error') {
				ErrMsg = DisplayName + ' must be a valid date in mm/dd/yy format';
			}
		}
		
		//Check for valid Phone
		if (FieldType == 'Phone') {
			var c;
			var numLth=0;
			for(i=0;i<TestVal.length;i++) {
			    c=TestVal.charAt(i);
			    //Allow left bracket in 1st position only, and only if right bracked entered too, ie. (617)
			    if (c == '(') { 
					if (i==0 && TestVal.charAt(4) == ')') {
						continue;
					} else {
						ErrMsg = DisplayName + ' contains invalid brackets.';
						break;
					}
				} 
				
				//Allow right bracket in 5th position only ie. (617)
			    if (c == ')') {	
					if (i==4) {
						continue;
					} else {
						ErrMsg = DisplayName + ' contains invalid brackets.';
						break;
					}
				}
			    
			    if (c == ' ') {
					//Allow space only after area code right bracket
					if (i==5 && TestVal.charAt(4) == ')') {
						 continue; 
					} else {   
					   ErrMsg = 'Embedded spaces are not allowed in ' + DisplayName + '.\nUse hyphen, period, or comma to seperate numbers.';
					   break;
					}
			    }
			    
			    //Comma, hyphen or period allowed
			    if (c==',' || c=='-' || c==".") {
					continue;
				} else {
					if (isNaN(c)) {  
						ErrMsg = DisplayName + ' cannot have non-numeric digits.'; 
					    break;
					} else {
						numLth = numLth + 1;
					}
				}
			}
			
		}		
	
		//Check for valid email address
		if (FieldType == 'Email') {
			var no=0;
			var c;
    
			for(i=0;i<TestVal.length;i++) {
				c=TestVal.charAt(i);
			    if(i==0) { 
			        if(!isNaN(c)) {
						no=2;  
					}
				}
			    if(c==' ') no=2;
			    if(c =='@')  no++;
			}

			if(no!=1 || TestVal.indexOf('@')<2) {
				ErrMsg = TestVal + ' is not a valid E-mail Address';
			}
				   
			if (TestVal.indexOf('.')<5) {
				ErrMsg = TestVal + ' is not a valid E-mail Address';
			}
		}
	}
	
	if (ErrMsg == 'None') {
		return('OK');
	} else {
		if (FieldType == 'List') {
			WhichField.selectedIndex = 0;
		}
		WhichField.focus();
		window.alert(ErrMsg);
		return('Error');
	} 
}

function CheckForDupName(list,textboxToCheck, currKey, EntityName) {
	
	var textToCheck = textboxToCheck.value.toUpperCase();

	//Replace any whitespace at beginning and end of string with nothing
	textToCheck = textToCheck.replace(BeginningWhiteSpaceRegExp,'');
	textToCheck = textToCheck.replace(EndingWhiteSpaceRegExp,'');
		
	for (i = 0; i < list.options.length; i++)  {
		if (list.options[i].text.toUpperCase() == textToCheck) {
			//Ignore current key text matching itself
			if (list.options[i].value == currKey) {
				continue;
			}
			textboxToCheck.focus();
			alert(EntityName + ' "' + list.options[i].text + '" already exists');
			return('Error');
		}
	}
}

function CheckForChange(Field1, Field2, CaseSensitive) {
	
	//If booleans passed convert to character
	if (Field1 == true) {
		Field1 = 'T';
	} else {
		if (Field1 == false) {
			Field1 = 'F';
		}
	}
	
	if (Field2 == true) {
		Field2 = 'T';
	} else {
		if (Field2 == false) {
			Field2 = 'F';
		}
	}
		
	//Replace any whitespace at beginning and end of strings with nothing
	Field1 = Field1.replace(BeginningWhiteSpaceRegExp,'');
	Field1 = Field1.replace(EndingWhiteSpaceRegExp,'');
	
	Field2 = Field2.replace(BeginningWhiteSpaceRegExp,'');
	Field2 = Field2.replace(EndingWhiteSpaceRegExp,'');

	//Convert both to uppercase before comparison
	if (CaseSensitive == false) {
		Field1 = Field1.toUpperCase();
		Field2 = Field2.toUpperCase();
	}
		
	if (Field1 == Field2) {
		return(false);
	} else {
		return(true);	
	}
}

function isBlank(WhichField) {
	
	var TestVal;
	
	if (WhichField.type == "select-one" ) {	 
		if (WhichField.selectedIndex == -1 || WhichField.options[WhichField.selectedIndex].value == 0) {
			TestVal = '';
		} else {	
			TestVal = WhichField.options[WhichField.selectedIndex].text;
		}
	} else {
		if (WhichField.type == "checkbox") {
			if (WhichField.checked == false) {
				TestVal = '';
			} else {
				TestVal = 'on';
			}
		} else {
			TestVal = WhichField.value;
		}
	}
	
	//Replace any whitespace at beginning and end of string with nothing	
	TestVal = TestVal.replace(BeginningWhiteSpaceRegExp,'');
	TestVal = TestVal.replace(EndingWhiteSpaceRegExp,'');

	if (TestVal == '') {
		return(true);
	} else {
		return(false);	
	} 
}
	
function trimSpaces(WhichField) {
	
	var TestVal;
	
	//Replace any whitespace at beginning and end of string with nothing	
	TestVal = WhichField.value.replace(BeginningWhiteSpaceRegExp,'');
	TestVal = TestVal.replace(EndingWhiteSpaceRegExp,'');
	
	return(TestVal);
}

function CheckDate(WhichDate) {
	
	var SplitStr;
	var SplitDate;
	var NumSplits;
	
	//Check for date separator either / or -
	SplitStr = WhichDate.indexOf("/");
	if (SplitStr == -1) {
		SplitStr = "-";
	} else {
		SplitStr = "/";
	}
	
	//Split by separator into mm dd yy
	SplitDate = WhichDate.split(SplitStr);
	NumSplits = SplitDate.length;
	if (NumSplits != 3) {
		return('Error');
	} else {
		mm = SplitDate[0];
		dd = SplitDate[1];
		yy = SplitDate[2];
	}
	if(mm.length>2){
		return('Error');
	}
	if(dd.length>2){
		return('Error');
	}
	
	if (yy.length != 2) {
		if(yy.length!=4){
			return('Error');
		}else{
			if (isNaN(yy) || yy<0  || yy>2100 || yy < 1800) return('Error');
		}
	}else{
		if (isNaN(yy) || yy<0  || yy>99) return('Error');
	}
			
	//basic error checking - check for number and proper range
	if (isNaN(mm) || mm<1  || mm>12) return('Error');
	if (isNaN(dd) || dd<1  || dd>31) return('Error');
	

	
	//advanced error checking

	// months with 30 days
	if (mm==4 || mm==6 || mm==9 || mm==11) {
		if (dd==31) return('Error');

	}

	// february, leap year
	if (mm==2) {
		if (dd>29) 	return('Error');

		if (dd==29) {
			if ((yy % 4 == 0 && yy % 100 != 0) || yy % 400 == 0) {
				return('OK');
			} else {
				return('Error');
			}
		}
	}
	return('OK');
}

function getMMDDCCYY(DateMMDDYY) {
	var Date1;
	var dd;
	var mm;
	var yr;
	Date1 = new Date(DateMMDDYY);
	dd = Date1.getDate();
	mm = Date1.getMonth();
	yr = Date1.getYear();
	if (yr < 50) {
		yr = yr + 2000;
	}
	return (new Date(yr,mm,dd));
}

function MoveSelectToSelect(selFrom,selTo){
	var i;
	var j;
	var k;
	var selValue;
	var selText;
	var actCode;
	var valueToBump;
	var textToBump;
	var SplitItemKey;
	var SelFromAssn;
	var lngFromLength = selFrom.options.length;
  	var lngToLength = selTo.options.length;

	for (i = 0; i < lngFromLength; i++)  {
		if (selFrom.options[i].selected == true) {
		
			selValue = selFrom.options[selFrom.selectedIndex].value;
			selText =  selFrom.options[selFrom.selectedIndex].text;
			
			
			
						
			//Prepare selFrom item to be added  to selTo
			//If value is already prefixed with an Action code, this item is
			//now going back to its original select box, so remove action code.
			//Otherwise its a first time move, so add action code.
			if (selValue.substr(0,1) == 'A' || selValue.substr(0,1) == 'D') {
				selValue = selValue.substr(1);
				actCode = '';
			} else {
				//If selFrom name includes the string "Ass" then we're moving
				//an Assigned item back to Available, so Action code is 'D',
				//else we're moving Available to Assigned so Action cod is 'A'
				SelFromAssn = selFrom.name.indexOf("Ass");
				if (SelFromAssn != -1) {			//string 'Ass' was found
					actCode = 'D'
				} else {
					actCode = 'A'
				}
			}
			selValue = actCode + selValue;
      
			//Remove option from selFrom and decrease selFrom length
			selFrom.options[i] = null;
			i -= 1;
			lngFromLength -= 1;
			
			//Find proper alphabetical place in selTo list, save index in var j
			for (j = 0; j < lngToLength; j++)  {
				if (selText.toUpperCase() < selTo.options[j].text.toUpperCase()) {
					break;
				}
			}
	  
			//Bump up remainder of selTo list to create empty slot for new entry
			for (k = lngToLength; k > j; k--)  {
				valueToBump = selTo.options[k-1].value;
				textToBump =  selTo.options[k-1].text;
				selTo.options[k] = new Option(textToBump,valueToBump);  // KEY! 
			}
			
			//Now add new entry using saved index postion (j) and increase selTo length 	
			selTo.options[j] = new Option(selText,selValue);  // KEY! 
			lngToLength += 1;
		} 
	} 
	//Unselect all items in both dropdowns
  	selFrom.selectedIndex = -1;
  	selTo.selectedIndex = -1;
} 

function SelectAll(whichSel) {
	var lngSel = whichSel.options.length;
	for (i = 0; i < lngSel; i++)  {
		whichSel.options[i].selected = true;
	}
}