function setValandSubmit()
{
if(document.getElementById("mobilePDR-free").checked || document.getElementById("mobilePDR-memory-card").checked) {
if(document.getElementById("mobilePDR-free").checked){
document.getElementById("78_0_0_1").value ='B';
}
else {
document.getElementById("78_0_0_1").value ='C' ;
} 
}
else {
document.getElementById("78_0_0_1").value ='A'
}

var id = document.getElementById("emailaddressid").value;
//document.getElementById(id).value=document.getElementById("originalemailid").value;
if(!validateEmailId(document.getElementById("emailid").value)) {
setErrorMessage("errorEmailID", "Please enter valid email address");
return false; }
else {
removeErrorMessage("errorEmailID");if(document.getElementById("mobilePDR-memory-card").checked) {      //  document.getElementById("f2").target="_blank";	//	document.getElementById("f2").method="post";	//	document.getElementById("f2").submit();}return true;

}
}
function disableLink(obj){if(document.getElementById(obj).checked){return true;}else{return false;}}
function setAddressID(address,obj) {
if(document.getElementById("81_0_0_1")!=null) {
var addressArr = address.split("_");
var addressID = addressArr[1];
var addrObj = document.getElementById("81_0_0_1");

if(obj.checked) {
if(addrObj.value != "") {
setErrorMessage("errorPDR","Please choose Only one adress");
document.getElementById(address).checked = false; 
 }
 else {
 removeErrorMessage("errorPDR");
 addrObj.value =addressID;
 }
}
else {

if(addrObj.value == addressID) {
addrObj.value ="";
removeErrorMessage("errorPDR");
 }
}
}
}
function toAscii (str)  {

var symbols = " !\"#$%&'()*+'-./0123456789:;<=>?@";
var loAZ = "abcdefghijklmnopqrstuvwxyz";
symbols+= loAZ.toUpperCase();
symbols+= "[\\]^_`";
symbols+= loAZ;
symbols+= "{|}~";
var loc;
loc = symbols.indexOf(str);
if (loc >-1) { 
Ascii_Decimal = 32 + loc;
return (32 + loc);
}
return(0); 
}




function checkName() {
 
var iChars = "~`\!@#$%^&*()+=-[]\';,./{}|\":<>?";

  var pdrtextbox = '';
  
  pdrtextbox=document.getElementById("phyid").value;
  
  if (pdrtextbox == "" ) {
   
   setErrorMessage("error"+"PhysID","Please enter Preferred Account ID");
   return false;
   }
  // if (pdrtextbox.length > 0 && pdrtextbox.length > 10)
  // {
    //setErrorMessage("error"+"PhysID","Value should not be more than 10");
    //return false;
   //}
   var eflag = false;
    for (var i = 0; i < pdrtextbox.length; i++) {
    if (iChars.indexOf( pdrtextbox.charAt(i)) != -1 || toAscii(pdrtextbox.charAt(i)) == 32) 
  	{
  	eflag = true ;
  	break;
  	 
    }
    }
    if(eflag)
    {
    setErrorMessage("error"+"PhysID","Contains special characters. These are not allowed.Please remove them and try again.");
    return false;
    }
 return true;
}


/** this global error is used to differentiate the form submit or change in dropdown */
var skipValidation=false;
/*
 *This function removes the affiliation error messages from the
 *affiliation page.
 */

function removeAffiliationErrorMessages()
{
   document.getElementById("affiliationerror").innerHTML="";
   document.getElementById("affiliationerror").style.display="none"
}

/*
 *This function hides a layer
 *
 */

 function hideLayer(layer)
 {
    var layerOne = document.getElementById("1div"+layer);
    layerOne.style.display="none";
    var layerTwo = document.getElementById("2div"+layer);
    layerTwo.style.display="none";
 }
 /*
 *This function shows a layer
 *
 */

 function showLayer(layer)
 {
   var layerOne = document.getElementById("1div"+layer);
    layerOne.style.display="";
    var layerTwo = document.getElementById("2div"+layer);
    layerTwo.style.display="";
 }

 /*
 *This function checks if the atleast one option from the radio button is selected.
 *
 */
 function  checkAllOptions(f)
{
   var toReturn = false;
   for(var i = 0; i < f.length; i++)
      {
      if(f.elements[i].type == "radio")
        {
            if(f.elements[i].checked)
            {
               toReturn = true;
            }
        }
     }

     return toReturn;
}

/*
 *This function checks if the affiliation entered is right.
 *
 */

function checkAffiliation(radioObjId)
{

   var flag = checkRadioButtons(radioObjId);
   if(!flag) {
      document.getElementById("affiliationerror").style.display="block"
      document.getElementById("affiliationerror").innerHTML="Please select the hospital with which you are affiliated.";
      return false;
   }
   return true;
}


/*
 *This function checks if the atleast one option from the radio button is selected.
 *
 */

function checkRadioButtons(radioObj){
   var flag=false;
   for(i=0;i<radioObj.length;i++){
      if(radioObj[i].checked){
         flag=true;
         break;
      }
   }
   return flag;
}


// this variable is used to build the drop down options for the primary specialty.
var selectArrPri = new Array();

// this variable is used to build the drop down options for the secondary specialty.
var selectArrSec = new Array();


/*
 *This function is used to build the primary specialty drop down.
 *
 */

function bldUpdatePri(docObj,hintObj)
{
   var str = hintObj.value.replace('\\s*','');
   var j = 0;
   var pattern = new RegExp("^"+str,"i");
   if (selectArrPri.length == 0)
   {
      for(var i=0;i<docObj.options.length;i++)
      {
         selectArrPri[i] = docObj.options[i];
      }
   }
   for(var i=0;i<selectArrPri.length;i++)
   {
      if(selectArrPri[i].text.indexOf(str)== 0)
      {
         docObj.options[j++] = selectArrPri[i];
      }
      docObj.options.length = j;
   }
   if(j==1)
   {
      docObj.options[0].selected = true;
   }
   return true;
}

/*
 *This function is used to build the secondary specialty drop down.
 *
 */
function bldUpdateSec(docObj,hintObj)
{
   var str = hintObj.value.replace('\\s*','');
   var j = 0;
   var pattern = new RegExp("^"+str,"i");
   if (selectArrSec.length == 0)
   {
      for(var i=0;i<docObj.options.length;i++)
      {
         selectArrSec[i] = docObj.options[i];
      }
   }
   for(var i=0;i<selectArrSec.length;i++)
   {
      if(selectArrSec[i].text.indexOf(str)== 0)
      {
         docObj.options[j++] = selectArrSec[i];
      }
      docObj.options.length = j;
   }
   if(j==1)
   {
      docObj.options[0].selected = true;
   }
   return true;
}

/*
 *This function is used to confirm the specialties entered by the user
 *in the medical information page.
 *
 */
function verifyChoice(docObj)
{
   if(docObj.selectedIndex>-1){
   var val1 = docObj.options[docObj.selectedIndex].text;
   var val2 = docObj.options[docObj.selectedIndex].value;
   var choice = confirm('You chose\n'+val1+'\nIs this OK?');
   if (choice)
   {
      docObj.options.length = 1;
      docObj.options[0].value = val2;
      docObj.options[0].text = val1;
      docObj.options[0].selected = true;
      return true;
   }
   else
   {
      docObj.selected = true;
      return false;
   }
   }
   return true;
}


/*
 *This function is used to check the phone number format.
 *
 */
function checkPhoneNumField(id)
{
   var string = document.getElementById(id).value;   
   var FilterOne=/^[0-9 ]*$/;
   var FilterTwo =  /^[0-9]{3}\-[0-9]{3}\-[0-9]{4}$/;
   var FilterThree = /^\([0-9]{3}\)[0-9]{3}\-[0-9]{4}$/;
   var FilterFour =  /^\([0-9]{3}\)[ ][0-9]{3}\-[0-9]{4}$/;  
   if (string == "")
   {
         return (false);
   }     
  if( !isUsNumber(string) || isRepeatedValue(string))
   {
      return(true);
   }
   if( FilterOne.test(string) || FilterTwo.test(string) || FilterThree.test(string) || FilterFour.test(string) )
   {
       return(false);
   }
   else
   {
      return(true);
   }
  return false;
}
/*
 *This function is used to check the if this is US phone number
 *
 */
function isUsNumber(string)
{
   var toReturn = false;
   var val = extract(string);
   if (val.length > 0 && val.length == 10)
   {
      if(( val.substring(0,3) >= 201 ) && ( val.substring(3,6) != 555 ) && (parseInt(val.charAt(3)) > 1 ) )
      {
         toReturn = true;
      }            
   }
   return toReturn;
}

/*
 *This function is used to check the if this is not US phone number
 *
 */
 function isNonUsNumber(string)
 {
    if(isNaN(string))
   {
      return false; 
   }
    if (string.length < 11 || string.length >15)
    {
       return false;                
    }
     return true;
 }
/*
 *This function is to extract only numbers
 *
 */
function extract(value)
{
   var result = "";
   var digPat = /[0-9]/;
   if( value != null && value.length > 0 )
   {
      for( var i = 0; i < value.length; i++ )
      {
         var ch = value.substring( i, i+1 );
         if( ch.match( digPat ) != null )
         {
            result = result + ch;
         }
      }
   }
   return result;
}
/*
 *This function is used to check the occurance of recursive string.
 *
 */
function isRepeatedValue(val)
{
   var toReturn = true;
   if(val != null && val.length > 0)
   {
      var firstChar = val.substring(0,1);
      for(var i=1; i < val.length; i++)
      {
         if(firstChar != val.substring(i,i+1))
         {
            toReturn = false;
         }
      }
   }
   return toReturn;
}

/*
 *This function is used to check the extension format.
 *
 */
function checkExtnField(string)
{
   var Filter=/^[0-9]*$/;
   if( !Filter.test(string) || string == "" || string == 0 )
   {
      return(false);
   }
   return true;
}

/*
 *This function is used to check the zip code format.
 *
 */
function checkZipCodeField(string)
{
   var Filter=/^[0-9]*$/;
   if( !Filter.test(string) )
   {
      return(false);
   }
   if(parseInt(string)==0)
   {
      return (false);
   }
   return true;
}

/*
 *This function is used to check the address field format.
 *
 */
function checkAddressField(string)
{
   var Filter=/^[a-zA-Z]*$/;
   if( !Filter.test(string) )
   {
      return(false);
   }
   return true;
}

/*
 *This function is used to check the UPIN format.
 *
 */
function checkUPIN(widgetId,divId,errorMessage)
{
   removeErrorMessage(divId);
   var isChange = document.getElementById("changed"+widgetId).value;
   if (isChange == 'Y')
   {
      var string = document.getElementById(widgetId).value;
      if (string == "")
      {
         return (false);
      }
      var filter=/^[a-zA-Z][0-9]{5}$/;
      if( !filter.test(string) )
      {
         setErrorMessage(divId,errorMessage);
         return(true);
      }
      return (false);
    }
    else
    {
       return (false);
    }
}

/*
 *This function is used to check the password format.
 *
 */
function checkPassword(string)
{

   if(string.length<6)
   {
       return false;
   }

   return checkAlphaNumeric(string);
}

/*
 *This function is used to check if the String is alphanumeric.
 *
 */
function checkAlphaNumeric(string)
{

   var filter=/^[A-Za-z0-9]/;
   if(!(filter.test(string)) )
   {
      return false;
   }
    if(isRepeatedValue(string))
   {
      return false;
   }
   return true;
}

/*
 *This function is used to check the graduation year.
 *
 */
function checkYear(gyear)
{
   var Filter=/^[0-9]*$/;
   if( !Filter.test(gyear)){
      return false;
   }

   var gradYear = parseInt(gyear);
   var currentDate = new Date();
   var currentYear = currentDate.getFullYear();
   if(gradYear>(currentYear+10))
   {
      return false;
   }
   else if(gradYear<(currentYear-70))
   {
      return false;
   }
   return true;
}



/*
 * This method is to set the value to the hidden field
 */
function acceptAgreement(isAccepted){
   document.getElementById("isAccepted").value=isAccepted;
}

/*
 *This function is used to check the Birth Date.
 *
 */
function checkBirthDate(byear){
   var currentDate = new Date();
   var currentYear = currentDate.getFullYear();
   if(((currentYear-byear)<18 || (currentYear-byear)>99)) {
      return false;
   }
   return true;
}

var isError=false;


/*
 * This method is used to set the error message into the error block
 * Returns true when the field is empty
 */
function checkMandatoryValue(widgetId,divId,errorMessage)
{
   // removes the error message from the screen before evaluating.
   removeErrorMessage(divId);
   mandatoryIndVarName = "mandatory"+ widgetId;
   if (document.getElementById(mandatoryIndVarName) != null &&
            document.getElementById(mandatoryIndVarName).value != "Y")
   {
      return false;
   }
   // if the value has not been entered by the user error populates.

   if(document.getElementById(widgetId).type=="text" || document.getElementById(widgetId).type=="password" || document.getElementById(widgetId).type=="hidden")
   {
      document.getElementById(widgetId).value = trim(document.getElementById(widgetId).value);
   
      if(document.getElementById(widgetId).value=="")
      {
         setErrorMessage(divId,errorMessage);
         return true;
      }
   }
   else
   {
      if(document.getElementById(widgetId).selectedIndex==0)
      {
         setErrorMessage(divId,errorMessage);
         return true;
      }
   }

}

/*
 * trim left and right spaces for the string
 */
function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}



