<!-- Functions for Client Side Validations-->

//this function includes all necessary js files for the application
function includeJS(file)
{

  var script  = document.createElement('script');
  script.src  = file;
  script.type = 'text/javascript';
  script.defer = true;

  document.getElementsByTagName('head').item(0).appendChild(script);

}

/* include any js files here */
includeJS('js/velos/dateformatSetting.js');
includeJS('js/velos/date.js');
  


 var whitespace = " \t\n\r";
 var  checkQuote="Y";
 var overRideChar;
 overRideArray=new Array();
 overRideFldArray=new Array();

 //these variables are used for htmlareA
 _editor_url = "./htmlarea/";
   _editor_lang = "en";

   var veltoolbar=[
		[ "fontname", "space",
		  "fontsize", "space",
		  "formatblock"],
		  ["bold", "italic", "underline", "strikethrough", "separator",
		  "subscript", "superscript", "separator",
		  "copy", "cut", "paste", "separator", "undo", "redo", "space"],
		[ "justifyleft", "justifycenter", "justifyright", "justifyfull","separator",
			"orderedlist", "unorderedlist", "outdent", "indent", "separator",
		  "forecolor", "hilitecolor", "separator",
		  "inserthorizontalrule", "createlink", "separator","htmlmode"]
	];

 var editorWidth=500;
 var editorHeight=200;

//To set the value of checkQuote.If checkQuote is set to 'N', it will skip the checking of quotes in the page
 function setCheckQuote(val)
 {
	 checkQuote=val;
 }

 // Parameter name is the name of the field.
function validate_col(name,column)
{

	// to check for single and double quotes..
	if((column.name).toLowerCase()=="esign")
	{
	  t=document.forms.length;
	        for(k=0;k<t;k++)
		{
		  formobj = document.forms[k];
		  if(allfldquotecheck(formobj)==false)
		  return false;
		}

	}

	else
	{
		value=column.value;

	}

	/*Modified by Sonia Abrol, 01/25/05, if the column is disabled, bypass its
		mandatory validation*/
	/* Modified by Sonia Abrol on 02/04.05 to handle radio n checkboxes*/


	if (column.length == undefined || column.type == 'select-one')
	 {
		if (column.disabled)
		{
			return true;
		}

	 }
	else
	{

		if (column.length > 0)
		{
		   if (column[0].disabled ==  true)
			{
				return true;
			}

		}
	}





	if (column.type == "select-one")
			{
				 i = column.options.selectedIndex;
				 value = column.options[i].value;
			}
		else
		{
	        value=column.value;
		}
            if(value==''||value==null){
				if(column.readOnly==true)
				{
					alert("Please enter data in "+name);

				}
				else
				{
					alert("Please enter data in all mandatory fields")
		            column.focus()
				}
                return false;
            }else if (isWhitespace(value) == true){
                alert("Please enter valid data")
                column.focus()
                return false;
            }else {
                return true;
            }
    }


//This function is used for checkbox/radiobutton mandatory validation
//Displays a message if the checkbox is not checked
//name is the column text that you want to display in the message
//column is formobj.column
 function validate_chk_radio(name,column) {


 	totrows = column.length;
	checked = false;

	if ( totrows == undefined || totrows==1) {

		if (column.disabled ==  true)
			{
				return true;
			}


		if (column.checked) {
			checked=true;
		}else {
			checked=false;
		}
	} else
		{//more than one checkbox

		if (totrows > 0) //bypass validation for disabled columns
		{

			if (column[0].disabled ==  true)
			{
				return true;
			}
		}

		for (i=0;i<totrows;i++) {
			if (column[i].checked) {
				checked=true;
				break;
			} else {
				checked=false;
			}
		}
	}

	if (!checked) {
		alert("Please select " + name);
		return false;
	}

    return true;
 }



function validate_col_spl(name,column)
{
	// end of checking for special characters

	/*Modified by Sonia Abrol, 03/09/05, if the column is disabled, bypass its
		mandatory validation*/



	if (column.length == undefined || column.type == 'select-one')
	 {
		if (column.disabled)
		{
			return true;
		}

	 }
	else
	{

		if (column.length > 0)
		{
		   if (column[0].disabled ==  true)
			{
				return true;
			}

		}
	}



		if (column.type == "select-one")
		{
			 i = column.options.selectedIndex;
			 value = column.options[i].value;
		}
		else
		{
	       		 value=column.value;
		}

            if(value.length==0||value==''||value==null){
                alert("Please enter data in all mandatory fields");
                column.focus();
                return false;
            }else if (isWhitespace(value) == true){
                alert("Please enter valid data");
                column.focus();
                return false;
            }else {

		if (  splcharcheckforlinks(value) == false)
		{
			column.focus()
			return false ;
		}

                return true;
            }
    }

    function validate_col_nofocus(name,column)
{
	// end of checking for special characters

		if (column.type == "select-one")
		{
			 i = column.options.selectedIndex;
			 value = column.options[i].value;
		}
		else
		{
	       		 value=column.value;
		}


            if(value.length==0||value==''||value==null){
                alert("Please enter data in "+name);
                //column.focus();
                return false;
            }else if (isWhitespace(value) == true){
                alert("Please enter valid data in "+name);
                //column.focus();
                return false;
            }else {

		if (  splcharcheckforlinks(value) == false)
		{
			//column.focus()

			return false ;
		}

                return true;
            }
    }


function isEmpty(s){
	return ((s == null) || (s.length == 0))
}

