// validation.js

/*
Common Client side validations to be implemented
*/
//CONSTANTS
VALID_DATE_MASK="^[0-9]{2}/[0-9]{2}/[0-9]{4}$";
VALID_WHOLE_NUMBER="^[0-9]+$";
//REG_MASK=/((\b|[0-9])+[uU]{1}\b)|(\s|[^0-9])\.[0-9]+\b|[1-9]+\.0+\b|\b(MS|MSO4)\b|\bIU\b|[Qq]{1}\.?[Oo]{1}\.?[Dd]{1}|[Qq]{1}\.?[Dd]{1}\.?|\b[Xx]\s?[0-9]+\s?[Dd]{1}\b|&micro;|\u00B5|&oslash;|\u2205/;
REG_MASK=/\s[Uu](\s|\.)|(\s*)(\d+)+[uU](\b|\.)|^[uU]\b|\B\.[0-9]+\b|(\s|[^0-9])\.[0-9]+\b|\b(\sMS(\s|\n|r|\b|$)|MSO4|MS04)\b|\bIU\b|[Qq]{1}\.?[Oo]{1}\.?[Dd]{1}|[Qq]{1}\.?[Dd]{1}\.?|\b[Xx]\s?[0-9]+\s?[Dd]{1}\b|&micro;|\u00B5|&oslash;|\u2205/;
//Error colors
NORMAL_COLOR="white";
ERROR_COLOR="#ff8e82";
FORM_COLOR = "#FFFFFF";

//Valid date check
	function isValidDatePlus(dateVal) {
   		dateRegexp = new RegExp(VALID_DATE_MASK);
		var match = dateRegexp.exec(dateVal);
		if(match == null) return false;
		var oDate = new Date();
		oDate.setTime(Date.parse(dateVal));
		var month = oDate.getMonth() + 1; //month is 0 based
		var day = oDate.getDate();
		var year = oDate.getFullYear();
		month=(month>9)?month:"0" + month;
		day = (day>9)?day:"0" + day;
		var workDate = month + "/" + day + "/" + year;
		return (workDate==dateVal);
	}
	
	function isValidWholeNumber(val) {

   		regexp = new RegExp(VALID_WHOLE_NUMBER);
   		
		var match = regexp.exec(val);
		
		return (match != null);
	}
	//DK 06.18.08 bug#5525 - check if data is whole number
	function isValidWholeNumber(val, elementName) {
	
	   var stringValue = trim(val.value);

	   if(stringValue == ""){		
	       return "";	   		
		}else{		
		   var valid = /^\d+$/.test(stringValue);//DK-08.14.08 bug#5659		
		   if(valid == false){		     
			   setErrorColor(val);			 
		       return elementName + " is not an whole number.\n"
		   }
		}
		
		return "";
	}
	
//Validating a Time 
//give me a value (example textbox:  isValidTime(oForm.someText.value))
//Added by DS 8/03/2004
	function isValidTime(timeval){
		return /\d{1,2}[:]\d{2}( [aApP][mM])+$/.test(timeval);
	}