function checkFirstNameField(widgetId,divId)
{

   var nameFilterOne=/^[A-Za-z][ A-Za-z.\'\- ]*[A-Za-z.]$/;
   var nameFilterTwo=/^[A-Za-z][A-Za-z.]*$/;
   document.getElementById(widgetId).value = RTrim(document.getElementById(widgetId).value);
   if(checkMandatoryValue(widgetId,divId,"Please supply a first name."))
   {
      isError = true;
   }
    else if( !nameFilterOne.test(document.getElementById(widgetId).value) && !nameFilterTwo.test(document.getElementById(widgetId).value))
   {
      setErrorMessage(divId,"Please supply a first name");
      isError = true;
   }


}

function checkLastNameField(widgetId,divId)
{
   var nameFilterOne=/^[A-Za-z][ A-Za-z.\'\- ]*[A-Za-z.]$/;
   var nameFilterTwo=/^[A-Za-z][A-Za-z.]*$/;
   document.getElementById(widgetId).value = RTrim(document.getElementById(widgetId).value);
   if(checkMandatoryValue(widgetId,divId,"Please supply a last name."))
   {
      isError = true;
   }
   else if( !nameFilterOne.test(document.getElementById(widgetId).value) && !nameFilterTwo.test(document.getElementById(widgetId).value))
   {
      setErrorMessage(divId,"Please supply a last name.");
      isError = true;
   }
}

function validateEmailId (emailStr) 
{  
   emailStr = emailStr.toLowerCase();
   var checkTLD=1;   
   var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
   var emailPat=/^(.+)@(.+)$/; 
   var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
   var validChars="\[^\\s" + specialChars + "\]"; 
   var quotedUser="(\"[^\"]*\")";   
   var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
   var atom=validChars + '+';
   var word="(" + atom + "|" + quotedUser + ")";
   var userPat=new RegExp("^" + word + "(\\." + word + ")*$"); 
   var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
   var matchArray=emailStr.match(emailPat); 
   
   if (matchArray==null) 
   {   
      return false;
   }
   
   var user=matchArray[1];
   var domain=matchArray[2]; 
   
   for (i=0; i<user.length; i++) 
   {
      if (user.charCodeAt(i)>127) 
      {
         return false;
      }
   }
   
   for (i=0; i<domain.length; i++) 
   {
      if (domain.charCodeAt(i)>127) 
      {  
         return false;
      }
   }
   
   if (user.match(userPat)==null) 
   {
      return false;
   } 
      
   var IPArray=domain.match(ipDomainPat);
   
   if (IPArray!=null) 
   {
      for (var i=1;i<=4;i++) 
      {
         if (IPArray[i]>255) 
         {
            return false;
         }
      }
      return true;
   }
      
   var atomPat=new RegExp("^" + atom + "$");
   
   var domArr=domain.split(".");
   
   var len=domArr.length;
   
   for (i=0;i<len;i++) 
   {
      if (domArr[i].search(atomPat)==-1)
      {  
         return false;
      }
   }
      
   if (checkTLD && domArr[domArr.length-1].length!=2 &&  
      domArr[domArr.length-1].search(knownDomsPat)==-1) 
   {
      return false;
   } 

   if (len<2) 
   {
      return false;
   }  
   return true;
} 
function checkEmailField(widgetId,divId)
{
  // var emailFilter=/^[a-zA-Z0-9][a-zA-Z0-9_.]*[@][a-zA-Z0-9]+[.][a-zA-Z]+$/;

   if(checkMandatoryValue(widgetId,divId,"Please supply a valid email address."))
   {
      isError = true;
   }
   else if ( !(validateEmailId(Trim(document.getElementById(widgetId).value)) ) )
   {
      setErrorMessage(divId,"Please supply a valid email address.");
      isError = true;
   }
}

function checkDEAField(widgetId,divId,lastNameId)
{
   var isChange = document.getElementById("changed"+widgetId).value;
   if(checkMandatoryValue(widgetId,divId,"Please supply a valid DEA number."))
   {
      isError = true;
   }
   else if(isChange == 'Y')
   {
      if (document.getElementById(widgetId).value.length > 0 &&
                 checkDEAFormat(document.getElementById(widgetId),lastNameId))
      {
         setErrorMessage(divId,"Please supply a valid DEA number.");
         isError = true;
      }
   }


}

/*
 *This function is used to check the DEA format.
 *
 */
function checkDEAFormat(deaObj,lastNameId)
{
   var str = deaObj.value;
   var lastName = document.getElementById(lastNameId).value.toUpperCase();
   var firstCharLastName = lastName.substr(0,1);
   var firstNum   = parseInt(str.substr(2,1));
   var secondNum  = parseInt(str.substr(3,1));
   var thirdNum   = parseInt(str.substr(4,1));
   var fourthNum  = parseInt(str.substr(5,1));
   var fifthNum   = parseInt(str.substr(6,1));
   var sixthNum   = parseInt(str.substr(7,1));
   var seventhNum = parseInt(str.substr(8,1));
   var firstChar  = str.substr(0,1).toUpperCase();
   var secondChar = str.substr(1,1).toUpperCase();
   var isFirstCharRight = false;
   var isValidDEA = true;
   if ((firstChar == 'A') || (firstChar == 'B') || (firstChar == 'F') || (firstChar == 'M') || (firstChar == 'P') || (firstChar == 'R'))
   {
      isFirstCharRight = true;
   }

   if(firstCharLastName == '$')//if $lastName velocity is not rendered.
   {
      //stopping validation. In this case dyne handler has to validate.
      return false;
   }

   var sumOfDigits = (firstNum + thirdNum + fifthNum) + 2*(secondNum + fourthNum + sixthNum);
   if ((sumOfDigits%10 == seventhNum) && ((secondChar == firstCharLastName) || (secondChar == '9')) && isFirstCharRight)
   {
      return false;
   }
   else
   {
      return true ;
   }
 }

function setChangedInd(wName)
{
   var elemName = "changed"+wName;
   document.getElementById(elemName).value = 'Y';
}

function checkBirthDateField(widgetId,divId)
{

   var yearId = widgetId;
   if(document.getElementById(yearId).options[document.getElementById(yearId).selectedIndex].text!="YYYY"
      && !checkBirthDate(document.getElementById(yearId).options[document.getElementById(yearId).selectedIndex].text))
   {
      setErrorMessage(divId,"Please enter a valid date");
      isError = true;
   }
}

function checkCreatePasswordField(widgetId,divId,confirmPassWidgetId)
{

   if(checkMandatoryValue(widgetId,divId,"Please supply a password."))
   {
      isError = true;
      document.getElementById(confirmPassWidgetId).value = "";
   }
   else if(!checkPassword(document.getElementById(widgetId).value))
   {
      setErrorMessage(divId,"Please supply a valid password. Passwords must be between 6 and 20 alphanumeric characters.");
     document.getElementById(widgetId).value = "";
     isError = true;
     document.getElementById(confirmPassWidgetId).value = "";
   }
}

function checkConfirmPassword(createwidgetId,confirmwidgetId,createdivId,confirmdivId)
{
   if(checkMandatoryValue(confirmwidgetId,confirmdivId,"Please confirm your password."))
   {
      setErrorMessage(confirmdivId,"Please confirm your password.");
      isError = true;
   }
   if(!checkPassword(document.getElementById(confirmwidgetId).value))
   {
      if(document.getElementById(createwidgetId)!= null)
      {
      if(document.getElementById(createwidgetId).value.length > 0 && checkPassword(document.getElementById(createwidgetId).value))
      {
          if(document.getElementById(confirmwidgetId).value.length > 0)
         {
             setErrorMessage(confirmdivId,"Your passwords did not match, please recreate your password and confirm.");
             isError = true;
             document.getElementById(confirmwidgetId).value = "";
             document.getElementById(createwidgetId).value = "";
         }
         else
         {
             setErrorMessage(confirmdivId,"Please confirm your password.");
              isError = true;
         }
         }
      }
   }
   else if(document.getElementById(confirmwidgetId).value!=document.getElementById(createwidgetId).value)
   {
      
     if(document.getElementById(createwidgetId)!= null)
      {
      if(document.getElementById(createwidgetId).value.length > 0 && checkPassword(document.getElementById(createwidgetId).value))
      {
         if(document.getElementById(confirmwidgetId).value.length > 0)
         {
            setErrorMessage(confirmdivId,"Your passwords did not match, please recreate your password and confirm.");
            isError = true;
            document.getElementById(confirmwidgetId).value = "";
            document.getElementById(createwidgetId).value = "";
         }
         else
         {
             setErrorMessage(confirmdivId,"Please confirm your password.");
              isError = true;
         }
      }
      }
   }
}

function checkConfirmEmail(createwidgetId,confirmwidgetId,createdivId,confirmdivId)
{
   
   if(checkMandatoryValue(confirmwidgetId,confirmdivId,"Please confirm your email address."))
   {
      setErrorMessage(confirmdivId,"Please confirm your email address.");
      isError = true;
   }
   if ( !(validateEmailId(Trim(document.getElementById(confirmwidgetId).value)) ) )
   {
       
      if(document.getElementById(createwidgetId)!= null)
      {
      if(document.getElementById(createwidgetId).value.length > 0 && validateEmailId(Trim(document.getElementById(createwidgetId).value)))
      {
          if(document.getElementById(confirmwidgetId).value.length > 0)
         {
             setErrorMessage(confirmdivId,"Your emails did not match, please re-enter your email and confirm.");
             isError = true;
             
         }
         else
         {
             setErrorMessage(confirmdivId,"Please confirm your email address.");
              isError = true;
         }
         }
      }
     
   }
   else if(Trim(document.getElementById(confirmwidgetId).value.toLowerCase()) != Trim(document.getElementById(createwidgetId).value.toLowerCase()))
   {
      
     if(document.getElementById(createwidgetId)!= null)
      {
      if(document.getElementById(createwidgetId).value.length > 0 && validateEmailId(Trim(document.getElementById(createwidgetId).value)))
      {
          if(document.getElementById(confirmwidgetId).value.length > 0)
         {
             setErrorMessage(confirmdivId,"Your emails did not match, please re-enter your email and confirm.");
             isError = true;
             
         }
         else
         {
             setErrorMessage(confirmdivId,"Please confirm your email address.");
              isError = true;
         }
         }
      }
    
   }
}
function setErrorMessage(divId,errorMessage)
{
   document.getElementById(divId).style.display="block"
   document.getElementById(divId).innerHTML=errorMessage;
}

function removeErrorMessage(divId)
{
   document.getElementById(divId).innerHTML="";
   document.getElementById(divId).style.display="none"
}

function validateLoginAttributes()
{
   isError=false;
   if (document.getElementById("importantMessageDiv") != null)
   {
        document.getElementById("importantMessageDiv").style.display="none";
   }

   document.getElementById("login.username_index_0").value=RTrim(document.getElementById("login.username_index_0").value);
   if(checkMandatoryValue("login.username_index_0","useridError","Please supply a User ID."))
   {
      isError=true;
   }
   if(checkMandatoryValue("login.password_index_0","passwordError","Please supply a password."))
   {
      isError=true;
   }
   if (isError)
   {
      window.scroll(0,0);
      if (document.getElementById("importantMessageDiv") != null)
      {
         document.getElementById("importantMessageDiv").style.display="block";
      }
   }
   return !isError;
}
function validatePasswdAttributes()
{
   isError=false;
   if (document.getElementById("importantMessageDiv") != null)
   {
        document.getElementById("importantMessageDiv").style.display="none";
   }

  // document.getElementById("login.username_index_0").value=RTrim(document.getElementById("login.username_index_0").value);
    
   if(checkMandatoryValue("login.password_index_0","passwordErrorProfile","Please supply a password."))
   {
      isError=true;
   }
   if (isError)
   {
      window.scroll(0,0);
      if (document.getElementById("importantMessageDiv") != null)
      {
         document.getElementById("importantMessageDiv").style.display="block";
      }
   }
   return !isError;
}
function validateCreditCardNumber(objIDCreditCardType,objIDCreditCardNumber)
{
var objCreditCardType = document.getElementById(objIDCreditCardType);
var objCreditCardNumber = document.getElementById(objIDCreditCardNumber);

var creditCardTypeCode;
var validNumber = false;

if(objCreditCardType!=null && objCreditCardNumber!=null )
{
    if(objCreditCardNumber.value == ""){
     return false;
    } 
	for(iterator=0;iterator<=objCreditCardType.length;iterator++)
	{
		if(objCreditCardType[iterator].selected)
		{
			creditCardTypeCode = objCreditCardType[iterator].value;
			iterator = objCreditCardType.length;
		}
	}
	
	if(creditCardTypeCode == '1' && (objCreditCardNumber.value.match("^\\d{13}$") || objCreditCardNumber.value.match("^\\d{16}$") ))
	{
		if(IsValidPrefix(creditCardTypeCode,objCreditCardNumber.value))
		{
			validNumber = IsValidByMOD10(objCreditCardNumber.value);
		}
	}
	else if((creditCardTypeCode == '2'|| creditCardTypeCode == '4') && objCreditCardNumber.value.match("^\\d{16}$") )
	{
		if(IsValidPrefix(creditCardTypeCode,objCreditCardNumber.value))
		{
			validNumber = IsValidByMOD10(objCreditCardNumber.value);
		}
	}
	else if(creditCardTypeCode == '3' && objCreditCardNumber.value.match("^\\d{15}$"))
	{
		if(IsValidPrefix(creditCardTypeCode,objCreditCardNumber.value))
		{
			validNumber = IsValidByMOD10(objCreditCardNumber.value);
		}
	}	

}

return validNumber;

}

function IsValidPrefix(creditCardTypeCode,creditCardNumber)
{
	var prefixArray;
	
	switch(creditCardTypeCode)
	{
		case '1':
				prefixArray = new Array('4');
				break;
		case '2':
				prefixArray = new Array('51','52','53','54','55');
				break;
		case '4':
				prefixArray = new Array('6011','644','645','646','647','648','649','65');
				break;
		case '3':
				prefixArray = new Array('34','37');
				break;
	}	
	
	if(prefixArray!=null)
	{	
		for(iterator=0;iterator<prefixArray.length;iterator++)
		{
			if(creditCardNumber.indexOf(prefixArray[iterator]) == 0)
			{
				return true;
			}
		}
		
		if(creditCardTypeCode == '4')
		{		
			if(parseInt(creditCardNumber.substring(0,6)) > 622125 && parseInt(creditCardNumber.substring(0,6)) < 622926)
			{
				return true;
			}
		}
	}
	
	return false;
}

function IsValidByMOD10(creditCardNumber)
{
		var sum = 0;

		var alternate = false;
		// Loop through the credit card number
		for (iterator = creditCardNumber.length - 1; iterator >= 0; iterator--)
		{
			// Get each number
			currentDigit = parseInt(creditCardNumber.substring(iterator, iterator + 1));
			// If alternate number, multiply by 2
			// After multiplication, check whether the number is greater than 9. If yes,
			// Mod the number by ten and add the result with 1 and make it as a single digit.
			// Example: 12 - 12%10 = 2. 1 + 2 = 3.
			if (alternate) {
				currentDigit *= 2;
				if (currentDigit > 9)
				{
					currentDigit = (currentDigit % 10) + 1;
				}
			}
			sum += currentDigit;
			alternate = !alternate;
		}
		
		return (sum % 10 == 0);
}
function checkExpiryDate(objExpriryDateID)
{

    expDate = document.getElementById(objExpriryDateID).value;
	var currentDate = new Date();
	var currentMonth;
	var currentYear;
	
    if (expDate.match(new RegExp('[0-1][0-9][/][0-9][0-9]'))) 
    {
		currentMonth = currentDate.getMonth() + 1;
		currentMonth = currentMonth.toString();
		currentYear = currentDate.getFullYear().toString();
		
		if(currentMonth.length == 1)
		{
			currentMonth = "0" + currentMonth;
		}
		
	  	var gvnMonth = parseInt(expDate.substring(0,2),10) ;
		var gvnYear = parseInt(expDate.substring(3,5),10);
		var curMonth = parseInt(currentMonth,10);
		var curYear =  parseInt(currentYear.substring(2,4),10);
		
		if( (gvnYear < curYear || gvnMonth > 12) || (gvnYear == curYear && gvnMonth < curMonth) || gvnMonth <= 0)		
		{			
			return false;
		}
		
    }
    else
    {
        return false;
    }

   return true;
}

/**
 * This general function is called from the dynamic pages which loops through all the form
 * fields and get the attribute ids from the form field ids and does the specific validation
 * for that attribute.
 */
function validateAttributes()
{
  document.getElementById("dyneFieldSelected").value = "";
  if (document.getElementById("importantMessageDiv") != null)
  {
        document.getElementById("importantMessageDiv").style.display="none";
  }
   var form = document.DEThomletPage;
   
   var attrId;
   var firstNameId=""
   var lastNameId="";
   var passwordId="";
   var isCalled=false;

   var chkLicense = false;
   var isUSASelected = false;
   var specialty42 = "";
   var specialty44 = "";
   var hospital = "";
   var resStartDate = "";
   var resEndDate = "";
   var isRadioButton=false;
   var stateLicenseId = "";
   var medicalSchoolIndex=0;
   var medicalSchoolState="";
   var hospitalSchoolState="";
   isError=false;
   var z=0;
   var array=new Array();   
   
   if(!skipValidation)
   {
      for(var i = 0; i < form.length; i++)
      {
         attrId = findAttributeCode(form.elements[i].id);

         if(attrId=="15")
         {
            checkFirstNameField(form.elements[i].id,"error"+form.elements[i].id);
            firstNameId=form.elements[i].id;
         }
         else if(attrId=="16")
         {
            checkLastNameField(form.elements[i].id,"error"+form.elements[i].id);
            lastNameId=form.elements[i].id;
         }
         else if(attrId=="24" || attrId=="54")
         {
            checkEmailField(form.elements[i].id,"error"+form.elements[i].id);
         if(document.getElementById("confirmEmail") != null)
          {
            checkConfirmEmail(form.elements[i].id,"confirmEmail","error"+form.elements[i].id,"confirmemailerror");
          }
         }
         else if(attrId=="22")
         {
            if( lastNameId == "" || lastNameId == null)
            {
             lastNameId = "hidden_16_0_0_1";
            }
            checkDEAField(form.elements[i].id,"error"+form.elements[i].id,lastNameId);
         }
         else if(attrId=="23")
         {
            if (checkUPIN(form.elements[i].id,"error"+form.elements[i].id,"Please supply a valid UPIN number"))
            {
             isError=true;
            }
         }
         else if(attrId=="18")
         {
            if(checkMandatoryValue(form.elements[i].id,"error"+form.elements[i].id,"Please supply a Birth City"))
            {
             isError=true;
            }
         }
         else if(attrId=="40")
         {
            removeErrorMessage("error"+form.elements[i].id);
            if(document.getElementById(form.elements[i].id).value=="")
            {
             setErrorMessage("error"+form.elements[i].id,"For your security, please provide a Password Hint Question to help you recover your password.");
             isError=true;
            }else if(document.getElementById(form.elements[i].id).value.length > 50)
          {
             setErrorMessage("error"+form.elements[i].id,"Max length for Hint Question is 50.");
             isError=true;
          }
         }
         else if(attrId=="41")
         {
            if(checkMandatoryValue(form.elements[i].id,"error"+form.elements[i].id,"Please enter a Password Hint Answer."))
            {
              isError=true;
            }
            document.getElementById(form.elements[i].id).value = Trim(document.getElementById(form.elements[i].id).value);
         }
         else if(attrId=="25")
         {
            if(checkMandatoryValue(form.elements[i].id,"error"+form.elements[i].id,"Please supply a Company/practice name."))
            {
              isError=true;
              skipValidation = false;
              return !isError;
            }
         }
         else if(attrId=="4060")
         {
            if(checkMandatoryValue(form.elements[i].id,"error"+form.elements[i].id,"Please enter a Serial Number."))
            {
              isError=true;
            }
         }
          else if(attrId=="4062")
         {
            if(checkMandatoryValue(form.elements[i].id,"error"+form.elements[i].id,"Please select a Device Type."))
            {
              isError=true;
            }
         }
         else if(attrId=="26")
         {
            if(checkMandatoryValue(form.elements[i].id,"error"+form.elements[i].id,"You must fill in at least one address line."))
            {
              isError=true;
            }
         }
         else if(attrId=="28")
         {
            if(checkMandatoryValue(form.elements[i].id,"error"+form.elements[i].id,"Please supply a city."))
            {
              isError=true;
            }
         }
         else if(attrId=="29")
         {
            removeErrorMessage("error"+form.elements[i].id);
            if(isMandatory(form.elements[i].id))
            {
                if(checkSelected(form.elements[i].id))
                {
                   setErrorMessage("error"+form.elements[i].id,"Please supply a state.");
                   isError=true;
                }
            }
         }
         else if(attrId=="30")
         {
            if(checkMandatoryValue(form.elements[i].id,"error"+form.elements[i].id,"Please supply a country."))
            {
              isError=true;
            }
            else if(getSelectedValue(form.elements[i].id) == "USA")
            {
             isUSASelected = true;
            }
         }
         else if(attrId=="19")
         {
            if(!isCalled)
            {
               if(checkForBirthDate("error19_0_0_1","Please supply a date of birth.","19p2_0_0_1","19p3_0_0_1","19p1_0_0_1"))
               {
                  isError=true;
               }
            }
                            
               // added by vinay starts
            // removes the error message from the screen before evaluating.
            mandatoryIndVarName = "mandatory"+ form.elements[i].id;
            if (document.getElementById(mandatoryIndVarName) != null &&
                     document.getElementById(mandatoryIndVarName).value == "Y")
            {

               // if the value has not been entered by the user error populates.


               if(document.getElementById("19p2_0_0_1").selectedIndex==0)
               {
                  setErrorMessage("error19_0_0_1","Please supply a date of birth.");
                  isError=true;;
               }

            }
            // added by vinay ends
 
            isCalled=true;
         }
         else if(attrId=="31")
         {
         removeErrorMessage("error"+form.elements[i].id);
            if(isUSASelected)
            {
               
            var string = document.getElementById(form.elements[i].id).value;
             if(string != null)
             {
               string = trimString(string)
             }
            if(string == null || string == "" )
            {
               setErrorMessage("error"+form.elements[i].id,"Please supply a valid zip code.");
               isError=true;
            }
            //checkUSAZipCode(form.elements[i].id,"error"+form.elements[i].id,"Please supply a valid zip code.", "Please supply a valid zip code.")
            }
            else if(checkZipCode(form.elements[i].id,"error"+form.elements[i].id,"Please supply a valid zip code.", "Please supply a valid zip code."))
            {
               isError=true;
            }
         }
         else if(attrId=="32")
         {
          // var mandatoryName = "mandatory"+ form.elements[i].id;
          removeErrorMessage("error"+form.elements[i].id);
            if(isMandatory(form.elements[i].id))
            {
                if(checkSelected(form.elements[i].id))
                {
                   setErrorMessage("error"+form.elements[i].id,"Please supply an address type.");
                   isError=true;
                }
            }
          /*if (document.getElementById(mandatoryName) != null && document.getElementById(mandatoryName).value == "Y")
          {
                  if(form.elements[i-1] != null && (form.elements[i-1].id != form.elements[i].id))
               {
                  removeErrorMessage("error"+form.elements[i].id);
               }
               if(form.elements[i].checked)
               {
                  isRadioButton = true;
               }
               if(form.elements[i+1] != null && form.elements[i].id != form.elements[i+1].id)
               {
                  if(!isRadioButton)
                  {
                    setErrorMessage("error"+form.elements[i].id,"Please supply an address type.");
                    isError=true;
                  }
               isRadioButton = false;
               }
          }*/
         }
         else if(attrId=="37")
         {
            removeErrorMessage("error"+form.elements[i].id);
         document.getElementById(form.elements[i].id).value = Trim(document.getElementById(form.elements[i].id).value);
            if(isUSASelected)
            {
               if(document.getElementById(form.elements[i].id).value.length > 0)
               {
                  if(checkPhoneNumField(form.elements[i].id))
                  {
                     setErrorMessage("error"+form.elements[i].id,"Please supply a valid phone number.");
                     isError=true;
                  }
               }
            }
         else
          {
            if(document.getElementById(form.elements[i].id).value.length > 0)
               {
               if(!isNonUsNumber(document.getElementById(form.elements[i].id).value))
               {
                setErrorMessage("error"+form.elements[i].id,"Please supply a valid phone number.");
                isError=true;
               }
            }
          }
         }
         else if(attrId=="38")
         {
            removeErrorMessage("error"+form.elements[i].id);
            if(isUSASelected)
            {
               if(document.getElementById(form.elements[i].id).value.length > 0)
               {
                  if(checkPhoneNumField(form.elements[i].id))
                  {
                     setErrorMessage("error"+form.elements[i].id,"Please supply a valid fax number.");
                     isError=true;
                  }
               }
            }
         else
          {
            if(document.getElementById(form.elements[i].id).value.length > 0)
               {
               if(!isNonUsNumber(document.getElementById(form.elements[i].id).value))
               {
                setErrorMessage("error"+form.elements[i].id,"Please supply a valid fax number.");
                isError=true;
               }
            }
          }
        isUSASelected = false;
         }
         else if(attrId=="17")
         {
            removeErrorMessage("error"+form.elements[i].id);
            if(isMandatory(form.elements[i].id))
            {
               if(checkSelected(form.elements[i].id))
               {
                  setErrorMessage("error"+form.elements[i].id,"Please select your professional degree from the list below.");
                  isError=true;
               }
            }
         }
       else if(attrId=="75")
         {
            removeErrorMessage("error"+form.elements[i].id);
            if(isMandatory(form.elements[i].id))
            {
               if(checkSelected(form.elements[i].id))
               {
                  setErrorMessage("error"+form.elements[i].id,"Please select your primary practice setting.");
                  isError=true;
               }
            }
         }
         else if(attrId=="39")
         {
            removeErrorMessage("error"+form.elements[i].id);
            checkCreatePasswordField(form.elements[i].id,"error"+form.elements[i].id, "confirmPassword");
         removeErrorMessage("confirmpassworderror");
            checkConfirmPassword(form.elements[i].id,"confirmPassword","error"+form.elements[i].id,"confirmpassworderror");
         }
         else if(attrId=="53")
         {
            removeErrorMessage("error"+form.elements[i].id);
            if(isMandatory(form.elements[i].id))
            {
               if(checkSelected(form.elements[i].id))
               {
                  setErrorMessage("error"+form.elements[i].id,"Please select your primary practice type.");
                  isError=true;
               }
            }
         }
       else if(attrId=="51")
         {
            removeErrorMessage("error"+form.elements[i].id);
            if(isMandatory(form.elements[i].id))
            {
               if(document.getElementById(form.elements[i].id).value.length == 0)
               {
                  setErrorMessage("error"+form.elements[i].id,"Please enter California License Code.");
                  isError=true;
               }
            }
         }
         else if(attrId=="48")
         {
            removeErrorMessage("error"+form.elements[i].id);
            var attributeId = getAttrId(form.elements[i].id);
            if (attributeId == "48p1")
            {
               medicalSchoolState=document.getElementById(form.elements[i].id).value;
            }
          
            if(attributeId=="48p2")
            {
              medicalSchoolIndex = document.getElementById(form.elements[i].id).selectedIndex;
              var valueMedicalSchool = document.getElementById(form.elements[i].id).options[document.getElementById(form.elements[i].id).selectedIndex].value
              if (valueMedicalSchool=="" && medicalSchoolState!="")
              {
                   setErrorMessage("error"+form.elements[i].id,"Please select your school.");
                   isError=true;
              }                
            }
            

            if(isMandatory(form.elements[i].id))
            {
               if(checkSelectedEvenWhenEmpty(form.elements[i].id))
               {
                  if (attributeId == "48p1")
                  {
                     setErrorMessage("error"+form.elements[i].id,"Please select the state where you went to school.");
                  }
                  else if (attributeId == "48p2")
                  {
                     setErrorMessage("error"+form.elements[i].id,"Please select your school.");
                  }
                  isError=true;
               }
            }
         }
         else if(attrId=="42")
         {
            removeErrorMessage("errorduplicateSpecialty");
            removeErrorMessage("error"+form.elements[i].id);

            if(isMandatory(form.elements[i].id))
            {
            if(checkSelected(form.elements[i].id))
            {
               setErrorMessage("error"+form.elements[i].id,"Please select a primary specialty from the list below.");
               isError=true;
            }
            }
            if(!checkSelected(form.elements[i].id))
            {
                array[z]=getSelectedValue(form.elements[i].id);
                z=z+1;
            }
         }
         else if(attrId=="43")
         {
            removeErrorMessage("error"+form.elements[i].id);
            if(!checkSelected(form.elements[i].id))
            {
                array[z]=getSelectedValue(form.elements[i].id);
                z=z+1;
            }
            
         }
         else if(attrId=="44")
         {
            removeErrorMessage("error"+form.elements[i].id);
            if(!checkSelected(form.elements[i].id))
            {
               specialty44 = getSelectedValue(form.elements[i].id);
            }
         }
         else if(attrId=="52")
         {

            removeErrorMessage("error"+form.elements[i].id);
            var objid = form.elements[i].id;
            var partId = objid.substring(0,4);
            var secondPartId = objid.substring(4);
            var divId = "52"+secondPartId;
            var stateId= "";
            var valueHospital = "";
            stateId = "52p1"+secondPartId;
            if(partId== "52p2")
            {
               
               valueHospital = document.getElementById(form.elements[i].id).options[document.getElementById(form.elements[i].id).selectedIndex].value
               setHospital(valueHospital, divId);
               removeErrorMessage("error"+form.elements[i].id);
            }
            
            if (partId != "52p1")
            {
               if (document.getElementById(form.elements[i].id).value=="" && hospitalSchoolState!="")
               {
                  setErrorMessage("error"+form.elements[i].id,"Please select the hospital with which you are affiliated.");
                  isError=true;
               }
            }
            
            if (partId == "52p1")
            {
               hospitalSchoolState=document.getElementById(form.elements[i].id).value;
               removeErrorMessage("error"+stateId);
            }
            
            if(isMandatory(form.elements[i].id))
            {
              
               if(partId == "52p1")
               {
                  if (checkSelectedEvenWhenEmpty(stateId))
                  {
                    
                     setErrorMessage("error"+stateId,"Please select the state associated with your hospital.");
                     isError=true;
                  }
               }
               if (partId != "52p1")
               {
                  if(document.getElementById(form.elements[i].id).value == "")
                  {
                     setErrorMessage("error"+form.elements[i].id,"Please select the hospital with which you are affiliated.");
                     isError=true;
                  }
               }
            }
        
            
             
         }
         else if(attrId=="20")
         {
         
            removeErrorMessage("error"+form.elements[i].id);
            setResidentStartYear(document.getElementById("20p1_0_0_1").options[document.getElementById("20p1_0_0_1").selectedIndex].value);
            setResidentStartMonth(document.getElementById("20p2_0_0_1").options[document.getElementById("20p2_0_0_1").selectedIndex].value);
            if(isMandatory(form.elements[i].id))
            {
               var errorFromStartDate=false;
               if(checkSelected("20p2_0_0_1"))
               {
                  setErrorMessage("error"+form.elements[i].id,"Please choose your residency start date.");
                  isError=true;
                  errorFromStartDate=true;
               }
               if(checkSelected("20p1_0_0_1"))
               {
                  setErrorMessage("error"+form.elements[i].id,"Please choose your residency start date.");
                  isError=true;
                  errorFromStartDate=true;
               }
            }
            if (errorFromStartDate== false)
            {
               if (checkResidentStartDateForDE())
               {
                  setErrorMessage("error"+form.elements[i].id,"Please choose a valid residency start date.");
                  isError = true;
               }
            }

           
         }
         else if(attrId=="21")
         {
            setResidentEndYear(document.getElementById("21p1_0_0_1").options[document.getElementById("21p1_0_0_1").selectedIndex].value);
            setResidentEndMonth(document.getElementById("21p2_0_0_1").options[document.getElementById("21p2_0_0_1").selectedIndex].value);
            removeErrorMessage("error"+form.elements[i].id);
            
            if(isMandatory(form.elements[i].id))
            {
               var errorFromEndDate=false;
               if(checkSelected("21p2_0_0_1"))
               {
                  setErrorMessage("error"+form.elements[i].id,"Please choose when you expect to complete your residency.");
                  isError=true;
                  errorFromEndDate=true;
               }
               if(checkSelected("21p1_0_0_1"))
               {
                  setErrorMessage("error"+form.elements[i].id,"Please choose when you expect to complete your residency.");
                  isError=true;
                  errorFromEndDate=true;
               }
            
            }
            if (errorFromEndDate== false)
            {
        
               if (checkResidentEndDateForDE())
               {
                  setErrorMessage("error"+form.elements[i].id,"Please choose a valid residency start/End date.");
                  isError = true;
               }
            }
            

         }
         else if(attrId=="45")
         {
            removeErrorMessage("error"+form.elements[i].id);
            var specialty45 = getSelectedValue(form.elements[i].id);
         if(!document.getElementById("boardCertified_index_0").checked)
         {
            if(specialty44 == specialty45 && specialty44 != "")
            {
               setErrorMessage("error"+form.elements[i].id,"Please select a different speciality.");
               isError=true;
            }
         }
         }
         else if(attrId=="49")
         {
            var objid = form.elements[i].id;
            var partId = objid.substring(0,2);
            var secondPartId = objid.substring(2);
            var medicalSchoolForYearElement = "48p2"+secondPartId;
            var medicalIndexForYear = document.getElementById(medicalSchoolForYearElement).selectedIndex;
            var userTypeValueForGradYear = document.getElementById("userTypeValueForGradYear").value;
            var currentDate = new Date();
            var currentYear = currentDate.getFullYear();


            removeErrorMessage("error"+form.elements[i].id);
            checkGraduationYear(form.elements[i].id,"error"+form.elements[i].id);
            var mandatoryIndVarName = "mandatory"+ form.elements[i].id;
            if ((document.getElementById(mandatoryIndVarName) != null &&
                document.getElementById(mandatoryIndVarName).value == "Y") || document.getElementById(form.elements[i].id).value.length > 0)
            {
               if(document.getElementById("YOB"+form.elements[i].id) != null)
               {
                   var YOB = document.getElementById("YOB"+form.elements[i].id).value;
                   if(YOB !=null && YOB.length >0)
                   {
                     var gYear = document.getElementById(form.elements[i].id).value;
                //Commented as per issue 108 in Q&A Document. This Removes validation based on user type.
                    /* if (((gYear - currentYear) > 0) && ((userTypeValueForGradYear != "E") && (userTypeValueForGradYear != "F") && (userTypeValueForGradYear != "A")))
                     {
                        setErrorMessage("error"+form.elements[i].id,"Please enter your year of graduation (format xxxx).");
                        isError=true;
                     }
                     else */ if((gYear -  YOB) < 23)
                     {
                        setErrorMessage("error"+form.elements[i].id,"Please enter your year of graduation (format xxxx).");
                        isError=true;
                     }
                   }
                }
             }
  
         }
         else if(attrId=="76")
         {
            stateLicenseId = form.elements[i].id;
            removeErrorMessage("error"+form.elements[i].id);
            if(isMandatory(form.elements[i].id))
            {
         
                if(!checkSelected(form.elements[i].id))
                {
               
                   setErrorMessage("error"+form.elements[i].id,"Please supply state of licensure.");
                   isError=true;
                }
            }
         }
         else if(attrId=="50")
         {
            removeErrorMessage("error"+form.elements[i].id);
            if(!checkStateLicenseNumber(form.elements[i].id))
            {
                
                var objid = form.elements[i].id;
                var partId = objid.substring(0,2);
                var secondPartId = objid.substring(2);
                var stateForLicenseElement = "76"+secondPartId;
                var stateForLicense = document.getElementById(stateForLicenseElement).selectedIndex
                if(stateForLicense==0 && document.getElementById(form.elements[i].id).value!="")
                {
                  setErrorMessage("error"+form.elements[i].id,"Please supply the state of licensure.");
                    isError=true;
                }
                
            }
   
            if(isMandatory(form.elements[i].id))
            {
            
                if(document.getElementById(form.elements[i].id).value == "")
                {
               
                   setErrorMessage("error"+form.elements[i].id,"Please supply licensure number");
                   isError=true;
                }
            }
         }
      }//end of for loop
      
      

      //for duplicate specialties validation
      array.sort();
      for (var i=0; i<array.length-1; i++)
      {
          	if (array[i]!=null && array[i]!='undefined' && array[i]!='' && array[i]==array[i+1])
          	{ 
          	   setErrorMessage("errorduplicateSpecialty","Please select a different speciality.");
          	   isError=true;
          	   break;
          	}                         
      }       
      
   }//end of skipvalidation
   if (isError)
   {
      window.scroll(0,0);
      if (document.getElementById("importantMessageDiv") != null)
      {
         document.getElementById("importantMessageDiv").style.display="block";
      }
      
   }
   skipValidation = false;
   return !isError;
} //end of validate attributes function


	function checkOut()
	{
		removeErrorMessage("error"+"EmailIDOpt");
		removeErrorMessage("error"+"pdr");
		if(!(document.getElementById("emailId").value.length > 0))
		{
			setErrorMessage("error"+"EmailIDOpt","Please enter the Email Id.");
			isError=true;    
		}
		else
		{

			if(!(emailCheck(document.getElementById("emailId").value)))
			{
				isError=true;    
			}
			else
			{
				isError=false; 
			}

		}

		if(document.getElementById("pdr").checked|| document.getElementById("pdrtp").checked ||
		document.getElementById("thc").checked || document.getElementById("mdx").checked)
		{
			isError=false; 
			if(!(emailCheck(document.getElementById("emailId").value)))
			{
				isError=true;    
    		}
    		else
    		{
       			isError=false; 
    		}

		}
		else
		{
			setErrorMessage("error"+"pdr","Please select atleast one Preference.");
    		isError=true;

		}
 		skipValidation = false;
   		return !isError;
	
	}

	function populateValues(op)
	{
 		if(op=='pdr')
		{
	   		if(document.getElementById("pdr").checked)
	   		{
	    		document.getElementById("pdr").value=true;
	   		}
		}
		else if(op=='pdrtp')
		{
	  		if(document.getElementById("pdrtp").checked)
	   		{
				document.getElementById("pdrtp").value=true;
	        }
		}
		else if(op=='thc')
		{
	   		if(document.getElementById("thc").checked)
	    	{
				document.getElementById("thc").value=true;
			}
		}
		else if(op=='mdx')
		{
	  		if(document.getElementById("mdx").checked)
	    	{
				document.getElementById("mdx").value=true;
			}
		}
	}

	function emailCheck (emailStr) 
	{
		/* The following variable tells the rest of the function whether or not
		to verify that the address ends in a two-letter country or well-known
		TLD.  1 means check it, 0 means don't. */
		emailStr=emailStr.toLowerCase(); 
		var checkTLD=1;
        
        /* The following is the list of known TLDs that an e-mail address must end with. */
        
        var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

		/* The following pattern is used to check if the entered e-mail address
		fits the user@domain format.  It also is used to separate the username
		from the domain. */
		
		var emailPat=/^(.+)@(.+)$/;

		/* The following string represents the pattern for matching all special
		characters.  We don't want to allow special characters in the address. 
		These characters include ( ) < > @ , ; : \ " . [ ] */
		
		var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

		/* The following string represents the range of characters allowed in a 
		username or domainname.  It really states which chars aren't allowed.*/
		
		var validChars="\[^\\s" + specialChars + "\]";

		/* The following pattern applies if the "user" is a quoted string (in
		which case, there are no rules about which characters are allowed
		and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
		is a legal e-mail address. */

		var quotedUser="(\"[^\"]*\")";

		/* The following pattern applies for domains that are IP addresses,
		rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
		e-mail address. NOTE: The square brackets are required. */

		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

		/* The following string represents an atom (basically a series of non-special characters.) */

		var atom=validChars + '+';
		
		/* The following string represents one word in the typical username.
		For example, in john.doe@somewhere.com, john and doe are words.
		Basically, a word is either an atom or quoted string. */
		
		var word="(" + atom + "|" + quotedUser + ")";

		// The following pattern describes the structure of the user

		var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

		/* The following pattern describes the structure of a normal symbolic
		domain, as opposed to ipDomainPat, shown above. */
		
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

		/* Finally, let's start trying to figure out if the supplied address is valid. */

		/* Begin with the coarse pattern to simply break up user@domain into
		different pieces that are easy to analyze. */

		var matchArray=emailStr.match(emailPat);
	
		if (matchArray==null) 
		{

			/* Too many/few @'s or something; basically, this address doesn't
			even fit the general mould of a valid e-mail address. */

			setErrorMessage("error"+"EmailIDOpt","Please enter a valid Email Id.");
			return false;
		}
		var user=matchArray[1];
		var domain=matchArray[2];

		// Start by checking that only basic ASCII characters are in the strings (0-127).

		for (i=0; i<user.length; i++) 
		{
			if (user.charCodeAt(i)>127) 
			{
				setErrorMessage("error"+"EmailIDOpt","Please enter a valid Email Id.");
				return false;
   			}
		}
		for (i=0; i<domain.length; i++) 
		{
			if (domain.charCodeAt(i)>127) 
			{
				setErrorMessage("error"+"EmailIDOpt","Please enter a valid Email Id.");
				return false;
		    }
		}

		// See if "user" is valid 

		if (user.match(userPat)==null) 
		{
			// user is not valid

			setErrorMessage("error"+"EmailIDOpt","Please enter a valid Email Id.");
			return false;
		}

		// Domain is symbolic name.  Check if it's valid.
 
		var atomPat=new RegExp("^" + atom + "$");
		var domArr=domain.split(".");
		var len=domArr.length;
		for (i=0;i<len;i++) 
		{
			if (domArr[i].search(atomPat)==-1) 
			{
				setErrorMessage("error"+"EmailIDOpt","Please enter a valid Email Id.");
				return false;
		    }
  		}



		/* domain name seems valid, but now make sure that it ends in a
		known top-level domain (like com, edu, gov) or a two-letter word,
		representing country (uk, nl), and that there's a hostname preceding 
		the domain or country. */

		if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) 
		{
			setErrorMessage("error"+"EmailIDOpt","Please enter a valid Email Id.");
			return false;
		}

		// Make sure there's a host name preceding the domain.

		if (len<2) 
		{
			setErrorMessage("error"+"EmailIDOpt","Please enter a valid Email Id.");
			return false;
		}

		// If we've gotten this far, everything's valid!
		return true;
	}

function getAttrId(attr)
{
  attributeId = attr.substring(0,attr.indexOf("_"));
  return attributeId;
}


function checkGraduationYear(widgetId,divId)
{
   if(checkMandatoryValue(widgetId,divId,"Please enter your year of graduation (format xxxx)."))
   {
      isError = true;
   }
   else if(!checkYear(document.getElementById(widgetId).value))
   {
      setErrorMessage(divId,"Please enter your year of graduation (format xxxx).");
      isError = true;
   }

}

function validateMedicalInfoAttributes()
{
   var form = document.forms[0];
   var attrId;
   isError=false;
   isStartCalled=false;
   isEndCalled=false;
   for(i = 0; i < form.elements.length; i++) {
      attrId = form.elements[i].id.substring(0,form.elements[i].id.indexOf("_"));
      if(attrId=="20")
      {
         if(!isStartCalled)
         {
            if(checkDateforProfile("residentstartdayerror","Please choose your residency start date.","20_0_0_index_0","20_0_0_index_1","20_0_0_index_2",""))
            {
               isError=true;
            }
         }
         isStartCalled=true;
      }
      if(attrId=="21")
      {
         if(!isEndCalled)
         {
            if(checkResidentEndDateForProfile("residentenddayerror","Please choose when you expect to complete your residency.","20_0_0_index_0",
               "20_0_0_index_1","20_0_0_index_2","21_0_0_index_0","21_0_0_index_1","21_0_0_index_2"))
            {
               isError=true;
            }
            isEndCalled=true;
         }

      }
      if(attrId=="17")
      {
         if(checkMandatoryValue(form.elements[i].id,"degreeerror","Please select your professional degree from the list below."))
         {
            isError=true;
         }
      }
      if(attrId=="medicalSchoolState")
      {
         if(checkMandatoryValue(form.elements[i].id,"stateerror","Please select the state where you went to school."))
         {
            isError=true;
         }
      }
      if(attrId=="48")
      {
         if(checkMandatoryValue(form.elements[i].id,"schoolerror","Please select your school."))
         {
            isError=true;
         }
      }
      if(attrId=="49")
      {
         checkGraduationYear(form.elements[i].id,"yearerror");
      }
      if(attrId=="42")
      {
         if(document.getElementById(form.elements[i].id).length!=1)
         {
            if(checkMandatoryValue(form.elements[i].id,"specialtyerror","Please select a primary specialty from the list below."))
            {
               isError=true;
            }
         }
      }
   }
   return !isError;
}


function checkDuplicateUserIDEmail()
{
   var userNameVariable = document.getElementById("hiddenUserName").value;
   var username = document.getElementById(userNameVariable).value
   if (username != "")
   {
      if (document.getElementById("otherUserEmail").value == username)
      {
         setErrorMessage("emailerror","Please enter a new Email Address. You can't proceed with the same Email Address.");
         return true;
      }
   }
   return false;
}


/*
 * This method is to set the error message into the error block
 */
 function setErrorMessage(divId,errorMessage)
{
   if(document.getElementById(divId) != null)
   {
      document.getElementById(divId).style.display="block"
   document.getElementById(divId).innerHTML=errorMessage;
   }
}

/*
 * This method is to delete the error message from the error block
 */
function removeErrorMessage(divId)
{
   if(document.getElementById(divId) != null)
   {
      document.getElementById(divId).innerHTML="";
      document.getElementById(divId).style.display="none"
   }
}


/*
 * This method is to set the value to the hidden field for licenseCode
 * which is accepted by the user.
 */
function acceptAgreement(isAccepted){
  var nameOfVariable = document.getElementById("variableName").value;

  if (isAccepted)
  {
   document.getElementById("licenseCodeAccepted").value = document.getElementById("licenseCode").value;
   document.getElementById(nameOfVariable).value= document.getElementById("licenseCode").value;
  }
  else
  {
   document.getElementById(nameOfVariable).value = "-1";
   document.getElementById("licenseCodeAccepted").value = "-1";
  }

}



/*
 * This method is used to validate the zipcode entries and populate appropriate error messages
 * Returns true when the either the value entered is nothing or the value entered is invalid or both.
 */
function checkZipCode(widgetId,divId,errorZipCodeNotPresent, errorZipCodeNotValid)
{
   var isZipCodePresent = !checkMandatoryValue(widgetId,divId,errorZipCodeNotPresent)
   var isZipCodeValidFormat = true;
   if (isZipCodePresent)
   {
      isZipCodeValidFormat = !checkZipCodeFormat(widgetId,divId,errorZipCodeNotValid,errorZipCodeNotPresent);
   }

   return !(isZipCodePresent&&isZipCodeValidFormat)
}

/*
 * This method is used to validate the zipcode entries and populate appropriate error messages
 * Returns true when the either the value entered is nothing or the value entered is invalid or both.
 */
function checkUSAZipCode(widgetId,divId,errorZipCodeNotPresent, errorZipCodeNotValid)
{
   var isZipCodePresent = !checkMandatoryValue(widgetId,divId,errorZipCodeNotPresent)
   var isZipCodeValidFormat = true;
   if (isZipCodePresent)
   {
      isZipCodeValidFormat = !checkUSAZipCodeFormat(widgetId,divId,errorZipCodeNotValid);
   }

   return !(isZipCodePresent&&isZipCodeValidFormat)
}

/*
 *This function is used to check the zip code format.
 *Returns true when the zip code is of wrong format.
 *
 */
function checkUSAZipCodeFormat(widgetId,divId,errorZipCodeNotValid)
{
   var Filter1 =/^[0-9]*$/;
   var Filter2 = /^[0-9]*[ ]*[-][ ]*[0-9]*$/;
   var Filter3 = /^[0-9]*[-][0-9]*$/;

   var string = document.getElementById(widgetId).value;
   if( Filter1.test(string) || Filter2.test(string) || Filter3.test(string))
   {
         return false;
   }
   else
   {
        setErrorMessage(divId,errorZipCodeNotValid);
        return (true);
   }

   if( !Filter.test(string) )
   {
      setErrorMessage(divId,errorZipCodeNotValid);
      return(true);
   }
   if(parseInt(string)==0)
   {
      setErrorMessage(divId,errorZipCodeNotValid);
      return (true);
   }
   return false;
}

/*
 *This function is used to check the zip code format.
 *Returns true when the zip code is of wrong format.
 *
 */
function checkZipCodeFormat(widgetId,divId,errorZipCodeNotValid,errorZipCodeNotPresent)
{
   
   var Filter=/^[a-zA-Z0-9\- ]*$/;
   var string = document.getElementById(widgetId).value;
   if(string != null)
   {
       string = trimString(string);
   }
   if(string == null || string == "" )
   {
      setErrorMessage(divId,errorZipCodeNotPresent);
      return(true);
   }
   if( !Filter.test(string) )
   {
      setErrorMessage(divId,errorZipCodeNotValid);
      return(true);
   }
     return false;
}


/*
 * This method is used to validate the DEA entries and populate appropriate error messages
 * Returns true when the either the value entered is nothing or the value entered is invalid or both.
 */

function checkDEA(widgetId,divId,errorDEANotPresent, errorDEANotValid )
{
   var isDEAPresent = !checkMandatoryValue(widgetId,divId,errorDEANotPresent)
   var isDEAValidFormat = true;
   if (isDEAPresent)
   {
       isDEAValidFormat = !checkDEAFormat(widgetId,divId,errorDEANotValid);
   }
   return !(isDEAPresent&&isDEAValidFormat)
}


function checkDEAForRegistration(widgetId,divId,lastNameId,errorDEANotPresent, errorDEANotValid )
{
   var isDEAPresent = !checkMandatoryValue(widgetId,divId,errorDEANotPresent)
   var isDEAValidFormat = true;
   if (isDEAPresent)
   {
       isDEAValidFormat = !checkDEAFormatForRegistration(widgetId,divId,lastNameId,errorDEANotValid);
   }
   return !(isDEAPresent&&isDEAValidFormat)
}



/*
 *This function is used to check the DEA format.
 *Returns true when the value entered is invalid
 *
 */

function checkDEAFormatForRegistration(widgetId,divId,lastNameId,errorMessage)
{
   var str = document.getElementById(widgetId).value;
   var lastName = document.getElementById(lastNameId).value.toUpperCase();
   var firstCharLastName = lastName.substr(0,1);
   var firstNum   = parseInt(str.substr(2,1));
   var secondNum  = parseInt(str.substr(3,1));
   var thirdNum   = parseInt(str.substr(4,1));
   var fourthNum  = parseInt(str.substr(5,1));
   var fifthNum   = parseInt(str.substr(6,1));
   var sixthNum   = parseInt(str.substr(7,1));
   var seventhNum = parseInt(str.substr(8,1));
   var firstChar  = str.substr(0,1);
   var secondChar = str.substr(1,1);
   var isFirstCharRight = false;
   var isValidDEA = true;
   if ((firstChar == 'A') || (firstChar == 'B') || (firstChar == 'M') || (firstChar == 'P') || (firstChar == 'R'))
   {
      isFirstCharRight = true;
   }
   var sumOfDigits = (firstNum + thirdNum + fifthNum) + 2*(secondNum + fourthNum + sixthNum);
   if ((sumOfDigits%10 == seventhNum) && isFirstCharRight && (firstCharLastName == secondChar))
   {
      return false;
   }
   else
   {
      setErrorMessage(divId,errorMessage);
      return true;
   }
 }


/*
 *This function is used to set the resident start date.
 *
 */

function checkResidentStartDate(divId,errorMessage){
   removeErrorMessage(divId);
   var monthResidentStartDay = document.getElementById("MonthResidentStartDay").value;
   var dayResidentStartDay   = document.getElementById("DayResidentStartDay").value;
   var yearResidentStartDay  = document.getElementById("YearResidentStartDay").value;
   var today = new Date();
   var todayYear = today.getFullYear();
   var populated = "false";
   if (monthResidentStartDay != "")
   {
      populated = "true";
   }
   if (dayResidentStartDay != "")
   {
         populated = "true";
   }
   if (yearResidentStartDay != "")
   {
         populated = "true";
   }
   if (((monthResidentStartDay == "") || (dayResidentStartDay == "") || (yearResidentStartDay == "")) && (populated == "true"))
   {
      setErrorMessage(divId,errorMessage);
      return true;
   }


   var monthResidentStartDayStr = "";
   if (monthResidentStartDay == "1")
   {
      monthResidentStartDayStr="Jan";
   }
   else if (monthResidentStartDay == "2" )
   {
      monthResidentStartDayStr="Feb"
   }
   else if (monthResidentStartDay == "3" )
   {
      monthResidentStartDayStr="Mar"
   }
   else if (monthResidentStartDay == "4" )
   {
      monthResidentStartDayStr="Apr"
   }
   else if (monthResidentStartDay == "5" )
   {
      monthResidentStartDayStr="May"
   }
   else if (monthResidentStartDay == "6" )
   {
      monthResidentStartDayStr="Jun"
   }
   else if (monthResidentStartDay == "7" )
   {
      monthResidentStartDayStr="Jul"
   }
   else if (monthResidentStartDay == "8" )
   {
      monthResidentStartDayStr="Aug"
   }
   else if (monthResidentStartDay == "9" )
   {
      monthResidentStartDayStr="Sept"
   }
   else if (monthResidentStartDay == "10" )
   {
      monthResidentStartDayStr="Oct"
   }
   else if (monthResidentStartDay == "11" )
   {
      monthResidentStartDayStr="Nov"
   }
   else if (monthResidentStartDay == "12" )
   {
      monthResidentStartDayStr="Dec"
   }
   var variableName = document.getElementById("ResidentStartDayVariableName").value;
   if (populated == "true")
   {
      document.getElementById(variableName).value = yearResidentStartDay + "-" + monthResidentStartDay + "-" + dayResidentStartDay + " 00:00:00";
      document.getElementById("ResidentStartDayDisplay").value = dayResidentStartDay + "-" + monthResidentStartDayStr + "-" + yearResidentStartDay;
   }

   return false;
}

/*
 *This function is used to set the resident End date.
 *
 */

function checkResidentEndDateForProfile(divId,errorMessage,startMonthId,startDayId,startYearId,endMonthId,endDayId,endYearId){
   removeErrorMessage(divId);
   var monthResidentEndDay = document.getElementById(endMonthId).value;
   var dayResidentEndDay   = document.getElementById(endDayId).value;
   var yearResidentEndDay  = document.getElementById(endYearId).value;
   var today = new Date();
   var todayYear = today.getFullYear();
   var populated = "false";
   var monthResidentStartDay = document.getElementById(startMonthId).value;
   var dayResidentStartDay   = document.getElementById(startDayId).value;
   var yearResidentStartDay  = document.getElementById(startYearId).value;
   if (monthResidentEndDay != "")
   {
      populated = "true";
   }
   if (dayResidentEndDay != "")
   {
      populated = "true";
   }
   if (yearResidentEndDay != "")
   {
      populated = "true";
   }
   if (((monthResidentEndDay == "") || (dayResidentEndDay == "") || (yearResidentEndDay == "")) && (populated == "true"))
   {
      setErrorMessage(divId,errorMessage);
      return true;
   }
   if (populated == "true")
   {
      if ((yearResidentStartDay - yearResidentEndDay) > 0)
      {
         setErrorMessage(divId,"Please see if the Residency Start/ End dates are valid");
         return true;
      }
      else if ((yearResidentStartDay - yearResidentEndDay) == 0)
      {
         if ((monthResidentStartDay - monthResidentEndDay) > 0)
         {
            setErrorMessage(divId,"Please see if the Residency Start/ End dates are valid");
            return true;
         }
         else if ((monthResidentStartDay - monthResidentEndDay) == 0)
         if ((dayResidentStartDay - dayResidentEndDay) > 0 )
         {
            setErrorMessage(divId,"Please see if the Residency Start/ End dates are valid");
            return true;
         }
      }
   }

   return false;
}
/*
 *This function is used to set the resident End date.
 *
 */
function checkDateforProfile(divId,errorMessage,monthId,dayId,yearId,type)
{
   removeErrorMessage(divId);
   var monthBirthday = document.getElementById(monthId).value;
   var dayBirthday   = document.getElementById(dayId).value;
   var yearBirthday  = document.getElementById(yearId).value;
   var today = new Date();
   var populated = "false";
   if (monthBirthday != "")
   {
      populated = "true";
   }
   if (dayBirthday != "")
   {
      populated = "true";
   }
   if (yearBirthday != "")
   {
      populated = "true";
   }

   var todayYear = today.getFullYear();

   if (((monthBirthday == "") || (dayBirthday == "") || (yearBirthday == "")) && (populated == "true"))
   {
      setErrorMessage(divId,errorMessage);
      return true;
   }
   if(type=="birthdate")
   {
   if ((todayYear - yearBirthday) < 21 )
   {
      setErrorMessage(divId,errorMessage);
      return true;
   }
   }
   return false;
}
/*
 *This function is used to set the resident End date.
 *
 */

function checkResidentEndDate(divId,errorMessage){
   removeErrorMessage(divId);
   var monthResidentEndDay = document.getElementById("MonthResidentEndDay").value;
   var dayResidentEndDay   = document.getElementById("DayResidentEndDay").value;
   var yearResidentEndDay  = document.getElementById("YearResidentEndDay").value;
   var today = new Date();
   var todayYear = today.getFullYear();
   var populated = "false";
   var monthResidentStartDay = document.getElementById("MonthResidentStartDay").value;
   var dayResidentStartDay   = document.getElementById("DayResidentStartDay").value;
   var yearResidentStartDay  = document.getElementById("YearResidentStartDay").value;
   if (monthResidentEndDay != "")
   {
      populated = "true";
   }
   if (dayResidentEndDay != "")
   {
      populated = "true";
   }
   if (yearResidentEndDay != "")
   {
      populated = "true";
   }
   if (((monthResidentEndDay == "") || (dayResidentEndDay == "") || (yearResidentEndDay == "")) && (populated == "true"))
   {
      setErrorMessage(divId,errorMessage);
      return true;
   }
   if (populated == "true")
   {
      if ((yearResidentStartDay - yearResidentEndDay) > 0)
      {
         setErrorMessage(divId,"Please see if the Residency Start/ End dates are valid");
         return true;
      }
      else if ((yearResidentStartDay - yearResidentEndDay) == 0)
      {
         if ((monthResidentStartDay - monthResidentEndDay) > 0)
         {
            setErrorMessage(divId,"Please see if the Residency Start/ End dates are valid");
            return true;
         }
         else if ((monthResidentStartDay - monthResidentEndDay) == 0)
         if ((dayResidentStartDay - dayResidentEndDay) > 0 )
         {
            setErrorMessage(divId,"Please see if the Residency Start/ End dates are valid");
            return true;
         }
      }
   }

   var monthResidentEndDayStr = "";
   if (monthResidentEndDay == "1")
   {
      monthResidentEndDayStr="Jan";
   }
   else if (monthResidentEndDay == "2" )
   {
      monthResidentEndDayStr="Feb"
   }
   else if (monthResidentEndDay == "3" )
   {
      monthResidentEndDayStr="Mar"
   }
   else if (monthResidentEndDay == "4" )
   {
      monthResidentEndDayStr="Apr"
   }
   else if (monthResidentEndDay == "5" )
   {
      monthResidentEndDayStr="May"
   }
   else if (monthResidentEndDay == "6" )
   {
      monthResidentEndDayStr="Jun"
   }
   else if (monthResidentEndDay == "7" )
   {
      monthResidentEndDayStr="Jul"
   }
   else if (monthResidentEndDay == "8" )
   {
      monthResidentEndDayStr="Aug"
   }
   else if (monthResidentEndDay == "9" )
   {
      monthResidentEndDayStr="Sept"
   }
   else if (monthResidentEndDay == "10" )
   {
      monthResidentEndDayStr="Oct"
   }
   else if (monthResidentEndDay == "11" )
   {
      monthResidentEndDayStr="Nov"
   }
   else if (monthResidentEndDay == "12" )
   {
      monthResidentEndDayStr="Dec"
   }
   var variableName = document.getElementById("ResidentEndDayVariableName").value;
   if (populated == "true")
   {
      document.getElementById(variableName).value = yearResidentEndDay + "-" + monthResidentEndDay + "-" + dayResidentEndDay + " 00:00:00";
      document.getElementById("ResidentEndDayDisplay").value = dayResidentEndDay + "-" + monthResidentEndDayStr + "-" + yearResidentEndDay;
   }

   return false;
}

/*
 *This function is used to set the birthdate.
 *
 */

function checkBirthdate(divId,errorMessage){
   removeErrorMessage(divId);
   var monthBirthday = document.getElementById("MonthBirthday").value;
   var dayBirthday   = document.getElementById("DayBirthday").value;
   var yearBirthday  = document.getElementById("YearBirthday").value;
   var today = new Date();
   var populated = "false";
   if (monthBirthday != "")
   {
      populated = "true";
   }
   if (dayBirthday != "")
   {
      populated = "true";
   }
   if (yearBirthday != "")
   {
      populated = "true";
   }
   var todayYear = today.getFullYear();
   if (((monthBirthday == "") || (dayBirthday == "") || (yearBirthday == "")) && (populated == "true"))
   {
      setErrorMessage(divId,errorMessage);
      return true;
   }
   if ((todayYear - yearBirthday) < 21 )
   {
      setErrorMessage(divId,errorMessage);
      return true;
   }
   var monthBirthdayStr = "";
   if (monthBirthday == "1")
   {
      monthBirthdayStr="Jan";
   }
   else if (monthBirthday == "2" )
   {
      monthBirthdayStr="Feb"
   }
   else if (monthBirthday == "3" )
   {
      monthBirthdayStr="Mar"
   }
   else if (monthBirthday == "4" )
   {
      monthBirthdayStr="Apr"
   }
   else if (monthBirthday == "5" )
   {
      monthBirthdayStr="May"
   }
   else if (monthBirthday == "6" )
   {
      monthBirthdayStr="Jun"
   }
   else if (monthBirthday == "7" )
   {
      monthBirthdayStr="Jul"
   }
   else if (monthBirthday == "8" )
   {
      monthBirthdayStr="Aug"
   }
   else if (monthBirthday == "9" )
   {
      monthBirthdayStr="Sept"
   }
   else if (monthBirthday == "10" )
   {
      monthBirthdayStr="Oct"
   }
   else if (monthBirthday == "11" )
   {
      monthBirthdayStr="Nov"
   }
   else if (monthBirthday == "12" )
   {
      monthBirthdayStr="Dec"
   }
   var variableName = document.getElementById("BirthdayVariableName").value;
   if (populated == "true")
   {
      document.getElementById(variableName).value = yearBirthday + "-" + monthBirthday + "-" + dayBirthday + " 00:00:00";
      document.getElementById("BirthdayDisplay").value = dayBirthday + "-" + monthBirthdayStr + "-" + yearBirthday;
   }
   return false;
}

function getMonthinMMMFormat(monthBirthday)
{
   var monthBirthdayStr = "";
   if (monthBirthday == "1")
   {
      monthBirthdayStr="Jan";
   }
   else if (monthBirthday == "2" )
   {
      monthBirthdayStr="Feb"
   }
   else if (monthBirthday == "3" )
   {
      monthBirthdayStr="Mar"
   }
   else if (monthBirthday == "4" )
   {
      monthBirthdayStr="Apr"
   }
   else if (monthBirthday == "5" )
   {
      monthBirthdayStr="May"
   }
   else if (monthBirthday == "6" )
   {
      monthBirthdayStr="Jun"
   }
   else if (monthBirthday == "7" )
   {
      monthBirthdayStr="Jul"
   }
   else if (monthBirthday == "8" )
   {
      monthBirthdayStr="Aug"
   }
   else if (monthBirthday == "9" )
   {
      monthBirthdayStr="Sept"
   }
   else if (monthBirthday == "10" )
   {
      monthBirthdayStr="Oct"
   }
   else if (monthBirthday == "11" )
   {
      monthBirthdayStr="Nov"
   }
   else if (monthBirthday == "12" )
   {
      monthBirthdayStr="Dec"
   }
   return monthBirthdayStr;
}

/*
 * This method is to validate the entries in the AccountInfo page.
 */
function validateAffiliationAttributesForRegistration()
{
   
   isError = false;
   if (document.getElementById("importantMessageDiv") != null)
   {
        document.getElementById("importantMessageDiv").style.display="none";
   }
   removeErrorMessage("affiliationerror");
   var variableNameForRadioButtons = document.getElementById("variableNameForProfessionWithIndex").value;
   var affiliationCode = returnCheckedRadioButtonValue(document.getElementsByName(variableNameForRadioButtons));
   document.getElementById("affiliation").value = affiliationCode;
   if (affiliationCode == "")
   {
      setErrorMessage("affiliationerror","Please supply a profession.");
      isError = true;
   }
   if (isError)
   {
      window.scroll(0,0);
     if (document.getElementById("importantMessageDiv") != null)
      {
         document.getElementById("importantMessageDiv").style.display="block";
      }
      
   } 
   return !isError;
}

/*
 *This function checks if the atleast one option from the radio button is selected.
 *
 */

function returnCheckedRadioButtonValue(radioObj){
   var value = "";
   for(i=0;i<radioObj.length;i++){
      if(radioObj[i].checked){
         value = radioObj[i].value
         break;
      }
   }
   return value;
}

function validatePasswordFields()
{
   if (document.getElementById("importantMessageDiv") != null)
   {
        document.getElementById("importantMessageDiv").style.display="none";
   }
   isError = false;
   checkCreatePasswordField("password_index_0","createpassworderror", "confirmPassword_index_0");
   checkConfirmPassword("password_index_0","confirmPassword_index_0","createpassworderror","confirmpassworderror");
   if (isError)
   {
      window.scroll(0,0);
     if (document.getElementById("importantMessageDiv") != null)
      {
         document.getElementById("importantMessageDiv").style.display="block";
      }
      
   }
   return !isError;
}

function validateSignIn()
{
   isError=false;
   if (document.getElementById("importantMessageDiv") != null)
   {
        document.getElementById("importantMessageDiv").style.display="none";
   } 
   
   if(checkMandatoryValue("username_index_0","useridError","Please supply a User ID"))
   {
      isError=true;
   }
   if(checkMandatoryValue("password_index_0","passwordError","Please supply a Password."))
   {
      isError=true;
   }
   if (isError)
   {
      window.scroll(0,0);
     if (document.getElementById("importantMessageDiv") != null)
      {
         document.getElementById("importantMessageDiv").style.display="block";
      }
      
   } 
   return !isError;
}

/*
 * This method is temporarily added to alert the user that the link is not implemented.
 */
function checkImplementationExists()
{
   alert("This functionality is not yet implemented");
   return false;

}

function findAttributeCode(attributeName)
{


   myRe= new RegExp ("^([0-9]+)", "g");
   myArray = myRe.exec(attributeName);
   if (myArray == null)
   {
      return null;
   }
   return (myArray[0]);

}


function checkSelected(id)
{

   var selectBox = document.getElementById(id);
   if( selectBox.selectedIndex == 0 && selectBox.length > 1)
   {
      return true;
   }
   return false;
}

function checkSelectedEvenWhenEmpty(id)
{

   var selectBox = document.getElementById(id);
   if( selectBox.selectedIndex == 0)
   {
      return true;
   }
   return false;
}


function checkStateLicenseNumber(id)
{
   if(document.getElementById(id) != null)
   {
      if(document.getElementById(id).value.length <=0)
      {
         return true;
      }
      return false;
   }
}

function getSelectedValue(id)
{
   var combo = document.getElementById(id);
   if(combo != null)
   {
      return combo.item(combo.selectedIndex).value;
   }

}
function onChangeFormSubmit(attr, attrName)
{
   skipValidation = true;
   document.getElementById("dyneNoAttrValidation").value = attr;
   document.getElementById("dyneFieldSelected").value = attrName;
   
   document.DEThomletPage.submit();
}
/*
function onChangeFormSubmit()
{
   skipValidation = true;
   //document.getElementById("PFFormActionId_register.ThomletPage").click();
   document.DEThomletPage.submit();
}
*/


function isValidDate(monthBirthday, dayBirthday, yearBirthday)
{
    if (monthBirthday == 4 || monthBirthday == 6 || monthBirthday == 9 || monthBirthday == 11)
    {
       if (dayBirthday > 30)
       {
          return false;
       }
    }
    else if (monthBirthday == 2 && ((yearBirthday % 4 > 0) && (dayBirthday > 28))) 
    {
         return false;
    }
    else if (monthBirthday == 2 && (dayBirthday > 29))
    {
         return false; 
    }
    else if (dayBirthday > 31)
    {
         return false; 
    }
    else if (dayBirthday == 0)
    {
         return false;
    }
    return true;
}


function checkForBirthDate(divId,errorMessage,monthId,dayId,yearId)

{

   removeErrorMessage(divId);
   var monthBirthday = "";
   var dayBirthday = "";
   var yearBirthday = "";


   if(document.getElementById(monthId).selectedIndex > 0)
   {
              monthBirthday = document.getElementById(monthId).item(document.getElementById(monthId).selectedIndex).value;
   }
   if(document.getElementById(dayId).selectedIndex > 0)
   {
      dayBirthday   = document.getElementById(dayId).item(document.getElementById(dayId).selectedIndex).value;
   }
   if(document.getElementById(yearId).selectedIndex > 0)
   {
          yearBirthday  = document.getElementById(yearId).item(document.getElementById(yearId).selectedIndex).text;
   }
   if( (monthBirthday != "" && dayBirthday != "" && yearBirthday != "") && !isValidDate(monthBirthday,dayBirthday,yearBirthday) )
   {
       setErrorMessage(divId,errorMessage);
       return true;   
   }
   
   var today = new Date();
   var populated = "false";

   if (monthBirthday != "")
   {
      populated = "true";
   }
   if (dayBirthday != "")
   {
      populated = "true";
   }
   if (yearBirthday != "")
   {
      populated = "true";
   }
   var todayYear = today.getFullYear();
   if (((monthBirthday == "") || (dayBirthday == "") || (yearBirthday == "")) && (populated == "true"))
   {
       setErrorMessage(divId,errorMessage);
      return true;
   }
   if(yearBirthday != "")
   {
      if (((todayYear - yearBirthday)< 18) || ((todayYear - yearBirthday)> 99))
      {
         setErrorMessage(divId,errorMessage);
         return true;

      }
   }
   return false;
}


/*
 * Checks whether the attribute is mandatory or not.
 */
function isMandatory(attrId)
{
   mandatoryIndVarName = "mandatory"+ attrId;
   if (document.getElementById(mandatoryIndVarName) != null &&
            document.getElementById(mandatoryIndVarName).value != "Y")
   {
         return false;
    }
     if (document.getElementById(mandatoryIndVarName) == null )

     {
             return false;
     }
        return true;
}


function validateCSRInfo()
{
  var form = document.csrInfo;
  //var nameFilter=/^[A-Za-z]|[A-Za-z][ A-Za-z.'-]*[A-Za-z.]$/;
  var nameFilter = /^[a-zA-Z]*$/
  isError=false;
  removeErrorMessages()
  if (document.getElementById("importantMessageDiv") != null)
  {
        document.getElementById("importantMessageDiv").style.display="none";
  }

  for(var j = 0; j < form.elements.length; j++)
  {

    var index = form.elements[j].name.indexOf("_")
    var divId = form.elements[j].name.substring(0,index) + "Error"
    var errorMessage = form.elements[j].name.substring(0,index) + " is Required"

    if(form.elements[j].name.substring(0,index) =="csrName")
    {


   if (checkMandatoryValue(form.elements[j].id, divId, "CSR Name is required"))
   {
      isError = true

   }
   /*else if( !nameFilter.test(form.elements[j].value))
        {

         setErrorMessage(divId,"Please enter a valid CSR Name");
         isError = true;
        }*/
    }
    else if (form.elements[j].name.substring(0,index) =="requestedBy")
    {
        if (checkMandatoryValue(form.elements[j].id, divId, "Requested By is required"))
   {
      isError = true
   }
    }

    else if (form.elements[j].name.substring(0,index) =="reasonCode")
    {
        if (checkMandatoryValue(form.elements[j].id, divId, "Reason Code is required"))
   {
      isError = true
   }

    }
  }
  if (isError)
  {
      window.scroll(0,0);
     if (document.getElementById("importantMessageDiv") != null)
      {
         document.getElementById("importantMessageDiv").style.display="block";
      }
      
  }

  return !isError;
}

function removeErrorMessages()
{
   var form = document.csrInfo;

   for(var j = 0; j < form.elements.length; j++)
   {

       var index = form.elements[j].name.indexOf("_")
       var divId = form.elements[j].name.substring(0,index) + "Error"

       removeErrorMessage(divId)
   }

}


/*
 *This function checks if the atleast one option from the radio button is selected.
 *
 */
function checkRadioButtons(radioObj){
   var flag=false;
   for(i=0;i<radioObj.length;i++){
      if(radioObj[i].checked){
         flag=true;
         break;
      }
   }
   return flag;
}

/*
* This function is used to trim the given values
*/
function Trim(TRIM_VALUE)
{
   if(TRIM_VALUE.length < 1){
      return"";
    }
    TRIM_VALUE = RTrim(TRIM_VALUE);
    TRIM_VALUE = LTrim(TRIM_VALUE);
      if(TRIM_VALUE=="")
      {
         return "";
    }
      else
      {
      return TRIM_VALUE;
   }
}

/*
* This function is used to right-trim the given values
*/

function RTrim(VALUE){
   var w_space = String.fromCharCode(32);
   var v_length = VALUE.length;
   var strTemp = "";
   if(v_length < 0)
   {
      return"";
    }
   var iTemp = v_length -1;
      while(iTemp > -1)
      {
      if(VALUE.charAt(iTemp) == w_space)
      {  }
         else
         {
         strTemp = VALUE.substring(0,iTemp +1);
         break;
      }
      iTemp = iTemp-1;
   }
   return strTemp;
   }

/*
* This function is used to left-trim the given values
*/
function LTrim(VALUE)
{
   var w_space = String.fromCharCode(32);
   if(v_length < 1)
   {
   return"";
   }
   var v_length = VALUE.length;
   var strTemp = "";
   var iTemp = 0;
   while(iTemp < v_length)
   {
      if(VALUE.charAt(iTemp) == w_space)
      {}
      else
      {
         strTemp = VALUE.substring(iTemp,v_length);
         break;
      }
      iTemp = iTemp + 1;
    }
return strTemp;
}

/*
* This function is used to validate entries in the changeUserName page
*/
function validateChangeUserNamePage()
{
   var emailFilter=/^[a-zA-Z0-9][a-zA-Z0-9_.]*[@][a-zA-Z0-9]+[.][a-zA-Z]+$/;
   removeErrorMessage("emailiderror");
   var isError = false;
   var form = document.pdr;
   var emailFromRadioBox = "";
       for(var i = 0; i < form.length; i++)
         {
           if(form.elements[i].type == "radio")
           {
              if(form.elements[i].checked)
              {
                 emailFromRadioBox = form.elements[i].value;
              }
           }
   }
   var originalEmail = document.getElementById("54_0_0_1_index_0").value;
   var otherEmail = document.getElementById("ReEnterUserName_index_0").value;
   
   originalEmail = trim(originalEmail.toLowerCase());
   otherEmail = trim(otherEmail.toLowerCase());
   
   if ((originalEmail != "") || (otherEmail != ""))
   {
      if ( !(validateEmailId(Trim(originalEmail)) ) )
      {
               setErrorMessage("emailiderror","Please supply a valid email address.");
               isError = true;
      }
      else if(originalEmail != otherEmail)
      {
               setErrorMessage("emailiderror","Please verify if the emails entered are same.");
               isError = true;
      }
   }
   

   if ( (originalEmail == "") && (otherEmail == "") && (emailFromRadioBox == "") )
   {
         setErrorMessage("emailiderror","Please supply an email address.");
         isError = true;
   }
   
   return (!isError);
}

/*
 *This function is used to check the selected applications during CSR Deactivate. 
 *
 */

function getSelectedCheckBox(buttonGroup)
{
   removeErrorMessage("AppIdsError");
   // Go through all the check boxes. return an array of all the ones
   // that are selected (their position numbers). if no boxes were checked,
   // returned array will be empty (length will be zero)
   var isError = false;
   var lastElement = 0;
   if (buttonGroup[0]) { // if the button group is an array (one check box is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) 
         {
            isError = true;  
         }
      }
   } else { // There is only one check box (it's not an array)
      if (buttonGroup.checked) { // if the one check box is checked
         isError = true;
      }
   }
   
   if (!isError)
   {
      setErrorMessage("AppIdsError","Please select atleast one application to deactivate.");
   }
   return isError;
   
}


   
/*
 *This function is used to set the resident End date.
 *
 */