function isWhitespace(s){
    if (isEmpty(s)) return true

    // Search through string's characters one by one
     for (var i = 0; i < s.length; i++) {
        var c = s.charAt(i)
	if (whitespace.indexOf(c) == -1) return false
    }
    // All characters are whitespace.
    return true
}

    function isDigit (as_char)
    {
        if(as_char == ' ')
        {
            return false;
        }

        if ((as_char >=0) && (as_char <= 9)){
            return true;
        }
         else {
            return false; }
    }

    function isInteger(as_str)
    {
        if (as_str =='') {
            return true;
        }
        for (i=0;i < as_str.length;i++)
        {
            var c = as_str.charAt(i) ;
            if (!isDigit(c)) return false;
        }
        return true;
    }

	function isNegNum(as_str)
	{

		if (as_str =='') {
            return false;
        }
        var c = as_str.charAt(0) ;

			if (c == "-"){

			 if (isNaN(as_str.substring(1,as_str.length))) return false;
			}
			else
			{
			return false;
			}
		return true;
	}

    function isDecimal(as_str)
    {
        if (as_str =='') {
            return true;
        }
		dotCount =0;
		if ((as_str.length == 1) && (!isDigit(as_str))) return false;
        for (i=0;i < as_str.length;i++)
        {
            var c = as_str.charAt(i) ;
			if (c == "."){
				if (dotCount == 0) dotCount ++;
				else return false;
			}
            if (!isDigit(c) && (c != ".")) return false;
        }
        return true;
    }

    function isDecimalOrNumber(col)
    {
       var isDec;
       var isNumber ;

    	isDec= isDecimal(col.value);

		if (!isDec)
			{
			   isNumber = isInteger(col.value);

				if (!isNumber)
					{
						alert("Please enter a valid Number");
						col.focus();
						return false;
					}

				}
        return true;
    }



    function validate_date(date_col){

	/*Modified by Sonia Abrol, 03/09/05, if the column is disabled, bypass its
		mandatory validation*/

        return validate_date_optionalmsg(date_col,true);


    }


	//displays the valid date message only if required
    function validate_date_optionalmsg(date_col,dispMsg){

	/*Modified by Sonia Abrol, 03/09/05, if the column is disabled, bypass its
		mandatory validation*/



		if (date_col.disabled)
		{
			return true;
		}



		dateVal=date_col.value

		if(dateVal==null || dateVal=='') return true;



	    // Modifiedy by Isaac for Bug 4064 & 4082
	    if (calDateFormat.indexOf('MMM') != -1) {
	    	if (!hasValidShortMonthString(dateVal,calDateFormat)) {
	    		if (shortMonthStringOnlyOffByCase(dateVal,calDateFormat)) {
	    			alert("Please enter the month part in correct cases (e.g. 'Jan' for January)");
	    		} else {
                    alert("Invalid Date. Please enter a valid Date in '"+calDateFormat+"' format");
	    		}
	            date_col.focus()
	    		return false;
	    	}
	    }
	    // -- End of Bug 4064 & 4082

    	if (isDate(dateVal,calDateFormat))
    		{
    			return true;
    		} else
    			{

	    			if (dispMsg) {
		                 alert("Invalid Date. Please enter a valid Date in '"+calDateFormat+"' format");
	    	             date_col.focus()
					 }

	    			 return false;


    			};

    }



	//to check the format of entered data, format is specified as ##.## etc
	function validateDataFormat(colname,format) {
		/*Modified by Sonia Abrol, 03/09/05, if the column is disabled, bypass its
		mandatory validation*/


		if (colname.disabled)
		{
			return true;
		}


		val = colname.value;

		if(val==null || val=='') return true;

		valLen = val.length;
		valDecimalPos = val.indexOf(".");
		valNoAfterDec = valLen - (valDecimalPos+1) ;

		len = format.length;
		decimalPos = format.indexOf(".");
		noAfterDec = len - (decimalPos+1) ;

		//the position of decimal does not match with that given in format
		if (decimalPos != valDecimalPos) {
			alert("Please enter data in '"+format+"' format");
			colname.focus();
			return false;
		}
		//the number of numbers after decimal do not match with that given in format
		if (noAfterDec != valNoAfterDec) {
			alert("Please enter data in '"+format+"' format");
			colname.focus();
			return false;
		}

		return true;
	}


    //by sonia sahni to compare 2 dates
	// operator is obsolete. currently it will work only to check if dt1> dt2
 function CompareDates(dt1,dt2,operator)
    {
	  var retval;

	  retval= compareDates(dt1,calDateFormat,dt2,calDateFormat);

	  if (retval == 1)
	  {
		  return true;
	  }else
	  {
		  return false;
	  }



    }


    //by sonia sahni : compares two Date objects for '>' operator ; date: 18 jan 2001
      function compareDateObjects(dt1,dt2,operator)
    {


        Month1 = dt1.getMonth() ;
        Day1 = dt1.getDate();
        Year1= dt1.getFullYear();

        Month2 = dt2.getMonth() ;
        Day2 = dt2.getDate();
        Year2 = dt2.getFullYear();


        if (operator == '>')
        {
            //CHECK FOR YR
            if (Year1 < Year2)
            {
                return false;
            }
            else if (Year1 > Year2)
            {
                return true;
            }

            if (Month1 < Month2)
            {
                return false;
            }
            else if (Month1 > Month2)
            {
                return true;
            }

            if (Day1 <= Day2)
            {
                return false;
            }

         }

      return true; //this means date 1 is greater than date 2
    }