//Validating that any array of radio has atleast ONE item checked
//Written by David Seymore 08/04/2004
	function isRadioArrayChecked(radArray){
		length = radArray.length;
		bol = false;
		i = 0;
		while(!bol){
			if (radArray[i].checked){
				bol = true;
			}
			i++;
		}
		return bol;
	}
	
		//DK 9.8.07 OPD Nursing Infection Control ehn 
	//Checks explain and <, > depends on Yes/No selection
	function isEmptyConditionalOPD(elementObject, radArray, needLocation, elementName, grterLessName){
    	  	
    	for(i=0; i<radArray.length; i++){
   	
    	  if(i == needLocation*1){
    	      if (radArray[i].checked == true){
    	        var errorMsg = '';
    	        if( elementObject.value == ""){
    	            setErrorColor(elementObject);
    	            errorMsg = elementName + " is required\n";
    	        }
    	   
				return errorMsg;
			  }	 
    	   }
    	}
	  return ""
   }
   
	//DK 9.8.07 OPD Nursing Infection Control ehn 
	//Checks whether prompted questions are answered properly or not
	function checkTreatedOPDQuest(elementObject, radArray, needLocation, elementName){
 
    	  var allowedPrompt1='Was patient treated(Yes/No/Unknown)?';
    	  var allowedPrompt2='When:';
          var strArray=new Array();
          
          var allowedPrompt=elementObject.value;
          
          if(allowedPrompt.indexOf('\n') > -1){
            strArray=allowedPrompt.split("\n");
          }else{
            var indexNum = allowedPrompt.indexOf('When:');
            strArray[0] = allowedPrompt.substr(0, indexNum-1 );//entered first question
            strArray[1] = allowedPrompt.substr(indexNum, allowedPrompt.length );//entered second question
            //alert(' strArray[0]: ' +  strArray[0] + ' strArray[1]: ' +  strArray[1]);
          }
          
          
    	for(i=0; i<radArray.length; i++){
    	
    	  if(i == needLocation){
    	  //if user overwrote the prompted question, just check for empty
    	      if((!(strArray[0].indexOf(allowedPrompt1) > -1) || !(strArray[1].indexOf(allowedPrompt2) > -1)) && elementObject.value.length > 0){
    	           return "";
    	      }
    	      if ((radArray[i].checked == true)&&(strArray[0].indexOf(allowedPrompt1) > -1 && strArray[1].indexOf(allowedPrompt2) > -1)){
    	        var tempStr1 = strArray[0].replace(allowedPrompt1,"").toLowerCase();
    	        var tempStr2 = strArray[1].replace(allowedPrompt2,"").toLowerCase();
    	       // tempStr1 = tempStr1.replace(/^\s+|\s+$/g, '');
    	       // tempStr2 = tempStr2.replace(/^\s+|\s+$/g, '');
    	     
    	        if(((tempStr1.indexOf('yes') != -1 ) || (tempStr1.indexOf('no') != -1) || (tempStr1.indexOf('unknown') != -1)) && tempStr2.length > 0){  	                      
    	              return ""
    	        }else{
    	            setErrorColor(elementObject);
				    return elementName + " was not answered properly\n";
    	        } 	       
			  }//third if
    	   }//first if
    	}//for
	  return ""
   }
   
   function checkSymStartOPDQuest(elementObject, radArray, needLocation, elementName){
    	
    	var allowedPrompt='Did the symptoms start less than 5 days ago(Yes/No)?';    
        var promptedQuest=elementObject.value;
          
    	for(i=0; i<radArray.length; i++){
    
    	  if(i == needLocation){
    	  //if user overwrote the prompted question, just check for empty
    	      if(!(promptedQuest.indexOf(allowedPrompt) > -1) && !(elementObject.value.length > 0)){
    	           return "";
    	      }
    	      if ((radArray[i].checked == true)&&(promptedQuest.indexOf(allowedPrompt) > -1)){
    	        var tempStr1 = promptedQuest.replace(allowedPrompt,"").toLowerCase();
    	        
    	        //tempStr1 = tempStr1.replace(/^\s+|\s+$/g, '');
                // var tempStr1 = promptedQuest.toLowerCase();
    	        //valid input
    	        if((tempStr1.indexOf('yes') != -1 ) || (tempStr1.indexOf('no') != -1 )){
    	              return ""
    	        }else{
    	            setErrorColor(elementObject);
				    return elementName + " was not answered properly\n";
    	        } 	       
			  }//third if
    	   }//first if
    	}//for
	  return ""
   }
   
	// DK 01/31/06 Immunization Enh spec 
    //checks text area depends on radio button status
   function isEmptyConditional(elementObject, radArray, noNeedLocation, elementName){
    	
  
    	for(i=0; i<radArray.length; i++){
    	
    	  if(i != noNeedLocation){
    	   
    	      if ((radArray[i].checked == true)&&(elementObject.value == "")){
    	        setErrorColor(elementObject);
				return elementName + " is required\n";
			  }
    	   }
    	}
	  return ""
   }
   // DK doc notes Enh 04/27/06 
   // check certain field requirement dynamically
     function isEmptyConditionalDropDownMenu(elementObjectDDM, elementObject, elementName){	   	  	   
    	      if ((elementObjectDDM.value == "other")&&(elementObject.value == "")){ 	    	     
    	        setErrorColor(elementObject);
				return elementName + " is required\n";
			  }  
			  if ((elementObjectDDM.value != "other")&&(elementObject.value != "")){ 	    	     
    	        setErrorColor(elementObject);
				return elementName + " should be empty\n";
			  }  		      	
	  		return ""
    }
    
    function isEmptyConditionalCheckBox(elementObjectDDM, elementObject, elementName){	   	  	   
    	      if ((elementObjectDDM.checked == true)&&(elementObject.value == "")){ 	    	     
    	        setErrorColor(elementObject);
				return elementName + " is required\n";
			  }  
			  if ((elementObjectDDM.checked == false)&&(elementObject.value != "")){ 	    	     
    	        setErrorColor(elementObject);
				return elementName + " should be checked\n";
			  }  		      	
	  		return ""
    }
    // DK OPNursing notes Enh 01/04/07
   // checks drop down menu and other option that related with text field
    function isEmptyConditionalOtherWithDDM(DDMObject, DDMName, otherObject, otherName){	
  	
   			 if ((DDMObject.value == "")&&(otherObject.value == "")){ 	    	     
    	        setErrorColor(DDMObject);
				return DDMName + " is required\n";
			  }     	  	   
    	      if ((DDMObject.value == "Other")&&(otherObject.value == "")){ 	    	     
    	        setErrorColor(otherObject);
				return otherName + " is required\n";
			  }  
			  if ((DDMObject.value != "Other")&&(otherObject.value != "")){ 	    	     
    	        setErrorColor(otherObject);
				return otherName + " text field should be empty\n";
			  }  		      	
	  		return ""
    }
    //DK 01/18/07 OPD Nursing Notes Enh Part3 
    //if "yes" radio button is selected, checks associated comments 
    function isEmptyRadioAndComments(elementObj, elementCommentsObj, elementName){
	   	  	   
    	      if ((elementObj.checked == true)&&(elementCommentsObj.value == "")){ 	    	     
    	        setErrorColor(elementCommentsObj);
				return elementName + " is required\n";
			  }  
			  	      	
	  		return ""
    }
     //DK 01/13/07 OPD Nursing Notes Enh Part3 
    function checkVariationBy10Pct( elementObj, elementName, oldValue, newValue ){

        if(oldValue != -999){//if oldValue is not 'N/A'
    		var diff = Math.abs(newValue - oldValue);

    		if(diff > oldValue*0.10){
    			setErrorColor(elementObj);
    			return "The " + elementName + " varies  by more than 10%\n"
    		}else{
    			return ""
    		}			
    	}	
    	return ""
    }