function checkResidentEndDateForDE()
{

   var monthResidentEndDay = document.DEThomletPage.resEndMonth.value;
   var yearResidentEndDay  = document.DEThomletPage.resEndYear.value;
   var populated = "false";
   var monthResidentStartDay = document.DEThomletPage.resStartMonth.value;
   var yearResidentStartDay  = document.DEThomletPage.resStartYear.value;
   if (monthResidentEndDay != "")
   {
      populated = "true";
   }
   if (yearResidentEndDay != "")
   {
      populated = "true";
   }
   if (((monthResidentEndDay == "") || (yearResidentEndDay == "")) && (populated == "true"))
   {
      return true;
   }
   if (populated == "true" && ((monthResidentStartDay != "") && (yearResidentStartDay != "")))
   {
      if ((yearResidentStartDay - yearResidentEndDay) > 0)
      {
         return true;
      }
      else if ((yearResidentStartDay - yearResidentEndDay) == 0)
      {
         if ((monthResidentStartDay - monthResidentEndDay) > 0)
         {
            return true;
         }
         return false;
      }
      return false;
   }

   return false;
}

function checkResidentStartDateForDE()
{

   var monthResidentStartDay = document.DEThomletPage.resStartMonth.value;
   var yearResidentStartDay  = document.DEThomletPage.resStartYear.value;
    var populated = "false";
   if (monthResidentStartDay != "")
   {
      populated = "true";
   }
   if (yearResidentStartDay != "")
   {
      populated = "true";
   }
   if (((monthResidentStartDay == "") || (yearResidentStartDay == "")) && (populated == "true"))
   {
      return true;
   }
   return false;
}