function f_check_perm(pageRight,perm){
	if (perm == "N") { //check whether logon user has New Permission
		if ((pageRight == "7") || (pageRight == "1") ||
			(pageRight == "3") || (pageRight == "5")){
			return true;
		}else{
			alert("New Permission Denied");
			return false;
		}
	}else if (perm == "E") { //check whether logon user has Edit Permission
		if ((pageRight == "7") || (pageRight == "2") || (pageRight == "3")
			|| (pageRight == "6")){
			return true;
		}else{
			alert("Edit Permission Denied");
			return false;
		}
	}else if (perm == "V") { //check whether logon user has View Permission
		if ((pageRight == "7") || (pageRight == "4") || (pageRight == "5")
			|| (pageRight == "6")){
			return true;
		}else{
			alert("View Permission Denied");
			return false;
		}
	}
}

//**method for checking patient and organization right also
function f_check_perm_org(pageRight,orgRight,perm){
	if (perm == "N") { //check whether logon user has New Permission
		if (((pageRight == "7") || (pageRight == "1") ||	(pageRight == "3") || (pageRight == "5")) && ((orgRight == "7") || (orgRight == "1") ||	(orgRight == "3") || (orgRight == "5"))) {
			return true;
		}else{
			alert("New Permission Denied");
			return false;
		}
	}else if (perm == "E") { //check whether logon user has Edit Permission
		if (((pageRight == "7") || (pageRight == "2") || (pageRight == "3") || (pageRight == "6")) && ((orgRight == "7") || (orgRight == "2") || (orgRight == "3") || (orgRight == "6"))) {
			return true;
		}else{
			alert("Edit Permission Denied");
			return false;
		}
	}else if (perm == "V") { //check whether logon user has View Permission
		if (((pageRight == "7") || (pageRight == "4") || (pageRight == "5") || (pageRight == "6")) && ((orgRight == "7") || (orgRight == "4") || (orgRight == "5") || (orgRight == "6"))) {
			return true;
		}else{
			alert("View Permission Denied");
			return false;
		}
	}
}


//***********************************************************************************
//fnShowCalendar opens the Calendar window with the current date set as default in it.
//***********************************************************************************
/*Modified by Sonia Abrol, to send a dummy array to fnShowCalendarPopulateMiltiple
so that the code for opening a calendar is at one place
*/
function fnShowCalendar(theDateObj)
{

	var otherDateFieldsDummy = new Array(0) ;

	fnShowCalendarPopulateMultiple(theDateObj,otherDateFieldsDummy)
	return true;

}


/* Use it to set the same date to more than one targets
   theDateObj - the date object that is selected by the user
   otherDateFields - an array of other date objects that will be populated with the same value selected for the theDateObj field
	*/
function fnShowCalendarPopulateMultiple(theDateObj,otherDateFields)
{

	var win=""
	var msgWindow = null;
	var strDate = fnTrimSpaces(theDateObj.value);

	// if the dateobject is disabled, return

	if (theDateObj.disabled)
	{
		alert("This field is disabled. You can not select a date");
		return;
	}



	if(  ! isDate(strDate,calDateFormat) )
	{

		//strDate = theDateObj.value;
		strDate = fnGetFullCurrentDate();


	}


	calculateValForMultipleTargets(theDateObj,'Select Date',otherDateFields);

	return true;
}


//***********************************************************************************
//fnTrimSpaces trims leading and trailing spaces in 'strToTrim'
//***********************************************************************************

function fnTrimSpaces(strToTrim)
{
	if(strToTrim == null) {
		strTemp = ''
		return strTemp;
		};
	strTemp = strToTrim;
	len=strTemp.length;
	i=0;
	while (i < len && strTemp.charAt(i)==" ")
		i=i+1;
	strTemp = strTemp.substring(i);
	len=strTemp.length;
	j = len-1;
	while (j>0 && strTemp.charAt(j)==" ")
		j = j-1;
	strTemp = strTemp.substring(0,j+1);
	return strTemp;


}




//***********************************************************************************
//fnGetFullCurrentDate sets current date set as default in the Calendar.
//***********************************************************************************

function fnGetFullCurrentDate()
{
	var strFinalDate;
	var d = new Date();

	//Get all the attributes
	var strMonth = d.getMonth() +1;

	if( strMonth < 10 )
		strMonth = "0" + strMonth ;

	var strDay   = d.getDate();
	if( strDay < 10 )
		strDay = "0" + strDay;

	var strYear  = d.getFullYear(); //This will return full year


	var compileDate;

	compileDate = calDateFormat;

	compileDate = compileDate.replace("dd",strDay);
	compileDate = compileDate.replace("yyyy",strYear);


	compileDate = compileDate.replace("MMM",monthStringShort[parseInt(strMonth,10)]);

	compileDate = compileDate.replace("MM",strMonth);



	var strFinalDate = compileDate;

		//strMonth + "/" + strDay + "/" + strYear;
	return strFinalDate;
}

//***********************************************************************************
// Nth_Tab : Returns the string from 'strSource' at 'position'
// Starting from first element and each string in 'strSource' separated by 'separator'
//***********************************************************************************

function Nth_Tab(strSource, position, separator)
{
	var strTemp = strSource + separator;
	var indexPos = -999;
	var tokenStringf;
	for (i=0;i < position;i++)
	{
		indexPos = strTemp.indexOf(separator);
		tokenString = strTemp.substring(0, indexPos);
		strTemp  = strTemp.substring(indexPos+1, strTemp.length);
	}
	return tokenString;
}

//*********************************************************************************************
//To check the occurrence of the %&*% etc characters
//**********************************************************************************************