/*Jerry's main functions*/



/*Empty element functions*/
	//Check for empty or none values	
	function isEmpty(elementObject, elementName){
		//Check if its a radio button array
		if(typeof(elementObject.length) != "undefined" && elementObject[0].type == "radio"){
			return isRadioArrayEmpty(elementObject, elementName);
		}

		//Set the color if its a vaild element type for checking if its empty
		if(elementObject.type == "text" || elementObject.type == "textarea" || elementObject.type == "select-one" || elementObject.type == "radio" || elementObject.type == "checkbox"){
			
		}
		//For debugging purposes
		/*else{
			return elementName + " is not a textbox, textarea, select-one, radio or checkbox element to check if empty\n";
		}*/

		//If a textbox or textarea, check for any non-whitespace character
		if(elementObject.type == "text" || elementObject.type == "textarea"){
			//Trim off all the leading and trailing spaces
			var stringValue = trim(elementObject.value);

			if(stringValue == ""){
				setErrorColor(elementObject);
				return elementName + " is required\n";
			}
		}
		//If a dropdown, check if none is not selected
		else if(elementObject.type == "select-one"){
			if(elementObject.selectedIndex == -1){
				setErrorColor(elementObject);
				return elementName + " is required\n";
			}
			else if(elementObject.selectedIndex == 0 && elementObject.options[0].value == ""){
				setErrorColor(elementObject);
				return elementName + " is required\n";
			}
		}
		//If a radio or a checkbox, check if its not checked
		else if(elementObject.type == "radio" || elementObject.type == "checkbox"){
			if(elementObject.checked == false){
				setErrorColor(elementObject);
				return elementName + " is required\n";
			}
			
		}
		
		//Valid case
		return "";
	}
	//Just like isEmpty() but for an array of elements
	function isArrayEmpty(elementArrayObject, elementArrayName){
		if(elementArrayObject == null){
			return "At least one " + elementArrayName + " is required\n";
		}

		var errors = "";

		//Check if one element is in the array, making it a non-array element
		if(typeof(elementArrayObject.length) == "undefined"){
			if(elementArrayObject.name!="iefix"){
				errors += isEmpty(elementArrayObject, elementArrayName);
			}
		}

		//Check each element in the array
		var index = 0;
		for(index = 0; index < elementArrayObject.length; index++){
			if(elementArrayObject[index].name!="iefix"){
				errors += isEmpty(elementArrayObject[index], elementArrayName);
			}
		}
		return errors;
	}
	//Just like isEmpty() but for all elements of a certain type
	function isTypeEmpty(allElementsArrayObject, elementType, allElementsArrayObjectName){
		var index = 0;

		//Set the normal color
		/*
		for(index = 0; index < allElementsArrayObject.length; index++){
			if(allElementsArrayObject[index].type == elementType){
		//		setNormalColor(allElementsArrayObject[index]);
			}
		}
		*/
		//Check if one element type is not empty
		for(index = 0; index < allElementsArrayObject.length; index++){
			if(allElementsArrayObject[index].type == elementType && isEmptyBoolean(allElementsArrayObject[index]) == false){
				//Valid case
				return "";
			}
		}

		//Set the error color
		for(index = 0; index < allElementsArrayObject.length; index++){
			if(allElementsArrayObject[index].type == elementType){
				setErrorColor(allElementsArrayObject[index]);
			}
		}

		//Return the proper error statement based on the element type
		if(elementType == "text" || elementType == "textarea"){
			return allElementsArrayObjectName + " requires at least one text field to be filled\n";
		}
		else if(elementType == "select-one" || elementType == "radio"){
			return allElementsArrayObjectName + " requires an option to be selected\n";
		}
		else if(elementType == "checkbox"){
			return allElementsArrayObjectName + " requires at least one option to be selected\n";
		}
	}

	//Just like isEmpty() but returns a boolean and doesn't change the background color
	function isEmptyBoolean(elementObject){
		//Check if its a radio button array
		if(typeof(elementObject.length) != "undefined" && elementObject[0].type == "radio"){
			var index = 0;

			//Check if one element in the array selected
			for(index = 0; index < elementObject.length; index++){
				if(elementObject[index].checked == true){
					return false;
				}
			}
			return true;
		}

		//For debugging purposes
		/*if(elementObject.type != "text" && elementObject.type != "textarea" && elementObject.type != "select-one" && elementObject.type != "radio" && elementObject.type != "checkbox"){
			return elementName + " is not a textbox, textarea, select-one, radio or checkbox element to check if empty\n";
		}*/

		//If a textbox or textarea, check for any non-whitespace character
		if(elementObject.type == "text" || elementObject.type == "textarea"){
			//Trim off all the leading and trailing spaces
			var stringValue = trim(elementObject.value);

			if(stringValue == ""){
				return true;
			}
		}
		//If a dropdown, check if none is not selected
		else if(elementObject.type == "select-one"){
			if(elementObject.selectedIndex == -1){
				return true;
			}
			else if(elementObject.selectedIndex == 0 && elementObject.options[0].value == ""){
				return true;
			}
		}
		//If a radio or a checkbox, check if its not checked
		else if(elementObject.type == "radio" || elementObject.type == "checkbox"){
			if(elementObject.checked == false){
				return true;
			}
		}
		
		return false;
	}