function setResidentStartYear(value)
{
   document.DEThomletPage.resStartYear.value = value;
}
function setResidentStartMonth(value)
{
   document.DEThomletPage.resStartMonth.value = value;
}
function setResidentEndYear(value)
{
   document.DEThomletPage.resEndYear.value = value;
}
function setResidentEndMonth(value)
{
   document.DEThomletPage.resEndMonth.value = value;
}
function setHospital(value, divId)
{
   document.getElementById(divId).value = value;
}
function resetHospital(divId)
{
   document.getElementById(divId).value = "";
}
//function to remove leading and trainling withespace 
function trimString (str) {
   return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}


/* Variable to indicate a submit in License Page */
var licenseIndicator = false;

/**
 * This function is to disable the controls "I accept" and "I decline" after the user doing either one among them.
 */

function toggleLicensePage()
{
   
   if ( licenseIndicator == false )
   {
      licenseIndicator = true;
      return true;
   }
   return false;
}

/**
 * This function is used to disable all the submit buttons after the user performing a submit once.
 */
 
function disableSubmitButtons(theform)
{
   var submitButtonCounter = 0;
   
   if (document.all || document.getElementById) 
   {
      for (var i = 0; i < theform.length; i++) 
      {
         if(theform.elements[i].type.toLowerCase() == "submit")
         {
            submitButtonCounter++;
         }
      }
   }
   
   if (submitButtonCounter > 1)
   {
      for (var i = 0; i < theform.length; i++) 
      {
         if(theform.elements[i].type.toLowerCase() == "submit")
         {
            theform.elements[i].disabled = true;
         }
      }
   }
   return true;
}

/**
 * This general function is called from the dynamic pages which loops through all the form
 * fields and get the attribute ids from the form field ids and does the specific validation
 * for that attribute.
 */
function validateUserName()
{

   if (document.getElementById("importantMessageDiv") != null)
   {
         document.getElementById("importantMessageDiv").style.display="none";
   }
   var form = document.emailchange;

   var attrId;

   isError=false;
   if(!skipValidation)
   {
      for(var i = 0; i < form.length; i++)
      {
         attrId = findAttributeCode(form.elements[i].id);


         if(attrId=="54")
         {
         checkEmailField(form.elements[i].id,"error"+form.elements[i].id);
         if(document.getElementById("confirmEmail") != null)
          {
            checkConfirmEmail(form.elements[i].id,"confirmEmail","error"+form.elements[i].id,"confirmemailerror");
          }
         }
 
      }//end of for loop
   }//end of skipvalidation
   if (isError)
   {
      window.scroll(0,0);
      if (document.getElementById("importantMessageDiv") != null)
      {
         document.getElementById("importantMessageDiv").style.display="block";
      }
      
   }
   skipValidation = false;
   return !isError;
} //end of validate attributes function