function  splcharcheck(dataval)
{

     val= dataval;
     if(val=='' || val == null || val == 'null' || val == 'NULL' )
     return true;

    if(val.indexOf("%")!= -1)
	{
	   alert("No Special Character(%) Allowed");
           return false;
 	}
   /* if(val.indexOf("<")!= -1)
	{
	   alert("No Special Character(<) Allowed");
	   return false;
	}
    if(val.indexOf(">")!= -1)
	{
	  alert("No Special Character(>) Allowed");
	  return false;
	}*/
    if(val.indexOf("*")!= -1)
	{
	  alert("No Special Character(*) Allowed");
	  return false;
	}
    /*if(val.indexOf("&")!= -1)
	{
  	 alert("No Special Character(&) Allowed");
         return false;
	}*/
    if(val.indexOf("^")!= -1)
	{
 	 alert("No Special Character(^) Allowed");
         return false;
	}
    if(val.indexOf("!")!= -1)
	{
 	 alert("No Special Character(!) Allowed");
         return false;
	}

    if(val.indexOf("?")!= -1)
	{
	alert("No Special Character(?) Allowed");
        return false;
	}

    /*if(val.indexOf("'")!= -1){
	   alert("No Special Character(') Allowed");
           return false;
	}*/
    if(val.indexOf("(")!= -1) {
	   alert("No Special Character( ( ) Allowed");
           return false;
	}
    if(val.indexOf(")")!= -1) {
	alert("No Special Character( ) ) Allowed");
           return false;
	}
    if(val.indexOf("#")!= -1) {
	   alert("No Special Characters Allowed ( # )");
           return false;
	}

    if(val.indexOf("\"")!= -1) {
	   alert("No Special Character( \" ) Allowed");
           return false;
    }
    if(val.indexOf("$")!= -1) {
	alert("No Special Character( $ ) Allowed ");
        return false;
    }

	return true;
}


function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function


 function encodeString(InputStr)
 {
	  if (InputStr!=null)
	  {
	      if (InputStr.indexOf("'")>=0)
		  {
	      	  InputStr=replaceSubstring(InputStr,"\'","[SQuote]");
	      }
	      if (InputStr.indexOf("\"")>=0)
		  {
	      	  InputStr=replaceSubstring(InputStr,"\"","[DQuote]");
	      }
	      if (InputStr.indexOf("\r")>=0)
		  {
	      	  InputStr=replaceSubstring(InputStr,"\r","[CRet]");

	      }
	      if (InputStr.indexOf("\n")>=0)
		  {
	      	  InputStr=replaceSubstring(InputStr,"\n","[NLine]");

	      }
	       if (InputStr.indexOf("\t")>=0)
		   {
	      	  InputStr=replaceSubstring(InputStr,"\t","[HTab]");
	       }
	       if (InputStr.indexOf("\\")>=0)
		   {
	      	  InputStr=replaceSubstring(InputStr,"\\","[BSlash]");

	       }
		   if (InputStr.indexOf("#")>=0)
		   {
	      	  InputStr=replaceSubstring(InputStr,"#","[VelHash]");

	       }
	        if (InputStr.indexOf(",")>=0)
		   {
	      	  InputStr=replaceSubstring(InputStr,",","[VELCOMMA]");

	       }
	        if (InputStr.indexOf("%")>=0)
		   {
	      	  InputStr=replaceSubstring(InputStr,"%","[VELPERCENT]");

	       }
			if (InputStr.indexOf("&")>=0)
		   {
	      	  InputStr=replaceSubstring(InputStr,"&","[VELAMP]");

	       }
		   if (InputStr.indexOf(";")>=0)
		   {
	      	  InputStr=replaceSubstring(InputStr,";","[VELSEMICOLON]");

	       }

	       if (InputStr.indexOf(">") >= 0) {
                InputStr = replaceSubstring(InputStr, ">", "[VELGTSIGN]");

            }
            if (InputStr.indexOf("<") >= 0) {
                InputStr = replaceSubstring(InputStr, "<", "[VELLTSIGN]");

            }

	        if (InputStr.indexOf(" ") >= 0) {
                InputStr = replaceSubstring(InputStr, " ", "[VELSP]");

            }

			//KM-4Nov08
			if (InputStr.indexOf("+") >= 0) {
                InputStr = replaceSubstring(InputStr, "+", "[VELPLUS]");

            }


	   }
	   return InputStr ;
 }