/*Character limit functions*/
	//Check if the textarea element is within the character limit
	function isWithinCharLimit(elementObject, maxLength, elementName){
		//Prevent negative max length values
		if (maxLength < 0){
			return elementName + " can't have validation on a negative max length\n";
		}

		//Check the length for textbox or textarea only
		if(elementObject.type == "text" || elementObject.type == "textarea"){
			//Check if the element is empty
			/*if(elementObject.value == ""){
				//Valid case
				return "";
			}*/

			
			//check length (with mozilla fix)
			var returnCount = 0;
			var x = 0;
			if(navigator.appName=="Netscape"){
				while(x < elementObject.value.length ){
					if(elementObject.value.charAt(x)=="\n"){
						returnCount = returnCount + 1;
					}
				x = x + 1;
				}	
			}

			if(elementObject.value.length + returnCount > maxLength){
				setErrorColor(elementObject);
				return elementName + " can only be " + maxLength + " characters\n";
			}

			//Valid case
			return "";
		}
		//For debugging purposes
		/*else{
			return elementName + " is not a textbox or textarea to check if within character limit\n";
		}*/
	}

/*Type check functions*/
	//Check if the element is a number
	function isNumber(elementObject, elementName){
		if(elementObject.type == "text" || elementObject.type == "textarea"){
			

			//isNaN() returns false if empty string too
			if(isNaN(elementObject.value) == true){
				setErrorColor(elementObject);
				return elementName + " must be a number\n";
			}

			//Valid case
			return "";
		}
		//For debugging purposes
		/*else{
			return elementName + " is not a textbox or textarea to check if a number\n";
		}*/
	}
	
	//Checks the contents of a textbox or textarea is valid for the specified case
	//ED: 2004.04.16 SW changed date to use date_mask, cause that's why we have one
	function isTextValid(elementObject, textType, elementName){
		if(elementObject.type == "text" || elementObject.type == "textarea"){
			
			if(textType == "date"){
				//Invalid date syntax
				if(elementObject.value.match(VALID_DATE_MASK) == null){
					setErrorColor(elementObject);
					return elementName + " must be a date (ex: mm/dd/yyyy)\n";
				}
				//Valid date syntax but invalid range
				else if(isValidDatePlus(elementObject.value) == false){
					setErrorColor(elementObject);
					return elementName + " must have valid date values\n";
				}
			}
			// PACS 2/16/2007 bug 4244
			else if(textType == "time"){
				if(elementObject.value.match(/^[1]?[0-9]:[0-5][0-9] (AM|PM)$/) == null){
					setErrorColor(elementObject);
					return elementName + " must be a valid time format (ex: HH:MM AM/PM)\n";
				}
			}
			
			else if(textType == "phoneNumber"){
				if(elementObject.value.match(/^\(?\d{3}\)?[-| ]?\d{3}[-| ]?\d{4}$/) == null){
					setErrorColor(elementObject);
					return elementName + " must be a phone number (ex: xxx-xxx-xxxx)\n";
				}
			}
			else if(textType == "zipCode"){
				if(elementObject.value.match(/^\d{5}(-\d{4})?$/) == null){
					setErrorColor(elementObject);
					return elementName + " must be a valid zipcode (ex: 12345)\n";
				}
			}
			else if(textType == "e-mail"){
			    // RSJ 2/2/2007 Bug Fix 4183
				if(elementObject.value.match(/^[\w-_.]+@[\w-_]+(\.[\w-_]+)*$/) == null){ //DLS ~ 05/26/05 ~ Bug 2483	
					setErrorColor(elementObject);
					return elementName + " must be a valid e-mail address (ex: doe@kennedykrieger.org)\n";
				}
			}
			else if(textType == "KKI-e-mail"){
				if(elementObject.value.indexOf("@") > 0){ // Jonty Patel on 07-08-2005 Contact Note Change Request	
					setErrorColor(elementObject);
					return elementName + " must be a valid user name\n";
				} else if (elementObject.value.indexOf(",") > 0 || elementObject.value.indexOf("-") > 0 || elementObject.value.indexOf(" ") > 0) {
				    setErrorColor(elementObject);
				    return elementName + " cannot contain commas, hyphens, or spaces\n";
				}
			}
			else if(textType == "wholeNumber"){
				if(elementObject.value.match(/^\d+$/) == null){
					setErrorColor(elementObject);
					return elementName + " must be a whole number (ex: 1)\n";
				}
			}
			else if(textType == "float"){
				if(elementObject.value.match(/^\d+\.\d+$/) == null){
					setErrorColor(elementObject);
					return elementName + " must be a floating decimal (ex: 1.0)\n";
				}
			}
		}
		//For debugging purposes
		/*else{
			return elementName + " is not a textbox or textarea element to check if a valid" + textType + "\n";
		}*/
	
		//Valid case
		return "";
	}

	//Shows the errors if are any
	function isValid(errors){
		if (errors != ""){
			alert(errors);
			return false;
		}
		return true;
	}