function decodeString(InputStr)

 {

   if (InputStr!=null)
   {
       if (InputStr.indexOf("[SQuote]")>=0)
 	  {
       	  InputStr=replaceSubstring(InputStr,"[SQuote]","\'");
       }
       if (InputStr.indexOf("[DQuote]")>=0)
 	  {
       	  InputStr=replaceSubstring(InputStr,"[DQuote]","\"");
       }
       if (InputStr.indexOf("[CRet]")>=0)
 	  {
       	  InputStr=replaceSubstring(InputStr,"[CRet]","\r");

       }
       if (InputStr.indexOf("[NLine]")>=0)
 	  {
       	  InputStr=replaceSubstring(InputStr,"[NLine]","\n");

       }
        if (InputStr.indexOf("[HTab]")>=0)
 	   {
       	  InputStr=replaceSubstring(InputStr,"[HTab]","\t");
        }
        if (InputStr.indexOf("[BSlash]")>=0)
 	   {
       	  InputStr=replaceSubstring(InputStr,"[BSlash]","\\");

        }
		if (InputStr.indexOf("[VelHash]")>=0)
 	  	{
       	  InputStr=replaceSubstring(InputStr,"[VelHash]","#");
       	}
	    if (InputStr.indexOf("[VELCOMMA]")>=0)
 	  	{
       	  InputStr=replaceSubstring(InputStr,"[VELCOMMA]",",");
       	}
	    if (InputStr.indexOf("[VELPERCENT]")>=0)
 	  	{
       	  InputStr=replaceSubstring(InputStr,"[VELPERCENT]","%");
       	}
	    if (InputStr.indexOf("[VELAMP]")>=0)
 	  	{
       	  InputStr=replaceSubstring(InputStr,"[VELAMP]","&");
       	}
		if (InputStr.indexOf("[VELSEMICOLON]")>=0)
 	  	{
       	  InputStr=replaceSubstring(InputStr,"[VELSEMICOLON]",";");
       	}

	   	if (InputStr.indexOf("[VELGTSIGN]") >= 0) {
	            InputStr = replaceSubstring(InputStr, "[VELGTSIGN]", ">");
	        }

        if (InputStr.indexOf("[VELLTSIGN]") >= 0) {
            InputStr = replaceSubstring(InputStr, "[VELLTSIGN]", "<");
        }

        if (InputStr.indexOf("[VELSP]") >= 0) {
            InputStr = replaceSubstring(InputStr, "[VELSP]", " ");
        }

		//KM-4Nov08
		if (InputStr.indexOf("[VELPLUS]") >= 0) {
            InputStr = replaceSubstring(InputStr, "[VELPLUS]", "+");
        }


    }
    return InputStr ;
 }

// To override one of the character checking out of our standard list of checked characters
// val - char to be overridden
function overRideChar(val)
{
	overRideArray.push(val);
}
//reset the whole array
function resetOverRideChar()
{
	overRideArray=new Array();
}
//searches through an array for specified val
// overRideArray - array to search
// val- value to search
function arraySearch(array,val)
{
	var searchArray=array;
	var searchVal=val;
	if (searchArray.length==0) return false;
	for (i=0;i<searchArray.length;i++)
	{
		if (searchArray[i]==0) continue;
		if (searchArray[i]==searchVal)
		{
			return true;

		}
	}
	return false;
}
//To supress the cheking of a field for special characters, especially in allfldcheckquote
function overRideFld(name)
{
	overRideFldArray.push(name);

}

function resetOverRideFld()
{
	overRideFldArray=new Array();
}


function  splcharcheckforlinks(dataval)
{

     val= dataval;
     if(val==''||val==null || val=='null' || val == 'NULL')
	return true;

    if(val.indexOf("%")!= -1)
	{
	   alert("Special Character(%) not allowed for this Field");
           return false;
 	}

	if(val.indexOf("&")!= -1  && (!arraySearch(overRideArray,"&")))
	{
 	 alert("Special Character(&) not allowed for this Field");
         return false;
	}

    //if(val.indexOf("#")!= -1 && (overRideChar!="#"))

    if(val.indexOf("#")!= -1 && (!arraySearch(overRideArray,"#")))
      {
	   alert("Special Character(#) not allowed for this Field");
           return false;
	}
    if(val.indexOf("\"")!= -1)
	{alert("Special Character(\") not allowed for this Field");
           return false;
	}

	return true;
}

// sonia

function checkquote(dataval)
{

    val= dataval;

    if(val==''|| val==null || val == 'null' || val == 'NULL')
	return true;

    if(val.indexOf("\"")!= -1)
	{alert("Special Character(\") not allowed for this Field");
           return false;
	}

	return true;
}

// function to check single quote and double quote for all fields in the form....anu
function allfldquotecheck(formobj)
{
  i=0;

  var elemArray=formobj.elements;
  //  while( != null)
for(i=0;i<elemArray.length;i++)
{

   //if (arraySearch(overRideFldArray,elemArray[i].name)) continue;
   fldType=formobj[i].type;
   //km
   fldName=formobj[i].name;

   if((fldType=="text" || fldType=="textarea" || fldType=="file") && (!(formobj[i].readOnly)))
   {
	val=formobj[i].value;
	//Added by Manimaran to allow single quotes specifically in these fields.
	if ((checkQuote==null||checkQuote=="Y") && (fldName=='studyTitle' || fldName== 'studyObjective' || fldName == 'studySummary' || fldName=='protocolNotes')){
	;
	}
	else if (checkQuote==null||checkQuote=="Y") {
	  if(val.indexOf("'")!=-1)
		  {alert("Special Character(') not allowed for this Field");
		formobj[i].focus();
		return false;
		}
	}//if checkquote

	//Added by Manimaran to allow double quotes specifically in this field.
	if ((fldName == 'patnotes'))
	{;
	}
	else if(val.indexOf("\"")!=-1)
	  {alert("Special Character(\") not allowed for this Field");
		formobj[i].focus();
		return false;
		}
      }
  }//while
}

function validateDataRange(datafld,op1,val1,logOp1,op2,val2)
 {

var str1;
var str2;

var data_fld = "" + datafld;

	if(data_fld == null || data_fld == "")
	 {
		return true;
	 }


	/* if(!(isDecimal(data_fld)) )
	 {
		 return false;
	 } else 
	 	 {
	 	 	 if (!isInteger(data_fld))
	 	 		{
	 	 			return false;
	 	 		}
	 	 } */
	 	 
	 	 
	if (! isDecimalOrNumberValAndNotBlank(data_fld))
	{
		return false;
	}

	
	if(op1==">")
	 str1 =data_fld > val1;
	else if(op1=="<")
		str1 = data_fld < val1;
	else if(op1==">=")
	 	str1 = data_fld >= val1;
	else if(op1=="<=")
	 	str1 = data_fld <= val1;

	if(op2==">")
		str2 = data_fld > val2;
	else if(op2=="<")
		str2 = data_fld < val2;
	else if(op2==">=")
	 	str2 = data_fld >= val2;
	else if(op2=="<=")
		str2 = data_fld <= val2;



	if(logOp1=="and")
	 {
		if((str1) && (str2))
		{
		 return true;
		}
		else
		 {
			return false;
		 }
	 }
	 else if(logOp1=="or")
	 {
		if((str1) || (str2))
		{
		 return true;
		}
		else
		 {
			return false;
		 }
	 }

	 else
	 {
	 if((str1) || (str2))
	  return true;

	  else
	  return false;

	 }

	return true;

 }


 function validateNumFormat(colName)
 {
	/*Modified by Sonia Abrol, 03/09/05, if the column is disabled, bypass its
	mandatory validation*/



	if (colName.length == undefined || colName.type == 'select-one')
	 {
		if (colName.disabled)
		{
			return true;
		}

	 }
	else
	{

		if (colName.length > 0)
		{
		   if (colName[0].disabled ==  true)
			{
				return true;
			}

		}
	}



	colValue = colName.value;
    colLen =colValue.length;
	count = 0;
	for(i=0;i<colLen;i++)
	 {
	  if((colValue.charAt(i)!="#") && (colValue.charAt(i)!="."))
		 {
		  alert("Please specify the format in #");
		  colName.focus();
		  return false;
		 }
	 if(colValue.charAt(i)==".")
		 {
		  count++;
		 }
	 if(count>1)
		 {
		  alert("Please Specify the Format with one decimal point");
		  colName.focus();
		  return false;
		 }
	 }
	 if(colValue.charAt(colLen-1)==".")
	 {
	   alert("Please specify '#' after decimal point");
	   colName.focus();
	   return false;
	 }
 return true;
 }



/* Function to validate the data lengh of the text box */
function validateDataSize(column,len,name)
{
 var actLength=column.value.length;

 var lengthAllowed=parseInt(len);

 if (lengthAllowed<actLength){
            alert("Data size exceeded for "+name+" \nMaximum size allowed is "+len+".");
		column.focus();
            return false;
 }
return true;
}



/*** Function to open 'user search window' from a form.. opens the the one that selects a single user
 parameters
 formname : the form Name
 idfld : name of the id field
 namefld : name of the user name field */

function openCommonUserSearchWindow(formname,idfld,namefld)
 {
      var windowparam;

      windowparam = "&genOpenerFormName=" + formname + "&genOpenerUserNameFld=" + namefld + "&genOpenerUserIdFld=" + idfld;
      window.open("usersearchdetails.jsp?fname=&lname=" + windowparam ,"usersearchdetails","toolbar=no,scrollbars=yes,resizable=yes,menubar=no,width=800,height=450,left=100,top=200")

 }

/*** Function to check for special characters to be restricted for field XSL
 parameters
 dataval : the string to check
 returns : true if no restricted special character found
*/


function  splcharcheckForXSL(dataval)
{

     val= dataval;
     if(val=='' || val == null || val == 'null' || val == 'NULL' )
     return true;


    if(val.indexOf("\\")!= -1)
	{
	  alert("No Special Character(\\) Allowed");
	  return false;
	}

    if(val.indexOf("{")!= -1)
	{
	  alert("No Special Character({) Allowed");
	  return false;
	}

    if(val.indexOf("}")!= -1)
	{
	  alert("No Special Character(}) Allowed");
	  return false;
	}

	return true;
}

/**
Return a index of element in an array.
@param arrayOfObjects - array to search through
@param searchStr - String to search in an Array
@return Return the index of string in an array
  return -1 if not found
*/
function IndexOf(arrayOfObjects,searchStr)
{
   var index=-1;
   for (var i=0;i<arrayOfObjects.length;i++)
  {

    if (arrayOfObjects[i]==searchStr)
    {
     index=i;
      break;
    }
  }
  return index;
}


	//to check the format of entered data, format is specified as ##.## etc and dont display any alert message.
		// This for the soft check in forms
	function validateDataFormatNoAlert(colname,format) {

		/*Modified by Sonia Abrol, 03/09/05, if the column is disabled, bypass its
		mandatory validation*/



		if (colname.length == undefined || colname.type == 'select-one')
		 {
			if (colname.disabled)
			{
				return true;
			}

		 }
		else
		{

			if (colname.length > 0)
			{
			   if (colname[0].disabled ==  true)
				{
				return true;
				}

			}
		}

		val = colname.value;

		if(val==null || val=='') return true;

		valLen = val.length;
		valDecimalPos = val.indexOf(".");
		valNoAfterDec = valLen - (valDecimalPos+1) ;

		len = format.length;
		decimalPos = format.indexOf(".");
		noAfterDec = len - (decimalPos+1) ;

		//the position of decimal does not match with that given in format
		if (decimalPos != valDecimalPos) {
			return false;
		}
		//the number of numbers after decimal do not match with that given in format
		if (noAfterDec != valNoAfterDec) {
			return false;
		}

		return true;
	}

// Parameter name is the name of the field.
	//To validate the column and do not display alert messages. This is for the soft checks applied in form.