/*Jerry's helper functions*/



/*isEmpty() helper functions*/
	//The isEmpty() for an array of radio elements
	function isRadioArrayEmpty(radioArrayObject, radioArrayName){
		var index = 0;

		//Check if one element in the array selected
		for(index = 0; index < radioArrayObject.length; index++){
			if(radioArrayObject[index].checked == true){
				//Valid case
				return "";
			}
		}

		//Set the color to error
		setErrorColor(radioArrayObject);

		return radioArrayName + " requires an option to be selected\n";
	}

	//For isArrayEmpty function to check if null
	function isNull(elementObject, elementName){
		if(elementObject == null){
			//For debugging purposes
			return "At least one " + elementName + " is required\n";
		}

		//Valid case
		return "";
	}

/*Element color functions*/
	//Changes the element's color to the error color
	function setErrorColor(elementObject){
		//Check if its an array but not a select-one array
		if(typeof(elementObject.length) != "undefined" && elementObject.type != "select-one"){
			var index = 0;

			//Set the color to normal
			for(index = 0; index < elementObject.length; index++){
				elementObject[index].style.backgroundColor = ERROR_COLOR;
			}
		}
		else{
			elementObject.style.backgroundColor = ERROR_COLOR;
		}
	}

	//Changes the element's color to the normal color
	//ED: SW 2004.02.28, changed to work with multi selects and have check arg in one variable.
	function setNormalColor(elementObject){
		var type=elementObject.type;
		var check="type == \"text\" || type == \"textarea\" || type == \"select-one\" || type==\"select-multiple\""
		var altcheck="type == \"radio\" || type == \"checkbox\""
		//Check if its an array but not a select-one array
		if(typeof(elementObject.length) != "undefined" && type != "select-one" && type!="select-multiple"){
			var index = 0;

			//Set the color to normal
			for(index = 0; index < elementObject.length; index++){
				//Check if the background is white or the form's background
				type=elementObject[index].type;
				if(eval(check)){
					elementObject[index].style.backgroundColor = NORMAL_COLOR;
				}
				else if(eval(altcheck)){
					elementObject[index].style.backgroundColor = FORM_COLOR;
				}
			}
		}
		else{
			//Check if the background is white or the form's background
			if(eval(check)){
				elementObject.style.backgroundColor = NORMAL_COLOR;
			}
			else if(eval(altcheck)){
				elementObject.style.backgroundColor = FORM_COLOR;
			}
		}
		return true;
	}

	function checkRegs(oElement,label){
		//list of words to check for
		//roll through form text
		var value=oElement.value;
		var msg="";
		regexp = new RegExp(REG_MASK);
		var match = regexp.exec(value);
		if(match==null)
			return msg;
		setErrorColor(oElement);
		var msg=label + " is using an invalid letter/word/phrase, please correct.";
		return msg;
	}
	
	/*
		Loop through form elements checkin for text or textarea
		validate against Prohibited Abbrv mask (REG_MASK).
	*/
	function checkFormRegs(oForm){
		//list of words to check for
		//roll through form text
		var bRet=true;
		var oElements=oForm.elements;
		var oElement;
		var value;
		var msg="";
		regexp = new RegExp(REG_MASK);
		var match;
		var x = new Array();
		var j = 0;
		for(i=0;i<oElements.length;i++){
			oElement=oElements[i];
			type=oElement.type;
			if(type=="text" || type=="textarea"){
				value=oElement.value;
							match = regexp.exec(value);
				if(match!=null){
					setErrorColor(oElement);
					x[j] = match.toString();
					for(k = 0; k < x[j].length; k++) {
						if (x[j].charAt(k) == ",") {
							x[j] = x[j].substring(0,(k));
						}
					}
					j++;
				}
				bRet=(match==null) && bRet;
			}
		}//end loop
		if(!bRet){	
			msg="There are prohibited abbreviations being used, please correct.\nClick the question mark above for more help.\nBelow is a list of the prohibited abbreviations used for each highlighted entry field. only the first illegal entry in each field is listed.\n";
			for (i = 0; i < x.length; i++) {
			    j = i + 1;
				msg = msg + " Highlighted field " + j + ": " + x[i] + "\n";
			}
			msg = msg + "\n";
		}
		return msg;
	}
	
	// RSJ 10/16/2006 Bug Fix 4000
	// RSJ 10/24/2006 Bug Fix 4009
	function checkSingleFormReg(oElement, stripXML) {
		var bRet = true;
		var value;
		var msg = "";
		regexp = new RegExp(REG_MASK);
		var match;
		var x = new Array();
		var j = 0;
 	    type = oElement.type;
		if(type == "text" || type == "textarea")
		{
		    if(stripXML)
			{
		        tmpValue = oElement.value;
		        value = tmpValue.replace(/<[^>]+>/g, "");
		    }
		    else 
		    {
			    value = oElement.value;
			}
			match = regexp.exec(value);
			
			if(match != null)
			{
			    setErrorColor(oElement);
				x[j] = match.toString();
				alert("THIS IS OUR MATCH: " + x[j] + "\n" );
				for(k = 0; k < x[j].length; k++)
				{
				    if (x[j].charAt(k) == ",")
				    {
					    x[j] = x[j].substring(0,(k));
					}
				}
				j++;
			}
			bRet = (match == null) && bRet;
		}
		if(!bRet){	
			msg="There are prohibited abbreviations being used, please correct.\nClick the question mark above for more help.\nBelow is a list of the prohibited abbreviations used for each highlighted entry field. only the first illegal entry in each field is listed.\n";
			for (i = 0; i < x.length; i++) {
			    j = i + 1;
				msg = msg + " Highlighted field " + j + ": " + x[i] + "\n";
			}
			msg = msg + "\n";
		}
		return msg;
	}//end function

    //by Marlon Julian Gomez
    //check prohibitive abbreviations for many textNode
    function checkAllTextNode (arrTextNode)
    {
            var isFinished = false;//Se supone que todo esta bien 
            for(var i in arrTextNode)
            {
                    isFinished = checkAllForProhibitedAbbreviations(arrTextNode[i]);
                    if(isFinished)break;//Al menos un textArea tiene proh abbr y se cancelo la modificacion
            }
            return isFinished;

    }

    //check prohibitive abbreviations for all inputs, type "text" or ""textarea"
    function checkProhibitedAbbreviationsAnyText(oForm)
    {
    		//DK 04.16.08 bug#4901
   	        if(oForm.name == "PatientSearchForm")
   	        	return false;
   	        	
			var isFinished = false;//Se supone que todo esta bien 
			var oElements=oForm.elements;
			var oElement,type;
			for(var i=0;i<oElements.length;i++)
			{
				oElement=oElements[i];
				type=oElement.type;
				if(type=="text" || type=="textarea")
				{
					if(isVisible(oElement,oForm) )
					{
						isFinished = checkAllForProhibitedAbbreviations(oElement);
	                    if(isFinished)break;//Al menos un INPUT text o TEXTAREA tiene proh abbr y se cancelo la modificacion
					}
				}
			}
			return isFinished;
    }

    function isVisible (node,form)
    {
        var isVisible = true;
        var papa = node;
        while(isVisible && papa!=form)
        {
            if(papa.style.display == "none")
            {
                isVisible = false;
                break;
            }
            papa = papa.parentNode;
        }
        return  isVisible;
    }

    //check all prohibitive abbreviations for one, nodeText or input type "text" or ""textarea"
	function checkAllForProhibitedAbbreviations(htmlAnyText)
	{
		var proAbbr = checkForProhibitedAbbreviations(htmlAnyText);
		while(proAbbr)
		{
			proAbbr = checkForProhibitedAbbreviations(htmlAnyText);
			if(proAbbr == null)break;
		}
		return (proAbbr == null);
	}
    //by Marlon Julian Gomez

	//Added by A. Kone 04/26/2007 fix for bug to highlight Prohibited Abbreviations
	function checkForProhibitedAbbreviations(textArea)
	{
		//alert("Test")
		var tValue = getValueText(textArea);
		var regexp = new RegExp(REG_MASK);
		var match = regexp.exec(tValue);
		if(match != null)
		{
			selectTextRangeAny(textArea, match.index, match[0].length, match[0]);
			var wrongAbbr = match[0];
			var matchIndex = match.index;
			var correction = prompt("There are prohibited abbreviations within your entry. Please correct them before proceeding.", wrongAbbr);
			if( correction != null)
			{
				match = regexp.exec(correction);
				if(match == null)
				{
					correctText(correction, textArea, matchIndex, wrongAbbr.length);
					return true;//Se corrigio al primer intento.
				}
				else
				{
					while(match != null)
					{
						correction = prompt("This is an invalid correction. Please correct it before proceeding. ", wrongAbbr);
						if(correction == null)
						{
							selectTextRangeAny(textArea, matchIndex, wrongAbbr.length, wrongAbbr);
							break;
						}
						else
						{
							match = regexp.exec(correction);
						}
					}
					if(correction != null)
					{
						correctText(correction, textArea, matchIndex, wrongAbbr.length);	
                        return true;//Hasta que por fin lo corrigio, continuara con la siguiente si existe!
					}
					else
					{
						return correction;//Intento varias veces pero se canso, cancela correcion
					}
				}
			}
			else
			{
				return correction;//Se cancela correccion sin intentar
			}
		}
		else// No existen prohibitive abbreviation
		{
			return false;
		}
	}
    //by Marlon Julian Gomez
    function getValueText(textControl)
    {
        return (textControl.nodeType == 3)?textControl.nodeValue:textControl.value;
    }

    function setValueText(node,value)
    {
        if(node.nodeType == 3)
            node.nodeValue = value
        else
            node.value = value;
    }

    function selectTextRangeAny(textControl, startIndex, selectionLength, wrongWord)
    {
        if(textControl.nodeType == 3)
            tinyMCE.getInstanceById("mce_editor_0").selection.selectTextRange(textControl, startIndex, selectionLength, wrongWord);
        else
            selectTextRange(textControl, startIndex, selectionLength, wrongWord);
    }
    //by Marlon Julian Gomez

	//Added by A. Kone 04/26/2007
	function correctText(correctWord, textControl, startIndex, selectionLength)
	{
        var valor = getValueText(textControl);
	    var firstHalf = valor.substring(0, startIndex);
	    var secondHalf = valor.substring((startIndex + selectionLength) , valor.length);
        setValueText(textControl,firstHalf + correctWord +  secondHalf);
	}
	
	//Added by A. Kone 04/26/2007
	function selectTextRange(textControl, startIndex, selectionLength, wrongWord )
	{
	    if (textControl.createTextRange)
	    {
	        var textRange = textControl.createTextRange();
	      	textRange.findText(wrongWord, 1, 2);
	       	textRange.select();
	       	textRange.execCommand("BackColor",false, "#dddddd");
	       	textRange.execCommand("Bold",false);
	       	textRange.execCommand("ForeColor",false, "#FFFFFF");
	        textRange.scrollIntoView(true);
	        textRange.collapse(false);

	    }
	    else if(textControl.setSelectionRange)
	    {
	        textControl.focus();
	        textControl.selectionStart = startIndex;
	        textControl.selectionEnd = startIndex + selectionLength;
			var scrollPos = 0;
			textControl.scrollTop = 0;
			var numberOfLines = 1;
			var lb = /.*(\r\n|\r|\n)/g;
			lb.lastIndex = 0;
			var antecedent = textControl.value.substring(0, startIndex);
			var totalLength = textControl.value.length;
			var totalRows = Math.floor(totalLength / textControl.cols ) + textControl.value.split("\n").length;
			var lineBreaks = antecedent.match(lb);
			
			if(lineBreaks == null)
			{
				numberOfLines = 0;
			}
			else
			{
				numberOfLines = lineBreaks.length;
			}
			scrollPos = Math.floor(textControl.scrollHeight / antecedent.split("\n").length * 1.5 );
			var rows = Math.floor(antecedent.length / textControl.cols );
			var ratio = Math.floor(textControl.scrollHeight / totalRows);
			textControl.scrollTop += (rows + antecedent.split("\n").length) * ratio;
	        textControl.setSelectionRange(textControl.selectionStart, textControl.selectionEnd);
	    }
	
	    textControl.focus();
	}
	
	
	//added by Emma to check if the form is empty, exclude the hidden fields 07/09/2004
	function isFormEmpty(elementObject){
	
		var message="";
		var type 
		var check="type == \"text\" || type == \"textarea\" || type == \"select-one\" || type==\"select-multiple\"||type==\"radio\"||type==\"checkbox\"";

		for(i=0;i<elementObject.length;i++){
			oElement = elementObject[i];
			//alert(eval(oElement));	
			if(eval(oElement)){
				type=oElement.type;
				//AMC 11-9-2005 good idea to get rid of alerts after debuging (they scare the users)
                // bug 3276
				//alert(type + " " + oElement.id);
				if (eval(check)){
					message =isEmpty(oElement);
					if(message==""){
						break;
					}
				}
			}//end element check
		}
		if(message!=""){
			// Bug Fix # 2453
			message="Cannot submit an empty form\n";
			//message="Must fill out at least one item\n";
		}
		return message;
		
	}
	
    //added by Jonty to check if the format is correct for phone number and state fields 07/20/2004
	function isPhoneValid(elementObject, elementName){
	   if((elementObject.value.match(/^\(\d{3}\)?[-]?\d{3}[-]?\d{4}$/) == null) &&
	      (elementObject.value.match(/^\d{3}\-\d{4}$/) == null) ){
	      setErrorColor(elementObject);
		  return "Please enter number in xxx-xxxx or (xxx)xxx-xxxx\n";
		}
	return "";
	}
	
	function isStateValid(elementObject, elementName) {
	   if(elementObject.value.match(/\d/) != null) {
	      setErrorColor(elementObject);
	      return "Please abbreviate state in two letters\n";
	   }
	return "";
	}
	
	//added 8/18/2004 DLS to check that atleast one checkbox in the checkbox array is checked
	function atleastOneChecked(someCheckArray, someErrorMessage)
	{
		if ( someCheckArray.checked == undefined)
			{
				alength = someCheckArray.length;
				test = 0;
			
					<!-- walking through the array -->
				for (i = 0; i < alength; i++)
				{	<!-- checking that atleast one is checked.. when you find one, modify the test statement, and break -->
					if (someCheckArray[i].checked == true)
					{
						test ++;
						break;
					}
				} <!-- checking the test condition for a proper error condition -->
				if (test == 0)
				{
					return someErrorMessage;
				}
			}
				<!-- if there is only one prescription, this will do the check to make sure that atleast it is checked -->
			else if (someCheckArray.checked == false)
			{
				return someErrorMessage;
			}
		return "";
	}
	
	//Added 08/19/2004 JP to check if numbers are a whole number between min and max limit
	function isWholeNum(wholenum,min,max) {		
		if(((wholenum >= min) && (wholenum <= max)) || (wholenum == null)){
		return true;
		}
		else {
		return false;
		}
	}
	
	//Added 9/27/2004 Andrew Curtis to check format of zipcode if one is present
	function isZipValid(elementObject, elementName){
		if((elementObject.value.match(/^\d{5}(-\d{4})?$/) == null) && (isEmptyBoolean(elementObject) != true)){
					
					setErrorColor(elementObject);
					return elementName + " must be a valid zipcode (ex: 12345)\n";
				}
				return "";
	}	
	
	//added to check the format of KKI # in xx-xx-xx EY 10.21.2004
	// Edited by Jonty Patel on 06-09-2005 - Changed validation to meet Patient Search Enhancement
	function isKkiNumValid(elementObject, elementName){		
		if((isEmptyBoolean(elementObject) != true) &&
		   ((elementObject.value.match(/^\d{2}\-\d{2}\-\d{2}$/) == null) && (elementObject.value.match(/^\d{6}$/) == null))) {
			setErrorColor(elementObject);
			return elementName + " must be in this format nn-nn-nn or nnnnnn.";
		}
		return "";
	}
	
	// Added by Jonty Patel on 07-26-2005 ~ Bug Fix 2763, 2762
	function isEmptySubmit(elementObject) {
		var message;
		if(elementObject.value == "" || elementObject.value == undefined) {
			message="Cannot submit an empty form\n";
			return message;
		}	
		return "";
	}
	
	// Added by Jonty Patel on 08-08-2005 ~ Bug Fix # 2813
	function isCheckBoxesEmpty(elementObject) {
		
		var length = elementObject.length;
		var flag = true;
		var index = 0;
		
		if(length != 0 || typeof(length) != "undefined") {
			for(index = 0; index < length; index++) {			
				if((!(elementObject[index].checked)) && flag) {
					flag = true;
				} else {
					flag = false;					
				}
			}
			
			if(flag) {
				for(index = 0; index < length; index++) {
					elementObject[index].style.backgroundColor = ERROR_COLOR;									
				}
			}
		}
		return "";					
	}
	
	// Added by Jonty Patel on 08-0-2005 
	// Generic Function to check for a radio button being selected or not.
	// Also bug fix Bug Fix # 2835, 2854
	
	function isRadioSelected(elementObject, elementName){
		
		var len = elementObject.length;
		var flag = true;
		var index = 0;
		
		if(len != 0 || typeof(len) != "undefined") {
			for(index = 0; index < len; index++) {			
				if((!(elementObject[index].checked)) && flag) {
					flag = true;
				} else {
					flag = false;					
				}
			}
			
			if(flag) {
				return elementName + "\n"; 
			} else {
				return "";
			}
		}
		
		return "";
	}

	
	//Added SW: 2005.11.08 same as isFormEmpty instead calls isEmptyValue to not set the color, since the whole form is being checked
	function checkFormValues(elementObject){
		var message="";
		var ret;
		var type 
		var check="type == \"text\" || type == \"textarea\" || type == \"select-one\" || type==\"select-multiple\"||type==\"radio\"||type==\"checkbox\"";

		for(i=0;i<elementObject.length;i++){
			oElement = elementObject[i];
			if(eval(oElement)){
				type=oElement.type;
				if (eval(check)){
					ret = checkValue(oElement);
					if(ret){
						break;
					}
				}
			}//end element check
		}
		if(!ret){
			// Bug Fix # 2453
			message="Cannot submit an empty form\n";
			//message="Must fill out at least one item\n";
		}
		return message;
		
	}
	
		
	
	//Added SW: 2005.11.08
	//Check for empty or none values
	//do not change color and return true/false
	function checkValue(elementObject){
		//Check if its a radio button array
		if(typeof(elementObject.length) != "undefined" && elementObject[0].type == "radio"){
			return isRadioArrayEmpty(elementObject, "");
		}
		//If a textbox or textarea, check for any non-whitespace character
		if(elementObject.type == "text" || elementObject.type == "textarea"){
			//Trim off all the leading and trailing spaces
			if(trim(elementObject.value) == ""){
				return false;
			}
		}
		//If a dropdown, check if none is not selected
		else if(elementObject.type == "select-one"){
			if(elementObject.selectedIndex == -1){
				return false;
			}
			else if(elementObject.selectedIndex == 0 && elementObject.options[0].value == ""){
				return false;
			}
		}
		//If a radio or a checkbox, check if its not checked
		else if(elementObject.type == "radio" || elementObject.type == "checkbox"){
			if(elementObject.checked == false){
				return false;
			}
		}
		
		//Valid case
		return true;
		
	}
	
	function isYear(elementObject, elementName){
	if((elementObject.value.match(/^\d{4}(-\d{3})?$/) == null) && (isEmptyBoolean(elementObject) != true)){
					
					setErrorColor(elementObject);
					return elementName + " must be a valid 4 digit year (2006)\n";
		}
		
				return "";
		
	}