function validate_col_no_alert(name,column)
{


	// to check for single and double quotes..
	if((column.name).toLowerCase()=="esign")
	{

	  t=document.forms.length;
	  for(k=0;k<t;k++)
		{
		  formobj = document.forms[k];
		  if(allfldquotecheck(formobj)==false)
		  return false;
		}

	}

	else
	{
		value=column.value;
	}

	/*Modified by Sonia Abrol, 03/09/05, if the column is disabled, bypass its
		mandatory validation*/



	if (column.length == undefined || column.type == 'select-one')
	 {
		if (column.disabled)
		{
			return true;
		}

	 }
	else
	{

		if (column.length > 0)
		{
		   if (column[0].disabled ==  true)
			{
				return true;
			}

		}
	}


	if (column.type == "select-one")
			{
				 i = column.options.selectedIndex;
				 value = column.options[i].value;
			}
		else
		{
	        value=column.value;
		}
            if(value==''||value==null){
				 return false;
            }else if (isWhitespace(value) == true){
                 return false;
            }else {
                return true;
            }
    }

    // find the occurence of a character in a String
    function checkChar(dataVal,val)
    {
	    var dataValue=dataVal;
	    var charVal=val;
	    if (dataVal.indexOf(val)>=0)
	    {
		return true;
	    }
	    else
	    {
		   return false;
	    }
     }

     function IsNetscape()
     {
     if ( navigator.product == "Gecko" && navigator.productSub >= 20030210 )
	     return true;
     else return false;
     }

     	function validate_chk_radio_no_alert(name,column) {
 	totrows = column.length;
	checked = false;
	if ( totrows == undefined || totrows==1) {
		if (column.disabled ==  true)
			{
				return true;
			}
		if (column.checked) {
			checked=true;
		}else {
			checked=false;
		}
	} else
		{//more than one checkbox
		if (totrows > 0) //bypass validation for disabled columns
		{
			if (column[0].disabled ==  true)
			{
				return true;
			}
		}
		for (i=0;i<totrows;i++) {
			if (column[i].checked) {
				checked=true;
				break;
			} else {
				checked=false;
			}
		}
	}
	if (!checked) {

		return false;
	}
    return true;
 }

     /** Method opens the FCKeditor window with the supplied parameter
     */
     function openPopupEditor(formname,fieldname,formatfldname,toolbar,length)
     {
	     //KM-Width modified for Submit bar implementation
		 url="popupeditor.jsp?formname="+formname+"&fieldname="+fieldname+"&formatfieldname="+formatfldname+"&toolbar="+toolbar+"&length="+length;
	     popupeditor=window.open(url,"popupeditor","toolbar=no,scrollbars=no,resizable=no,menubar=no,width=600,height=300,left=100,top=200");
	     popupeditor.focus();
     }

    /**
	 *  Replaces the special character with the HTML encoding using html codes
	 *
	 *@param  str  String to encode
	 */
	function htmlEncode(str)
	{
		if (str==null) return null;
		if (str.length==0) return "";
		if (str.indexOf("'")>=0)
		str=replaceSubstring(str,"'","'");
		if (str.indexOf("\"")>=0)
		str=replaceSubstring(str,"\"","&#034;");
		if (str.indexOf("&quot;")>=0)
		str=replaceSubstring(str,"&quot;","&#034;");
		if (str.indexOf("<")>=0)
		str=replaceSubstring(str,"<","&lt;");
		if (str.indexOf(">")>=0)
		str=replaceSubstring(str,">","&gt;");
		if (str.indexOf("\r\n")>=0)
		str=replaceSubstring(str,"\r\n","<br/>");

		return str;
	}

	/**
	 *  Replaces the HTML encoding to special characters using html codes mapping
	 *
	 *@param  str  String to decode
	 *@return      Returns the decoded String. null if str is null
	 */
	function htmlDecode(str)
	{
		if (str==null) return null;
		if (str.length==0) return "";
		if (str.indexOf("&amp;")>=0)
		str=replaceSubstring(str,"&amp;","&");
		if (str.indexOf("'")>=0)
		str=replaceSubstring(str,"'","'");
		if (str.indexOf("&#034;")>=0)
		str=replaceSubstring(str,"&#034;","\"");
		if (str.indexOf("&lt;")>=0)
		str=replaceSubstring(str,"&lt;","<");
		if (str.indexOf("&gt;")>=0)
		str=replaceSubstring(str,"&gt;",">");
		if (str.indexOf("<br/>")>=0)
		str=replaceSubstring(str,"<br/>","\r\n");
		return str;
	}

	function getBrowserType()
	{
		if (document.all) {browserType = "ie"}
		if (window.navigator.userAgent.toLowerCase().match("gecko")) {browserType= "gecko"}
		return browserType;
	}





/* date functions*/

	/* returns last day of the month, the month index starts from 1*/
	function getLastDayOfMonth(month ,year)
	{
		var lastDay="";
		switch(month) {
			case "1":
				lastDay="31";
				break;
			case "2":
				var yrNum=0;
				yrNum = year;
				if (((yrNum) % (400)) == 0) {
					lastDay="29";
				}else {
					lastDay="28";
				}
				break;
			case "3":
				lastDay="31";
				break;
			case "4":
				lastDay="30";
				break;
			case "5":
				lastDay="31";
				break;
			case "6":
				lastDay="30";
				break;
			case "7":
				lastDay="31";
				break;
			case "8":
				lastDay="31";
				break;
			case "9":
				lastDay="30";
				break;
			case "10":
				lastDay="31";
				break;
			case "11":
				lastDay="30";
				break;
			case "12":
				lastDay="31";
				break;
		}
		return lastDay;
		//end of fn
	}
	function checkNumeric(objName,minval, maxval,comma,period,hyphen)
{
	var numberfield = objName;
	if (chkNumeric(objName,minval,maxval,comma,period,hyphen) == false)
	{
		numberfield.select();
		numberfield.focus();
		return false;
	}
	else
	{
		return true;
	}
}

		function chkNumeric(objName,minval,maxval,comma,period,hyphen)
		{
		// only allow 0-9 be entered, plus any values passed
		// (can be in any order, and don't have to be comma, period, or hyphen)
		// if all numbers allow commas, periods, hyphens or whatever,
		// just hard code it here and take out the passed parameters
		var checkOK = "0123456789" + comma + period + hyphen;
		var checkStr = objName;
		var allValid = true;
		var decPoints = 0;
		var allNum = "";

		for (i = 0;  i < checkStr.value.length;  i++)
		{
		ch = checkStr.value.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		if (ch == checkOK.charAt(j))
		break;
		if (j == checkOK.length)
		{
		allValid = false;
		break;
		}
		if (ch != ",")
		allNum += ch;
		}
		if (!allValid)
		{
		alertsay = "Please enter only these values \""
		alertsay = alertsay + checkOK + "\" in the \"" + checkStr.name + "\" field."
		alert(alertsay);
		return (false);
		}

		// set the minimum and maximum
		var chkVal = allNum;
		var prsVal = parseInt(allNum);
		if (chkVal != "" && !(prsVal >= minval && prsVal <= maxval))
		{
		alertsay = "Please enter a value greater than or "
		alertsay = alertsay + "equal to \"" + minval + "\" and less than or "
		alertsay = alertsay + "equal to \"" + maxval + "\" in the \"" + checkStr.name + "\" field."
		alert(alertsay);
		return (false);
		}
		}

	//checks if the number is blank, then its not a valid decimal
    function isDecimalAndNotBlank(as_str)
    {
	  if (isWhitespace(as_str ) || isEmpty(as_str) ) {

	  	   return false;
        }

         var c = as_str.charAt(0) ;

		if (c == "-" || c == "+")
		   {
			return isDecimal( as_str.substring(1,as_str.length) );
		  }
		  else
		  {
	  		return isDecimal(as_str);
		  }


    }

    function isIntegerAndNotBlank(as_str)
    {
      if (isWhitespace(as_str ) || isEmpty(as_str) ) {

	  	    return false;
       }
       var c = as_str.charAt(0) ;

       if (c == "-" || c == "+")
		   {
			return isInteger( as_str.substring(1,as_str.length) );
		  }
		  else
		  {
	  		return isInteger(as_str);
		  }

    }

    function isDecimalOrNumberValAndNotBlank(as_Str)
    {

    	if (! isDecimalAndNotBlank(as_Str))
    	{

    		if(! isIntegerAndNotBlank(as_Str))
    		{
    		 			return false;
    		}
    	}
    		return true;
    }




  function getDatediff(date_col1, date_col2)
    {
    	//datecol1 is the first date, datecol2 is subtracted from datecol1

    	// dont calculate difference if any of fields is disabled
    	if (date_col1.disabled || date_col2.disabled)
		{
			return 0;
		}

		// dont calculate difference if any of fields is does not have valid date
    	if ( (!validate_date_optionalmsg(date_col1 ,false)) || (!validate_date_optionalmsg(date_col2 ,false)))
		{
			return 0;
		}


        var date1=date_col1.value;
          if(date1==null || date1=='') return 0;

        var date2=date_col2.value;
           if(date2==null || date2=='') return 0;


        var dt1 = createDate(date1);
        var dt2 = createDate(date2);


      //Set 1 day in milliseconds
		var one_day=1000*60*60*24;
		 	var diff;

		//Calculate difference btw the two dates, and convert to days
		diff = Math.round(Math.ceil(dt1.getTime()-dt2.getTime()) /(one_day) );

		return diff;
	}
function getLookup(formobj,url,filter) {


var tempValue;
var urlL="";
formobj.target="Lookup";
formobj.method="post";
urlL="multilookup.jsp?"+url;
if (filter.length>0){
urlL=urlL+"&"+filter;
}
formobj.action=urlL;
formWin =open('donotdelete.html','Lookup','resizable=1,status=0, width=850,height=550 top=100,left=100,menubar=no,scrollbars=1');
if (formWin && !formWin.closed) formWin.focus();
formobj.submit();
formobj.target="";
}
function checkradio(theRadio){
 var name=theRadio.id;
 var attValue=theRadio.getAttribute(name+"_wasChecked");
 if(attValue=="true"){
  theRadio.checked = false;
  theRadio.setAttribute(name+"_wasChecked","false");
 } else {
  theRadio.setAttribute(name+"_wasChecked","true");
 }
}

  /**
     * Escape special character with escape character '\' for javascripts
     *

     */

    function escapeSingleQuoteEtc(str) {

        if (str==null) return null;
		if (str.length==0) return "";


		if (str.indexOf("'")>=0)
		{
		str=replaceSubstring(str,"'","\\'");

		}

		if (str.indexOf("\r\n")>=0)
		str=replaceSubstring(str,"\r\n"," ");

        return str;
    }

    function changeDDSize(elem1d,expansionflag)
    {

    	if (typeof document.body.style.maxHeight == "undefined") {

				return true;
 				// IE6, older browsers, dont process further
			}


    	elem=document.getElementById(elem1d);

    	if (expansionflag == '1')
    	{
    		elem.style.width = "";
    		elem.size=elem.length;
    	}
    	else
    	{
    		elem.style.width = "177px";
    		elem.size=0;
    	}
    }


/* rounds a decimal value to given number of decimals places
   num - the number to be rounded
   dec - the decimal places the number should be rounded to*/
   
function roundANumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}