function switchHintState(hintId, hintSectionId) {
      var get = new htmldb_Get(
        null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=SWITCH_HINT_STATE',0);
      get.add('TF_HINT_FAQ_ID', hintId);
      get.add('TF_HINT_SECTION_ID', hintSectionId);
      var section = get.get();
}

function hideOrShowHint(hintId, hintSectionId) {
   hideOrShowElement("hint" + hintId);
   switchHintState(hintId, hintSectionId);
}

function showSurveyCriteriaDiv(event, element, divName) {
   document.getElementById('wholePage').style.display = "inline";
   showMenu(event, element, '', 0, 0, '', divName, 500);
}

function hideSurveyCriteriaDiv(divName) {
  hideRegion(divName);
  document.getElementById('wholePage').style.display = "none";
}

function hideOrShowElement(elementName) {
    var region = document.getElementById(elementName);
    if (region) { 
       if (region.style.display == 'none') {
          region.style.display = "";
       }
       else {
          region.style.display = "none";
       }
    }
} 

function hideRegion(regionName) {
    var region = document.getElementById(regionName);
    if (region) { region.style.display = 'none'; }
}

function updateSurvey(divName) {
    var recordId = document.getElementById('P0_SURVEY_RECORD_ID').value;
    var surveyId = document.getElementById('P0_SURVEY_MED_LIST_ID').value;
    var isSample = recordId == -1;
    hideRegion(divName);
    setIdAndRedirect(surveyId, isSample);
}

function changeSurveyRecord(requestName, confMsg) {
   if (confirm(confMsg))    {
      doSubmit(requestName);
   }
   else {
      doSubmit('RESET_SURVEY_RECORD');
   }
}

function takeSurveyEditAction(surveyId, optionValue) {
    closeCurrent('genericPopup');
    var list = document.getElementById('P0_SURVEY_EDIT_MENU');   
    if (list) {
      for (i = 0; i < list.options.length; i++) {
        if (list.options[i].selected) {
          optionValue = list.options[i].value;
          break;
        }
      }
    }
    
    
    if (optionValue == "SAVE") {
       if (surveyId) {
          doSubmit("SAVE_SURVEY");
       }
       else {
          enableSaveAsDiv();
       }
    } 
    else if (optionValue == "SAVE_NEW_PATIENT") {
         enableImportDiv('importNewPatientDiv');
         var defaultField = document.getElementById('P0_RECORD_NAME');
         defaultField.focus();
    }

    else if (optionValue == "COPY_PATIENT") {
         enableImportDiv('copyPatientDiv');
         var defaultField = document.getElementById('P0_RECORD_NAME2');
         defaultField.focus();
    }

    else if (optionValue == "SAVE_NEW_REFERENCE") {
         enableImportDiv('importNewReferenceDiv');
         var defaultField = document.getElementById('P0_REFERENCE_NAME');
         defaultField.focus();

    }
    else if (optionValue == "START_NEW") {
       removeAll("Changes to the meds list you have been working on have not been saved and will be discarded. Do you want to continue? Click Cancel if you'd like to return to your current meds list and save it first.");
    }
    else if (optionValue == "MERGE_INTO_PATIENT") {
         enableImportDiv('importPatientDiv');
    }
    else if (optionValue == "MERGE_INTO_REFERENCE") {
         enableImportDiv('importReferenceDiv');
    }
}

function enableImportDiv(divName) {
   var div = document.getElementById(divName);
   if (div) {
       div.style.display = "inline";
       document.getElementById('wholePage').style.display = "inline";
   }
}


function saveSurvey() {
   var description = document.getElementById('P0_SURVEY_DESCRIPTION');
   if (description == null || description.value == null ||description.value == "") {
      alert("Please Give Your List a Description");
      description.focus();
   }
   else {
      doSubmit("SAVE_SURVEY");
   }
}

function cancelSave() {
   document.getElementById('wholePage').style.display = "none";
   document.getElementById("saveSurveyAs").style.display = "none";
   document.getElementById("importPatientDiv").style.display = "none";
   document.getElementById("importReferenceDiv").style.display = "none";
   document.getElementById("importNewPatientDiv").style.display = "none";
   document.getElementById("importNewReferenceDiv").style.display = "none";

   var list = document.getElementById('P0_SURVEY_EDIT_MENU');
   if(list) {
       list.options[0].selected = true;
   }
   document.getElementById('P0_RECORD_NAME').value = '';
   document.getElementById('P0_SEX_0').checked = true;
   document.getElementById('P0_SEX_1').checked = false;
   document.getElementById('P0_BIRTHYEAR').value = '';
   document.getElementById('P0_REAL_FLAG_0').checked = false;
   document.getElementById('P0_REFERENCE_ID').value = -1;
   document.getElementById('P0_REFERENCE_NAME').value = '';
   document.getElementById('P0_MED_LIST_NAME').value = '';

}

function enableSaveAsDiv() {
   var div = document.getElementById("saveSurveyAs");
   if (div) {
       div.style.display = "inline";
       document.getElementById('wholePage').style.display = "inline";
   }

}

function sideEffectSeverityToolTip(event, element, severity) {
   var message;
   if (severity == "Major") {
      message = "<b>Major</b><br/> - May be life threatening.";
   }
   else if (severity == "Minor") {
       message = "<b>Minor</b><br/> - Not life threatening.";
   }
   var region = document.getElementById('genericPopupTitle');
   region.innerHTML = message;

   showMenu(event, element, '', 0, 15, '',  'genericPopup');
}

function medlistObjectExistsToolTip(event, element, objectType) {
   var message;
   if (objectType == "Condition") {
      message = "This condition already exists<br/>in the Patient Med Cabinet.";
   }
   else if (objectType == "Med") {
       message = "This medication already exists<br/>in the Medlist / Patient Med Cabinet.";
   }
   var region = document.getElementById('genericPopupTitle');
   region.innerHTML = message;

   showMenu(event, element, '', 0, 15, '',  'genericPopup');
}

function contraindicationSeverityToolTip(event, element, severity) {
   var message;
   if (severity == "Absolute Contraindications") {
      message = "<b>Absolute Contraindication - Most significant contraindication warning</b>.  <br/>Indicates that the drug should never be given to patients with <br/>one of the listed conditions because harm is likely to occur.";
   }
   else if (severity == "Relative Contraindications") {
       message = "<b>Relative Contraindication - Clinically significant contraindication warning</b>.  <br/>Indicates that the listed conditions can be managed/treated <br/>before the drug may be given safely.";
   }
   else if (severity == "Contraindication Warnings") {
      message = "<b>Contraindication Warning - Least significant contraindication warning</b>.  <br/>Indicates that adequate monitoring of patients with the <br/>listed conditions may make it safer for the drug's use.";
   }
   var region = document.getElementById('genericPopupTitle');
   region.innerHTML = message;

   showMenu(event, element, '', 0, 15, '',  'genericPopup');
}

function pregnancyPrecautionSeverityToolTip(event, element, severity, routedDrug, narrative) {
   var message;
   if (severity == "FDA-A") {
      message = "<b>" + routedDrug + "<br/><br/>Pregnancy Precaution Comments<br/></b>" + narrative + "<br/><br/><b>FDA pregnancy risk category A <br/> - Evidence of no risk</b> </br>Adequate & well-controlled studies in pregnant woen have failed to demonstrate a risk to the fetus in 1st trimester of pregnancy (and no evidence of risk in later trimesters).";
   }
   else if (severity == "FDA-B") {
       message =  "<b>" + routedDrug + "<br/><br/>Pregnancy Precaution Comments<br/></b>" + narrative + "<br/><br/><b>FDA pregnancy risk category B</b></br>Animal studies have failed to demonstrate a risk to the fetus but there are no well-controlled studies in pregnant women; or animal reproduction studies have shown an adverse effect (other than decrease in fertility), but adequate and well-controlled studies in pregnant women have failed to demonstate a risk to the fetus during the first trimester of pregnancy (and there is no evidence of a risk in later trimesters.";
   }
   else if (severity == "FDA-C") {
      message =  "<b>" + routedDrug + "<br/><br/>Pregnancy Precaution Comments<br/></b>" + narrative + "<br/><br/><b>FDA pregnancy risk category C</b></br>Animal studies have shown adverse effect on fetus but no well-controlled studies in humans; potential benefits may warrant use in pregnant women despite potential risks; or no animal reproduction studies and no adequate and well-controlled studies in humans.";
   }
   else if (severity == "FDA-D") {
       message =  "<b>" + routedDrug + "<br/><br/>Pregnancy Precaution Comments<br/></b>" + narrative + "<br/><br/><b>FDA pregnancy risk category D</b></br>Positive evidence of human fetal risk based on investigation or marketing information but potential benefits may warrant use of drug in pregnant women despite potential risks.";
   }
   else if (severity == "FDA-X") {
       message =  "<b>" + routedDrug + "<br/><br/>Pregnancy Precaution Comments<br/></b>" + narrative + "<br/><br/><b>FDA pregnancy risk category X</b></br>Studies in animals or humans have shown fetal abnormalities and/or there is positive evidence of fetal risk based on investigational or marketing information and risks involved in use of drug in pregnant women clearly outweigh potential benefits.";
   }
   else if (severity == "FDB-1") {
       message =  "<b>" + routedDrug + "<br/><br/>Pregnancy Precaution Comments<br/></b>" + narrative + "<br/><br/><b>FDB severity 1</b></br>No fda rating but is contraindicated or not recommended; may have animal and/or human studies or pre or postmarketing information. this is an fdb-assigned value.";
   }
   else if (severity == "FDB-2") {
       message =  "<b>" + routedDrug + "<br/><br/>Pregnancy Precaution Comments<br/></b>" + narrative + "<br/><br/><b>FDB severity 2</b></br>No fda rating but has precautions or warnings; may have animal and/or human studies or pre or post marketing information. this is an fdb-assigned value.";
   }
   var region = document.getElementById('genericPopupTitle');
   region.innerHTML = message;

   showMenu(event, element, '', 0, 15, '', 'genericPopup', 225);
}

function generalPrecautionSeverityToolTip(event, element, precautionType, severity, routedDrug, narrative) {
   var message;
   if (narrative != "") {
      message = "<b>" + routedDrug + "<br/><br/>" + precautionType + " Comments<br/></b>" + narrative;
   
   var region = document.getElementById('genericPopupTitle');
   region.innerHTML = message;

   showMenu(event, element, '', 0, 15, '', 'genericPopup', 225);
   }
}

function interactionSeverityToolTip(event, element, severity) {
   var message;
   if (severity == "Severe") {
      message = "<b>Severe Severity Interaction</b><br/> - These medicines are contraindicated and not usually taken together.";
   }
   else if (severity == "Serious") {
       message = "<b>Serious Severity Interaction</b><br/> - These medicines may interact and cause very harmful effects.";
   }
   else if (severity == "Moderate") {
      message = "<b>Moderate Severity Interaction</b><br/> - These medicines may cause some risk when taken together.";
   }
   else if (severity == "Unknown") {
      message = "<b>Unknown Severity Interaction</b><br/> - These medicines may cause some risk when taken together.";
   }
   var region = document.getElementById('genericPopupTitle');
   region.innerHTML = message;

   showMenu(event, element, '', 0, 15, '',  'genericPopup');
}



  function removeTip(event, element, name) {
    toolTip_enable(event,element,'<b> Remove ' + 
                   name + ' from the risk maps</b>');
  }

  function  infoTip(event, element, name) {
    toolTip_enable(event,element,'<b> Click to View <br/>' +
                   name + 
                   '<br/>Med Info Sheet</b>');
  }

  function graphInfoTip(event, element, medName, ade) {
    toolTip_enable(event,element,'<b> ' +
                   medName + ' - </br> ' +
	           ade + ' </b>');
  }

function getScrollWidth()
{

  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
           
   return myWidth;
} 


function XDSOC() {
    var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;

    return document.all? iebody.scrollLeft : pageXOffset;
}

function toolTip_enable(evt,obj,tip, width, color){
    evt=(evt)?evt:((window.event)?event:null);
    var target_x=evt.pageX?evt.pageX:evt.clientX+getScrollXY()[0];
    var target_y=evt.pageY?evt.pageY:evt.clientY+getScrollXY()[1];
    if(toolTip_init()){
    tt_target = obj;
    if(!tip){tip = obj.getAttribute("htmldb:tip");}
    var iframe =  '<!--[if lte IE 6.5]><iframe class="hideSelect"></iframe><![endif]-->';
    if(gToolTipContent){gToolTipContent.innerHTML=tip+iframe;}else{gToolTip.innerHTML=tip+iframe;}
    if(!!width){gToolTip.style.width=width+"px";}
    if(!!color){gToolTip.style.backgroundColor=color;}else{gToolTip.style.backgroundColor="lightyellow";}
    gToopTipPointer.style.left = ( 10 + target_x ) +"px";
    gToopTipPointer.style.top  = (15 + target_y ) +"px";
    gToolTip.style.top  = ( 28 + target_y ) +"px";
    gToolTip.style.left = ( 7 + target_x ) +"px";

    gToolTip.style.visibility="visible";
    gToolTip.style.zIndex=10000;
    gToopTipPointer.style.zIndex=10001;
    gToopTipPointer.style.visibility="visible";

    if ((gToolTip.scrollWidth + 7 + target_x) > (getScrollWidth() + XDSOC())) {
       var rightMarginOffset = document.all? 5 : 20;

       var new_left = (getScrollWidth() +XDSOC() - gToolTip.scrollWidth - rightMarginOffset);
       gToopTipPointer.style.left = (target_x) + "px";
       if (target_x + gToopTipPointer.scrollWidth > new_left + gToolTip.scrollWidth) {
         gToopTipPointer.style.left = (getScrollWidth() + XDSOC() - gToopTipPointer.scrollWidth - rightMarginOffset) + "px";  
       }
       gToolTip.style.left = new_left + "px";
    }

    try {obj.addEventListener("mouseout",toolTip_disable, false);}
        catch(e){obj.attachEvent('onmouseout',toolTip_disable);}
   }

    return false;
}
 

function stopDingOnEnter(fieldName) {
   if (document.all) {
       document.getElementById(fieldName).onkeypress = function () {return stopRKey(event);};
   } else {
       document.getElementById(fieldName).onkeypress = function (e) {return stopRKey(e);};
   }
}

function nothing() { return; };

function runAbbySurvey(isAbbySurvey) {
   if (isAbbySurvey == 'TRUE') {
     var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=generateNewAbbySurvey',0
     );
     gReturn = get.GetAsync(nothing);
   }

}
function checkIfSurveyIsDone(buttonName) {
   var get = new htmldb_Get(
     null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=checkIfSurveyIsDone',0
   );

   gReturn = get.get();
   if (gReturn != "0") {
      var x=document.getElementById(buttonName);
      x.disabled = false;
   }
   else {
      setTimeout("checkIfSurveyIsDone('" + buttonName + "')", 1000);
   }
}

 var v_oldValues = new Array();
 var v_selectListContainers = new Array();

 var v_appItemTable   = new Array();
 var v_appItemColumn  = new Array();
 var v_matchcolor     = new Array();
 var v_nomatchcolor   = new Array();

 var v_enterFunctions = new Array();
 var c_SelectListSize = 8;
 
function register(p_TextFieldName, p_TableName, p_ColumnName, p_matchColor, p_noMatchColor, p_enterFunction) {
   v_oldValues[p_TextFieldName] = html_GetElement(p_TextFieldName).value;

   v_selectListContainers[p_TextFieldName] = document.createElement("div");
   v_selectListContainers[p_TextFieldName].setAttribute("id", "_"+p_TextFieldName+"_CONTAINER");
   v_selectListContainers[p_TextFieldName].style.zIndex = 1000;

   v_selectListContainers[p_TextFieldName].style.position = "relative";
   v_selectListContainers[p_TextFieldName].style.left = "0px";
   v_selectListContainers[p_TextFieldName].style.top = "0px";

   html_GetElement(p_TextFieldName).parentNode.appendChild(v_selectListContainers[p_TextFieldName]);
// move the text field into the new div
   v_selectListContainers[p_TextFieldName].appendChild(html_GetElement(p_TextFieldName));	

   if (document.all) {
     html_GetElement(p_TextFieldName).onkeyup = function () {return showSelectList(event);};
     html_GetElement(p_TextFieldName).onkeypress = function () {return stopRKey(event);};

   } else {
     html_GetElement(p_TextFieldName).onkeyup = function (e) {return showSelectList(e);};
     html_GetElement(p_TextFieldName).onkeypress = function (e) {return stopRKey(e);};
  }
   
   v_appItemTable[p_TextFieldName] = p_TableName;
   v_appItemColumn[p_TextFieldName] = p_ColumnName;
   v_matchcolor[p_TextFieldName] = p_matchColor;
   v_nomatchcolor[p_TextFieldName] = p_noMatchColor;
   v_enterFunctions[p_TextFieldName] = p_enterFunction;
 }

function stopRKey(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
  if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
} 

var keywaspressed = false;
function showSelectList(e) {
   var isFirefox35 = navigator.userAgent.indexOf('Firefox/3.5') != -1; 
   if (isFirefox35) {
      keywaspressed = true;
      setTimeout(function() {showSelectListNow(e)}, 700);
      setTimeout(function() {unsetPress()}, 300);
   }
   else {
      keywaspressed = false;
      showSelectListNow(e);
   }
}

function unsetPress() {
   keywaspressed = false;
}

 function showSelectListNow(e) {
   if (keywaspressed) { return; }
   var keynum;
   var p_TextFieldName;
   if(document.all)  {
     keynum = e.keyCode;
     p_TextFieldName = e.srcElement.getAttribute("id");
   } else {
     keynum = e.which;
     p_TextFieldName = e.target.getAttribute("id");
   }

   if (v_oldValues[p_TextFieldName] != html_GetElement(p_TextFieldName).value) {
     v_oldValues[p_TextFieldName] = html_GetElement(p_TextFieldName).value;
     if (html_GetElement(p_TextFieldName).value != "") {
       do_showSelectList(p_TextFieldName);
     } else {
       removeSelectList(p_TextFieldName);
     }
   } else {
     if (keynum == 40 || keynum == 38 || keynum == 9) {
       if (!e.shiftKey) {
         if (html_GetElement("_"+p_TextFieldName+"SELECTLIST")) {
           html_GetElement("_"+p_TextFieldName+"SELECTLIST").focus();vedSurveysForRecord
         }
       }
     } 
     if (keynum == 13) {
       do_pushBackValue(p_TextFieldName);
     }
   }
   return false;
 }

 function recordDoesNotExist(recordName, recordType) {
    return objectDoesNotExist(recordName, "recordDoesNotExist", recordType);
 }

 function medlistDoesNotExist(listName, recordId) {
    return objectDoesNotExist(listName, "medlistDoesNotExist", recordId);
 }

 function objectDoesNotExist(name, proccessName, extraParam) {
   var get = new htmldb_Get(
      null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS='+proccessName,0);
   get.add('TF_NAME', name);

   if (proccessName == "medlistDoesNotExist") {
      get.add('TF_RECORD_ID', extraParam);
   }
   else if (proccessName == "recordDoesNotExist") {
      get.add('TF_RECORD_TYPE', extraParam);
   }

   gReturn = get.get('');
   
   return gReturn==1;
 }

 function getSavedSurveysForRecord(recordId, updateFieldName) {
    var fieldToUpdate = document.getElementById(updateFieldName);
    fieldToUpdate.innerHTML = "";
    var gReturn = null;
    if (recordId != -1) { 

       var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=getSavedSurveysForRecord',0);
       get.add('TF_SURVEY_RECORD_ID', recordId);
       gReturn = get.get('XML');
    }
    else {
       var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=getSampleSurveys',0);
       gReturn = get.get('XML');
    }

    var newOptions = gReturn.getElementsByTagName("option");
    for (i = 0; i < newOptions.length; i++) {
       var id = newOptions[i].firstChild.firstChild.nodeValue;
       var value = newOptions[i].lastChild.firstChild.nodeValue;
       appendToSelect(fieldToUpdate, id, value);
    }

}

 function do_showSelectList(p_TextFieldName) { 
   var l_Return = null;
   var l_SelectList = html_GetElement("_"+p_TextFieldName+"SELECTLIST");
   if (!l_SelectList) {
     l_SelectList = createSelectList(p_TextFieldName);
   } else {
     l_SelectList.disabled = false;
     l_SelectList.style.visibility="visible";
   }

   var isFirefox3 = navigator.userAgent.indexOf('Firefox/3.0') != -1; 
   do {
     var valueUsed = html_GetElement(p_TextFieldName).value; 
     var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=getSearchList',0
     );
     get.add('TF_SL_SEARCH', valueUsed);
     get.add('TF_SL_TABLE', v_appItemTable[p_TextFieldName]);
     get.add('TF_SL_COLUMN', v_appItemColumn[p_TextFieldName]);
     gReturn = get.get('XML');
   } while (isFirefox3 && valueUsed != html_GetElement(p_TextFieldName).value)

   if(gReturn && l_SelectList){
     var l_Count = gReturn.getElementsByTagName("row").length;
     l_SelectList.length = 0;
     if (l_Count > 0) {
       if (l_Count < c_SelectListSize) {
         l_SelectList.size = l_Count;
       } else {
         l_SelectList.size = c_SelectListSize;
       }
       for(var i=0;i<l_Count;i++){
         var l_ReturnedItem = gReturn.getElementsByTagName("row")[i];
          appendToSelect(l_SelectList, l_ReturnedItem.firstChild.nodeValue, l_ReturnedItem.firstChild.nodeValue);
       }
       setFieldColor(p_TextFieldName, v_matchcolor[p_TextFieldName]);
       l_SelectList.options[0].selected=true;

     } else if (l_Count == 0) {
       removeSelectList(p_TextFieldName);
       setFieldColor(p_TextFieldName, v_nomatchcolor[p_TextFieldName]);
     } 
   }
 }

 function setFieldColor(pField, pColor) {
   html_GetElement(pField).style.color = pColor;
 }

 function createSelectList(p_TextFieldName) {
   var v_SelectList = document.createElement("select");
   v_SelectList.setAttribute("id", "_" + p_TextFieldName + "SELECTLIST");
   v_SelectList.style.position = "absolute";
   v_SelectList.style.display = "block";
   v_SelectList.style.width = "100%";
   v_SelectList.style.left = "0px";
   v_SelectList.style.top = "20px";
   v_SelectList.size = c_SelectListSize;
   if (document.all) {
     v_SelectList.onclick = function () {return pushBackValue(event);};
     v_SelectList.onkeyup = function () {return pushBackValueReturn(event);};
     v_SelectList.onkeypress = function () {return pushBackValueReturn(event);};
   } else {
     v_SelectList.onclick = function (e) {return pushBackValueReturn(e);};
     v_SelectList.onkeyup = function (e) {return pushBackValueReturn(e);};
     v_SelectList.onkeypress = function (e) {return pushBackValueReturn(e);};
  }

   v_selectListContainers[p_TextFieldName].appendChild(v_SelectList);

   return v_SelectList;
 }


 function removeSelectList(p_TextFieldName) {
   var v_SelectList = html_GetElement("_" + p_TextFieldName + "SELECTLIST");
   v_SelectList.style.visibility="hidden";
   html_GetElement(p_TextFieldName).focus();
   v_SelectList.disabled = true;

 }
  
 function do_pushBackValue(p_TextFieldName) {

   var v_SelectList = html_GetElement("_" + p_TextFieldName + "SELECTLIST");
   if (v_SelectList && v_SelectList.style.visibility!="hidden") {
       html_GetElement(p_TextFieldName).value = html_GetElement("_" + p_TextFieldName + "SELECTLIST").value;

       v_oldValues[p_TextFieldName] = html_GetElement(p_TextFieldName).value;

       setFieldColor(p_TextFieldName, v_matchcolor[p_TextFieldName]);
       removeSelectList(p_TextFieldName);
       html_GetElement(p_TextFieldName).focus();
   }
   else {
       var enterFunction = v_enterFunctions[p_TextFieldName];
       if (enterFunction) {
          enterFunction();
       }
   }
 }

 function pushBackValue(e) {
   var p_TextFieldName;
   if(document.all)  {
     p_TextFieldName = e.srcElement.getAttribute("id");
   } else {
     p_TextFieldName = e.target.parentNode.getAttribute("id");
   }
   if (p_TextFieldName) {
     if (p_TextFieldName.lastIndexOf("_CONTAINER") == p_TextFieldName.length - "_CONTAINER".length) {
         do_pushBackValue(p_TextFieldName.substring(1, p_TextFieldName.indexOf("_CONTAINER")));
     }
     else {
         do_pushBackValue(p_TextFieldName.substring(1, p_TextFieldName.indexOf("SELECTLIST")));
     }
   }
 }

 function pushBackValueReturn(e) {
   var keynum;
   var p_TextFieldName;
   if(document.all)  {
     keynum = e.keyCode;
     p_TextFieldName = e.srcElement.getAttribute("id");
   } else {
     keynum = e.which;
     p_TextFieldName = e.target.getAttribute("id");
     if (p_TextFieldName == null) {
         p_TextFieldName = e.target.parentNode.getAttribute("id");
     }
   }

   if (keynum == 13 || keynum == 1 ) {
     do_pushBackValue(p_TextFieldName.substring(1, p_TextFieldName.indexOf("SELECTLIST")));
   }
 }


 function appendToSelect(pSelect, pValue, pContent) {
   var l_Item = document.createElement("option");
   l_Item.value = pValue;
   if(document.all){
     pSelect.options.add(l_Item);
     l_Item.innerText = pContent;
   } else {
     l_Item.appendChild(document.createTextNode(pContent));
     pSelect.appendChild(l_Item);
   }
 }
 
// Simple function that sets an apex application item with a new value 
// on the server
function setItem(pItem,pValue,appId,sessionId){
		var get = new htmldb_Get(null,appId,'APPLICATION_PROCESS=returnNothing',0,sessionId);
		get.add(pItem,pValue);
		gReturn = get.get();
}

// Simple function that gets an apex application item's value from the server
function getItem(pItem,appId,sessionId){
		var get = new htmldb_Get(null,appId,'APPLICATION_PROCESS=returnItem',0,sessionId);
		get.add('RETURNITEM',pItem);
		gReturn = get.get();
		return gReturn;
}

// Checks to see if the app item AI_PAGE_REQUESTED is currently set
// to "NO". If it is NO then the user has most likely hit the back 
// button and the page needs to be refreshed to insure it is in a 
// proper state. If the value is not NO then set it to "NO" to 
// insure that what ever page is visit next can be properly tested            
function needRefresh(appId, sessionId) {
  var requested = getItem('AI_PAGE_REQUESTED', appId, sessionId);
  if (requested == "NO") {
      window.location = window.location;
  }
  else {
      setItem('AI_PAGE_REQUESTED', "NO",appId, sessionId);
  }
}

function convertToInteractions() {
 var x=document.getElementById("innerSurveyTable");
 var tableBody = x.tBodies[0];
 for (var i = 1; i < tableBody.rows.length; i++) {
    var row = tableBody.rows[i];
    var firstColumnToConvert;
    for (var j = 0; j < row.cells.length; j++) {
      firstColumnToConvert = j;
      var element = row.cells[j].firstChild;
      if (element.className == 'riskValue') {
         break;
      }
    }
    convertInteraction(row.cells[firstColumnToConvert], 'riskCurrent');
    for (var j = firstColumnToConvert+1; j < row.cells.length; j++) {
      convertInteraction(row.cells[j], 'riskDrugCurrent');
    }
 }
}

function convertInteraction(cell, className) {
   var value = cell.firstChild.innerHTML;
   var result = '<div class="' + className + '">';
   if (value == 1) {
     result += '<div class="interactionIcon"> &nbsp </div>';
   }
   else {
     result += "&nbsp;"
   }
   result += '</div>';
   cell.innerHTML = result;
}


function moveSearchBox() {
    var riskTab=document.getElementById("risk_tab");    
    var newPlace=document.getElementById("shSurveySubtitlePart1");
    newPlace.innerHTML = riskTab.innerHTML;
    newPlace=document.getElementById("shSurveySubtitlePart2"); 
    var searchField=document.getElementById("search_field");    
    newPlace.innerHTML = searchField.innerHTML;
    // remove the old searchField so that two fields with the same
    // name are not submitted
    searchField.innerHTML = '';
}

function showSearchBox() {
    var riskTab=document.getElementById("risk_tab");    
    var searchField=document.getElementById("search_field");    
    riskTab.style.display = "inline";
    searchField.style.display = "inline";

}

function moveNumRowsToDisplayToTable(div, rowsToDisplayName, maxRowsWithoutSearch, rowCount) {
     moveNumRowsToDisplayToTableBool(div, rowsToDisplayName, rowCount > maxRowsWithoutSearch);
}

function moveNumRowsToDisplayToTableBool(div, rowsToDisplayName, showSelect) {
     if (div) {
        var numRowSelectRegion = document.getElementById(rowsToDisplayName);
        var table = div.getElementsByTagName('table')[0];
        var tableBody = table.tBodies[0];
        var lastRow = tableBody.rows[tableBody.rows.length - 1];
        if (!showSelect) {
            lastRow.style.display = "none";
        }
        else {
           var cell = lastRow.cells[0];
           cell.innerHTML = "<table cellpadding='0' cellspacing='0' width='100%'><tr><td align='left'>" + numRowSelectRegion.innerHTML + "</td><td align='right'>" + cell.innerHTML + "</td></tr></table>";
           numRowSelectRegion.innerHTML = "";
        }
     }
}


function addSortArrowsToMedListTables(imageDirectory) {
     addSortArrowsToTable('basicmedlistreport', imageDirectory);
     addSortArrowsToTable('activemedlistreport', imageDirectory);
     addSortArrowsToTable('proposedmedlistreport', imageDirectory);
     addSortArrowsToTable('inactivemedlistreport', imageDirectory);
     addSortArrowsToTable('conditionlistreport', imageDirectory);

}

function addSortArrowsToTable(divId, imageDirectory) {
   var div = document.getElementById(divId);
   if (div) {
      var outterTable = div.firstChild;
      try {
         if (outterTable.nodeName == "DIV") {
            outterTable = outterTable.firstChild;
         }
         else if (outterTable.nodeName == "#text") {
            outterTable = div.childNodes[1];
         }
         if (outterTable.nodeName != "TABLE") {
            outterTable = document.getElementById("reportTable");
         }
         if (!outterTable || outterTable.nodeName == "SPAN") {
            return;
         }
//      var outterTable = document.getElementById("reportTable");

         var innerTable = outterTable.tBodies[0].rows[1].cells[0].firstChild;
         var headerRow = innerTable.tBodies[0].rows[0];
         var image = "sort_arrow_up_empty.gif";

         for (var i = 0; i < headerRow.cells.length; i++) {
             var header = headerRow.cells[i];
             var html = header.innerHTML;
             if (html.indexOf("Sort by") != -1) {
                var anchor = header.firstChild;
                if (html.indexOf("up.gif") == -1 && html.indexOf("down.gif") == -1) {
                   anchor.innerHTML += " <img src='" + imageDirectory +
                                       "themes/theme_106/" + image +
                                       "' alt='sort' title=''/>";
                }
                else {
                   // this moves the img tag into the anchor tag, so that ths 
                   // sort arrow is clickable.
                   var img = header.childNodes[1];
                   anchor.appendChild(img);
                }  
             }
         }
      }      
      catch (e) { return; }
   }
}

function importInto(appId, recordId, medListId) {
   document.getElementById('P0_IMP_RECORD_ID').value = recordId;
   if(medListId) {
      document.getElementById('P0_IMP_MED_LIST_ID').value = medListId;
   }
   doSubmit("IMPORT_SURVEY");
}

function showEditMedsListMenu(event, element, surveyId, loggedIn, appId, hasPatientRecords, hasReferenceRecords, recordModified, showHint, isCeleb, userType, recordType) {
    var region = document.getElementById('saveAsOptionsTitle');
    var hintRegion = document.getElementById('saveAsOptionsHint');
    hintRegion.innerHTML = "";
    region.innerHTML = "";

    if (loggedIn == "TRUE") {
       if ((userType == 'DEMO') && (recordType == 'P')) {
            region.innerHTML += "<div class=\"saveOption\"><a href=\"javascript:takeSurveyEditAction('" + surveyId + "', 'COPY_PATIENT');\">Copy Patient Med Cabinet to New Patient</a></div>";
       }
       region.innerHTML += 
            "<div class=\"saveOption\"><a href=\"javascript:takeSurveyEditAction('" + surveyId + "', 'SAVE_NEW_PATIENT');\">Merge Meds to New Patient Med Cabinet</a></div>";
       if (hasPatientRecords == 1) {
            region.innerHTML += "<div class=\"saveOption\"><a href=\"javascript:takeSurveyEditAction('" + surveyId + "', 'MERGE_INTO_PATIENT');\">Merge Meds into Existing Patient Med Cabinet</a></div>";
       }
       region.innerHTML +=
            "<br/><br/><div class=\"saveOption\"><a href=\"javascript:takeSurveyEditAction('" + surveyId + "', 'SAVE_NEW_REFERENCE');\">Save Meds to New Reference/Medlist</a></div>";
       if (hasReferenceRecords == 1) {
            region.innerHTML += "<div class=\"saveOption\"><a href=\"javascript:takeSurveyEditAction('" + surveyId + "', 'MERGE_INTO_REFERENCE');\">Merge Meds into Existing Reference/Medlist</a></div>";
       }

       var recordModLabel = document.getElementById('recordModLabel');
       
       if (showHint && (isCeleb == 'NO') && (recordModified == 'TRUE' || recordModLabel.innerHTML == 'Modified&nbsp;-&nbsp;unsaved')) {
            hintRegion.innerHTML = 'If you want to "Save All Changes" please do so before using "Save As".  Unsaved changes will be undone in this record and will be saved only to the Medlist or Med Cabinet you select.';
       }

       if (showHint && (isCeleb == 'YES') && (recordModified == 'TRUE' || recordModLabel.innerHTML == 'Modified&nbsp;-&nbsp;unsaved')) {
            hintRegion.innerHTML = 'You cannot "Save All Changes" for an Example Patient. You can use Save As to create a copy of the Example Patient meds which you can then save changes to. Unsaved changes will be undone in this record and will be saved only to the Medlist or Med Cabinet you select.';
       }

    }
    else {
       region.innerHTML =
            "You must sign in before saving a medlist<br/>" +
            "and then select save again<br/><br/>" +
            "<a href=\"f?p=" + appId + ":101:0\">Sign in</a> - I'm already a member<br/><br/>" +
            "<a href=\"f?p=" + appId + ":98:0\">Create an account</a> - I'm not already a member";
    }

    showMenu(event, element, '', 0, 12, '',  'saveAsOptions');
}

var curElement = null;
var curDeleteId;
var curPopupId;
var curDeleteName;
var curDivName;


function showInteractionRollOver(event, element, name1, name2, severity, id) {
    var region = document.getElementById('genericPopupTitle');
    region.innerHTML = 
         "<div class='interactionRollover'><b>" + name1 + 
         "</b><br/> interacts with <br/><b>" + 
         name2 + "</b><br/><br/>Severity: " + severity +
         "</div>";

    showMenuDelayed(event, element, name1 + " - " + name2, id, 0, '',  'genericPopup', 0, 700);
}

function getSeverityDescription(severity) {
   var severities = ["Unknown", "Moderate", "Serious", "Severe"];
   return severities[severity];
}

var curConditionId = null;
var curMedicationId = null;
var curConditions = null;
var curMedications = null;

function gotoConditionsTreatedByMed(appId) {
     window.location =
         "f?p="+appId+
         ":4029:0:::RP,4029:AI_ORIGINATING_PAGE,P4029_MEDICATION_ID:4003,"+curMedicationId;
}

function gotoMedsTreatingCondition(appId) {
     window.location = 
         "f?p="+appId+
         ":4023:0:::RP,4023:AI_ORIGINATING_PAGE,P4023_CONDITION_ID:4003,"+curConditionId;
}

function showDrugAddCondMenu(element, medicationName, medicationId, leftOffset, conditions) {
   curMedicationId = medicationId;
   curConditions = conditions;

   var conditionMedInfo = document.getElementById("conditionsTreatCell");

   if (conditions) {
      var meds = document.getElementById("condtionsForMedCell");
      meds.innerHTML = conditions;
      conditionMedInfo.style.display = "";
   }
   else {
      conditionMedInfo.style.display = "none";
   }

   showMenuDelayed(null, element, medicationName, medicationId, leftOffset, "medAddCondTitle", "medAddCond", 350, 500);
}

function showCondAddMedMenu(element, conditionName, conditionId, leftOffset, medications) {
   curConditionId = conditionId;
   curMedications = medications;

   var conditionMedInfo = document.getElementById("conditionTreatedByCell");

   if (medications) {
      var meds = document.getElementById("medsForConditionCell");
      meds.innerHTML = medications;
      conditionMedInfo.style.display = "";
   }
   else {
      conditionMedInfo.style.display = "none";
   }

   showMenuDelayed(null, element, conditionName, conditionId, leftOffset, "changeConditionTitle", "condAddMed", 350, 500);
}


function showEditDrugMenu(event, element, deleteName, deleteId, leftOffset, groupName, conditionId) {
     var groupCell = document.getElementById('changeDrugGroup');
     groupCell.innerHTML = groupName;

     showMenuDelayed(event, element, deleteName, deleteId, leftOffset, "changeDrugTitle", "editMedPopup", 260, 500);
}

function showEditCondMenu(event, element, conditionName, conditionId, leftOffset) {
     showMenuDelayed(event, element, conditionName, conditionId, leftOffset, "changeCondTitle", "editCondPopup", 0, 500);
}


function showStepOneMenu(event, element, deleteName, deleteId, leftOffset, titleDivName, popupDivName, popupWidth, delay) {

   showMenuDelayed(event, element, deleteName, deleteId, leftOffset, titleDivName, popupDivName, popupWidth,delay);

   var field = document.getElementById('P4003_MEDICATION');
   if (field && isIE()) {
      field.disabled = true;
   }

}

function showMenuDelayed(event, element, deleteName, deleteId, leftOffset, titleDivName, popupDivName, popupWidth, delay) {
   closeCurrent();

   curDeleteId = curPopupId = deleteId;
   timer = false;
   var theFunc = function() { showMenu(event, element, deleteName, deleteId, leftOffset, titleDivName, popupDivName, popupWidth, true); };
   setTimeout(theFunc, delay);
}


function showMenu(event, element, deleteName, deleteId, leftOffset, titleDivName, popupDivName, popupWidth, fromDelay, doNotOffsetTop) {

    if (curPopupId != deleteId && fromDelay) {
        return;
    }
 
    if (curDivName != null) {
       timer = true;
       closePopup(curElement, curDivName);
    }
    timer = false;

    curDivName = popupDivName;
    curDeleteId = curPopupId = deleteId;
    curDeleteName = (deleteName.indexOf("<")>0)?deleteName.substring(0, deleteName.indexOf("<")):deleteName;
    
    var parentNode = element.parentNode;
    var h = (element.clientHeight)?element.clientHeight:(element.scrollHeight + 2);
    if (!doNotOffsetTop) {
         h = h - 10;
    }
    var dTitle = document.getElementById(titleDivName);
    if (dTitle) { 
        dTitle.innerHTML = deleteName;
    }
    var div = document.getElementById(popupDivName);
    
    var windowWidth = getScrollWidth();
    if (!popupWidth) {
       popupWidth = 200;
       div.style.width="";
    }
    else {
        div.style.width= popupWidth+"px";
    }
    var left = (getLeft(element) + leftOffset);
    if (windowWidth < left + popupWidth) {
       var rightMarginOffset = document.all? 37 : 22;
       left = left - popupWidth + rightMarginOffset;
    }
    div.style.left = left + 'px';
    div.style.top = (getTop(element) + h) + 'px';
    div.style.display = "inline";
  }

var timer = false;
function stopTimer() {
  timer = false;
}

function closeCurrent(popupDivName) {

  if (! popupDivName) {
     popupDivName = curDivName;
  }
  if (popupDivName) {
     timer = true;
     closePopup(curElement, curDivName);
  }
}

function closePopup(element, popupDivName) {
   if (timer) {
      var div = document.getElementById(popupDivName);
      var field = document.getElementById('P4003_MEDICATION');
      // hack to hide cursor in IE
      if (field && isIE() && div.style.display != "none") { 
          field.disabled = false; 
          field.focus();
      }
      div.style.display = "none";
  }
}

function closePopupCountDown(element, popupDivName, delay) {
//   var field = document.getElementById('P4003_MEDICATION');
//   if (field) { field.disabled = false; }
   if (!delay) { delay = 500; }
   curPopupId = null;
   var func_def = "closePopup(curElement, '" + popupDivName + "')";
   timer = true;
   setTimeout(func_def, delay);
}

function getLeft(element) {
    if (element.offsetParent) {
       return element.offsetLeft + getLeft(element.offsetParent);
    }
    else {
       return 0;
    }
}

function getTop(element) {
    if (element.offsetParent) {
       return element.offsetTop + getTop(element.offsetParent);
    }
    else {
       return 0;
    }
}

function containsDOM (container, containee) {
  var isParent = false;
  do {
    if ((isParent = container == containee))
      break;
    containee = containee.parentNode;
  }
  while (containee != null);
  return isParent;
}

function checkMouseEnter (element, evt) {
  if (element.contains && evt.fromElement) {
    return !element.contains(evt.fromElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

function checkMouseLeave (element, evt) {
  if (element.contains && evt.toElement) {
    return !element.contains(evt.toElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

function setCustomSort(imageDirectory, curSort, curOrder) {
 // add empty sort arrows to each header that is not sorted
 var table = document.getElementById('innerSurveyTable');
 if (table) {
   var tableBody = table.tBodies[0];
   firstRow = tableBody.rows[0];
   for (var i = 0; i < firstRow.cells.length; i++) {
      var cell = firstRow.cells[i];
      var link = cell.getAttribute("id") + "";
      link.replace(/COL0?([0-9]*)/);
      var colNum = RegExp.$1;
      if (colNum != 6) {
         var headerTitle = cell.innerHTML;
         var image = (colNum == 4)?"sort_arrow_up_empty.gif":"sort_arrow_down_empty.gif";
         if (curSort == colNum) {
            image = (curOrder == "asc")?"blue_arrow_up.gif":"blue_arrow_down.gif";
         }
         cell.innerHTML = '<a href="javascript:sort(' + colNum + ')"' + 
                          '>' +
                          headerTitle + " <img src='" + imageDirectory +
                          "themes/theme_106/" + image +
                          "' alt='sort' title='' /></a>";
      }
   }
 }
}

function prepare600Table(imageDirectory, tab, curSort, curOrder) {
  var table = document.getElementById('innerSurveyTable');
  var oldLocation = document.getElementById('search_and_view');
  var newLocation;

  if (table) {
     checkForAndRunTemplates(table);
     if (tab != "Interactions") {
        newLocation = table.tHead.rows[0].cells[0];
        newLocation.innerHTML = oldLocation.innerHTML;
        addSearchLabels600(newLocation);

        oldLocation.innerHTML = "";
     }
     else {
        setInteractionNames600(imageDirectory + "themes/theme_106/");
     }
     setCustomSort(imageDirectory, curSort, curOrder);
     moveTopPaginationToBottomLeft600();
     setSurveyTableBGColors();
  }
  else if (tab != "Interactions") {
     newLocation = document.getElementById('new_search_home');
     if (newLocation) {
        newLocation.innerHTML = oldLocation.innerHTML;
        addSearchLabels600(newLocation);
        oldLocation.innerHTML = "";
     }
     else {
        addSearchLabels600(oldLocation);
        oldLocation.style.display = "inline";
     }
  }
  changeViewSelectOnChange600();
  setColSpan();
}

function addSearchLabels600(fields) {
        var viewField = fields.firstChild.tBodies[0].rows[0].cells[1];
        viewField.innerHTML = "<span class='t106OptionalLabel'>View:&nbsp;</span>" + viewField.innerHTML;

        var searchField = fields.firstChild.tBodies[0].rows[1].cells[1];
        searchField.innerHTML = "<span class='t106OptionalLabel'>Search side effects for my symptoms:</span><br/>" + searchField.innerHTML;

}

function setColSpan() {
  var surveyOptimalsTitle = document.getElementById('SurveyOptimalsTitle');
  if (surveyOptimalsTitle) {
     var table = document.getElementById('innerSurveyTable');
     var row = table.tBodies[0].rows[0];
     var colspan = 0;
     for (i = 0; i < row.cells.length; i++) {
         var cell = row.cells[i].innerHTML;
         if (cell.indexOf("Risk") != -1) {
            colspan = row.cells.length - i - 1 ;
            surveyOptimalsTitle.setAttribute("colSpan", colspan);
            break;
         }         
    }
    var shDrugsRegimensTitle = document.getElementById('shDrugsRegimensTitle2');
    if (shDrugsRegimensTitle) {
        shDrugsRegimensTitle.setAttribute("colSpan", colspan -1);
    }
  }
}

function checkPagination(minToDisplay) {
    var table = document.getElementById('innerSurveyTable');
    if (table) {
      var paginationTable = table.parentNode.parentNode.parentNode;
      var paginationText = paginationTable.lastChild.innerHTML;
      paginationText.replace(/[0-9]* - ([0-9]*)/);
      var totalCount = RegExp.$1;

      if (paginationText.indexOf("Next") == -1 && 
          paginationText.indexOf("Previous") == -1 && 
          totalCount <= minToDisplay) {

         paginationTable.lastChild.style.display = "none";
      }
    }
}

function moveTopPaginationToBottomLeft600() {
    var table = document.getElementById('innerSurveyTable').tBodies[0];
    var topPag = document.getElementById('topPagination');
    var numRows = table.rows.length;
    var pagRow = table.rows[numRows - 1];
    var pagCell = pagRow.cells[0];
    var colspan = pagCell.getAttribute("colSpan");
    pagCell.setAttribute("colSpan", colspan - 2);
    pagCell.setAttribute("colspan", colspan - 2);

    pagCell.setAttribute('align', 'center');
    var bottomRight = pagCell.innerHTML;
    pagCell.innerHTML="<table width='100%'><tr><td align='left'>" + 
                      topPag.innerHTML + 
                      "</td><td align='right'>" + 
                      bottomRight + 
                      "</td></tr></table>";
    topPag.innerHTML = '';
    var test = '';
}

function setSurveyTableBGColors () {
 var table=document.getElementById("innerSurveyTable");
 var tableBody = table.tBodies[0];
 for (var i = 1; i < tableBody.rows.length; i++) {
    var row = tableBody.rows[i];

  
    for (var j = 0; j < row.cells.length; j++) {
	var cell = row.cells[j];
        if (cell.style && cell.firstChild.style) {
          var styles;
          if (cell.firstChild.currentStyle) {
              styles = cell.firstChild.currentStyle;
          }
          else {
              styles = window.getComputedStyle(cell.firstChild, null);
          }
          if (styles.backgroundColor != "transparent") {
             cell.style.backgroundColor = styles.backgroundColor;
          }
        }
    }
 }
}

function printPage(appId, pageNum, sessionId) {
     var address = "f?p=" + appId + ":" + pageNum + ":" +
	sessionId + "::::AI_PRINTER_FRIENDLY:YES";
     var myWindow = 
     window.open (address,
"print","location=0,status=1,scrollbars=1,menubar=1,toolbar=0, height=950, width=900");
     myWindow.focus();
}

function openNews(address) { 
     var myWindow = 
     window.open (address,
"news","location=1,status=1,scrollbars=1,menubar=1,toolbar=1,height=600, width=800");
     myWindow.focus();

}

function openPartner(address) { 
     var myWindow = 
     window.open (address,
"partner","location=1,status=1,scrollbars=1,menubar=1,toolbar=1,height=700, width=1050");
     myWindow.focus();

}

function getMedicationsFromHTML(medRow, firstMedIndex) {
    var medNames = [];
    for (var i = firstMedIndex; i < medRow.cells.length; i++) {
       var html = medRow.cells[i].innerHTML;
       html = html.substring(html.indexOf("event,this,'"));
       html = html.substring(html.indexOf("'")+1);
       html = html.substring(0, html.indexOf("')"));
       medNames[i+1] = html;
    }
    return medNames;
}

function getMedSections(medRow, firstMedIndex, medIDs) {
    var medSection = [];
    for (var i = firstMedIndex; i < medRow.cells.length; i++) {
       var element = document.getElementById("MEDINFO" +medIDs[i+1]);
       medSection[i+1] = element.getAttribute("medsection");
    }
    return medSection;
}

function getMedicationIDsFromHTML(medRow, firstMedIndex) {
    var medIDs = [];
    for (var i = firstMedIndex; i < medRow.cells.length; i++) {
       var html = medRow.cells[i].innerHTML;
       html = html.substring(html.indexOf("info("));
       html = html.substring(html.indexOf("(")+1);
       html = html.substring(0, html.indexOf(","));
       medIDs[i+1] = html;
    }
    return medIDs;
}

function getMedicationsFromHTML600(medRow, firstMedIndex) {
    var medNames = [];
    for (var i = firstMedIndex; i < medRow.cells.length; i++) {
       var html = medRow.cells[i].innerHTML;
       html = html.substring(html.indexOf("event,this,'"));
       html = html.substring(html.indexOf("'")+1);
       html = html.substring(0, html.indexOf(" <br"));
       medNames[i] = html;
    }
    return medNames;
}

function setAllContraMouseovers(imageDirectory) {
 var x=document.getElementById("innerSurveyTable");
 var tableBody = x.tBodies[0];
 var medicationRow = x.tHead.rows[1];
 var medNames = getMedicationsFromHTML(medicationRow, 1);
 var medName;
 for (var i = 1; i < tableBody.rows.length; i++) {
    var row = tableBody.rows[i];
    var firstColumnToConvert;
    for (var j = 0; j < row.cells.length; j++) {
      firstColumnToConvert = j;
      var value = row.cells[j].innerHTML;
      if (value.indexOf('interact.gif') != -1) {
         medName = medNames[j-1];
         var severity = stripHTML(row.cells[0].lastChild.innerHTML);
         severity = severity.replace(":", ": ");
         var advisory = row.cells[2].firstChild.firstChild.innerHTML;
         advisory = advisory.substring(0, advisory.indexOf(":"));
         var condition = row.cells[1].firstChild.firstChild.getAttribute("laymanterm");
         addContraMouseover(row.cells[j], medName, severity, advisory, condition);
         break;
      }
    }
 }
}

function showContraRollOver(event, element, drugName, severity, advisory, condition) {
    var region = document.getElementById('genericPopupTitle');
    region.innerHTML =
         "<div class='interactionRollover'><b>" + drugName + "</b><br/>" + 
         advisory + 
         "</br>if patient has Condition of Concern</br>" +
         "<b>" + condition + "</b>" +
         "<br/><br/>" + severity + "</div>";

    showMenuDelayed(event, element, 'Contra', 0, 0, '',  'genericPopup', 0, 700);
}

function addContraMouseover(cell, drugName, severity, advisory, condition) {
   var image = cell.lastChild.childNodes[0];

   image.onmouseover = function() { showContraRollOver(this, image, drugName, severity, advisory, condition); };

   image.onmouseout = function() { closePopupCountDown(image, 'genericPopup'); };
}


function addInteractionMouseovers(name1, name2, row, severity, id) {

    for (var j = 0; j < row.cells.length; j++) {
      var element = row.cells[j].lastChild;
      var value = element.innerHTML;
      if (value && value.indexOf('interact.gif') != -1) {
          addInteractionMouseover(row.cells[j], name1, name2, severity, id);
      }
    }
}

function addInteractionMouseover(cell, name1, name2, severity, id) {
   var image = cell.lastChild.childNodes[0];

   image.onmouseover = function() { showInteractionRollOver(this, image,  name1, name2, severity, id); };

   image.onmouseout = function() { closePopupCountDown(image, 'genericPopup'); };
}

function addGraphMouseovers(surveyType) {
 var x=document.getElementById("innerSurveyTable");
 var firstMedCol = (surveyType == "Combined")?2:1;

 var medNames;
 var medIDs;
 var medSections;

 if (surveyType != "Monograph") {
    var medicationRow = x.tHead.rows[1];
    medNames = getMedicationsFromHTML(medicationRow, firstMedCol);
    medIDs = getMedicationIDsFromHTML(medicationRow, firstMedCol);
    medSections = getMedSections(medicationRow, firstMedCol, medIDs);
 }

 var tableBody = x.tBodies[0];
 for (var i = 1; i < tableBody.rows.length; i++) {
    var row = tableBody.rows[i];
    var firstColumnToConvert;
    var ade;
    for (var j = 0; j < row.cells.length; j++) {
      firstColumnToConvert = j;
      var element = row.cells[j].lastChild;
      var value = element.innerHTML;
      if (value.indexOf('risk-') != -1) {
         break;
      }
      else if (element.className == 'adeFeature' || element.className == "drugInfoAdeFeature") {
         ade = element.innerHTML;
      }
    }
    if (surveyType == "Compare") {
      for (var j = firstColumnToConvert; j < row.cells.length; j++) {
        addGraphMouseover(row.cells[j], medNames[j], medIDs[j] ,ade, medSections[j]);
      }
    }
    else if (surveyType == "Combined") {
      for (var j = firstColumnToConvert+1; j < row.cells.length; j++) {
        addGraphMouseover(row.cells[j], medNames[j], medIDs[j] ,ade, medSections[j]);
      }
      addCombinedGraphMouseover(row.cells[firstColumnToConvert], ade);
    }
    else if (surveyType == "Monograph") {
      for (var j = firstColumnToConvert; j < row.cells.length; j++) {
        addMonographRiskMouseover(row.cells[j], ade);
      }

    }
 }
}

var matchMouseover = /onmouseover=""/g;


function addCombinedGraphMouseover(cell, ade) {
   var node = cell.lastChild.innerHTML;
   var image = cell.lastChild.childNodes[1];
   if (node) {
       ade = stripHTML(ade);
       var percentage = getCellPercentage(node);

       image.onmouseover = function() { showMenuDelayed(this, image,  "<strong>Combined Risk</strong><br/>With this combination" +
                          "<br/><br/>" + percentage +
                          "<br/><strong>" + ade + "</strong>", 0 , 15, 'genericPopupTitle', 'genericPopup', 0, 700); };

       image.onmouseout = function() { closePopupCountDown(image, 'genericPopup'); };
   }
}

function addGraphMouseover(cell, medName, medId, ade, medSection) {
   var node = cell.lastChild.innerHTML;

   if (medName) {
       var image = cell.lastChild.childNodes[1];
       if (!medSection) { medSection = ""; }
       ade = stripHTML(ade);
       var percentage = getCellPercentage(node);

       image.onmouseover = function() { showMenuDelayed(this, image,  "<strong>" + medName + "</strong>" +
                         "<br/>" + medSection +
                          "<div><br/>" + percentage +
                          "<br/><strong>" + ade + "</strong></div>", 0 , 15, 'genericPopupTitle', 'genericPopup', 0, 700); };
       image.onmouseout = function() { closePopupCountDown(image, 'genericPopup'); };
   }
}

function addMonographRiskMouseover(cell, ade) {
   var node = cell.lastChild.innerHTML;

   if (node) {
       ade = stripHTML(ade);
       var percentage = getCellPercentage(node);
       var image = cell.lastChild.childNodes[1];
       image.onmouseout = function() { closePopupCountDown(image, 'genericPopup'); };
       image.onmouseover = function() { showMenuDelayed(this, image, percentage + "<br/>" + "<strong>" + ade + "</strong>", 0, 15, 'genericPopupTitle', 'genericPopup'); };

   }
}


function getCellPercentage(cell) {
    cell = cell.substring(cell.indexOf("risk-")+5);
    cell = cell.substring(0, cell.indexOf(".jpg"));

    var result = "Of 100 people<br/>";
    if (cell == 1) {
	result += "<strong>0 to 1 may experience</strong> ";
    } else if (cell == 2) {
        result += "<strong>1 to 5 may experience</strong> ";
    } else if (cell == 3) {
        result += "<strong>5 to 10 may experience</strong> ";
    } else if (cell == 4) {
        result += "<strong>10 to 25 may experience</strong> ";
    } else if (cell == 5) {
        result += "<strong>25 to 50 may experience</strong> ";
    } else if (cell == 6) {
        result += "<strong>50 to 100 may experience</strong> ";
    }
    else {
        result = "No Significant Reports";
    }

    return result;
}


function stripHTML(text) {
       var matchTag = /<(?:.|\s)*?>/g;
       text = text.replace(matchTag, "");
       matchTag = /'/g;
       return text.replace(matchTag, "\\'");
}

function setInteractionNames600(imageDirectory) {
 var x=document.getElementById("innerSurveyTable");
 var tableBody = x.tBodies[0];
 var medicationRow = x.tHead.rows[3];
 var medNames = getMedicationsFromHTML600(medicationRow, 0);
 
 for (var i = 1; i < tableBody.rows.length-1; i++) {
    var row = tableBody.rows[i];

    var firstColumnToConvert;
    for (var j = 0; j < row.cells.length; j++) {
      firstColumnToConvert = j;
      var value = row.cells[j].firstChild.innerHTML;
      if (value.indexOf('interact.gif') != -1) {
         break;
      }
    }
    var medCombo = null;
    for (var j = firstColumnToConvert+1; j < row.cells.length; j++) {
      var value = row.cells[j].firstChild.innerHTML;
      var inInteraction = (value != undefined && value.indexOf('interact.gif') != -1);

      if (inInteraction) {
        if (medCombo == null) {
          medCombo = medNames[j-firstColumnToConvert-1];
        }
        else {
          medCombo += " - " + medNames[j-firstColumnToConvert-1];
        }
      }
    }
    var interaction = row.cells[1];
    var interactionText = interaction.firstChild.firstChild;
    var myHREF = interactionText.getAttribute("href");
    myHREF = myHREF.replace(/\)/, ", '" + medCombo + "')");
    interactionText.setAttribute("href", myHREF); 
    interactionText.innerHTML = "<b style='font-size:8pt'>" + medCombo + " Interaction:</b><br/> " + interactionText.innerHTML;
    interactionText.innerHTML = "<img src='" + imageDirectory + "mono.gif' height='13' width='13' style='float:right; vertical-align: middle;'/>" + interactionText.innerHTML; 
 }
}

function setInteractionNames(imageDirectory) {
 var x=document.getElementById("innerSurveyTable");
 var tableBody = x.tBodies[0];
 var medicationRow = x.tHead.rows[1];
 var medNames = getMedicationsFromHTML(medicationRow, 1);
 for (var i = 1; i < tableBody.rows.length; i++) {
    var row = tableBody.rows[i];
    var firstColumnToConvert;
    for (var j = 0; j < row.cells.length; j++) {
      firstColumnToConvert = j;
      var value = row.cells[j].innerHTML;
      if (value.indexOf('interact.gif') != -1) {
         break;
      }
    }
    var medCombo = null;
    var name1 = null;
    var name2 = null;
    for (var j = firstColumnToConvert; j < row.cells.length; j++) {
      var value = row.cells[j].innerHTML;
      var inInteraction = (value != undefined && value.indexOf('interact.gif') != -1);
      if (inInteraction) {
        if (medCombo == null) {
          medCombo = medNames[j];
          name1 = medNames[j];
        }
        else {
          medCombo += " - " + medNames[j];
          name2 = medNames[j];
        }
      }
    }
    var severity = row.cells[0].lastChild.innerHTML;
    var interaction = row.cells[1];
    var interactionText = interaction.lastChild.firstChild;
    var myHREF = interactionText.getAttribute("href");
    var interactionID = myHREF.substring(myHREF.indexOf("(") +1, myHREF.indexOf(")"));

    myHREF = myHREF.replace(/\)/, ", '" + medCombo + "')");
    interactionText.setAttribute("href", myHREF);
    interactionText.innerHTML = "<img src='" + imageDirectory + "mono.gif' height='15' width='15' style='float:right; vertical-align: middle;'/>" + interactionText.innerHTML;


    addInteractionMouseovers(name1, name2, row, severity, interactionID);
 }
}

function convertInteraction(cell, className) {
   var value = cell.firstChild.innerHTML;
   var inInteraction = (value.indexOf('interact.gif') != -1);
   cell.innerHTML = cell.firstChild.innerHTML;
   return inInteraction;
}

function moveViewSelector() {
        var newPlace = document.getElementById("new_view_select");;
        var viewSelect=document.getElementById("view_select");

        newPlace.innerHTML = "<table><tr><td><span class='shLabel'>View:</span></td><td>" + viewSelect.innerHTML + "</td></tr></table>";
        viewSelect.innerHTML = '';

        changeViewSelectOnChange();

}

function moveSearchFields() {
        var  newPlace = document.getElementById("new_search_field");;
        var searchField=document.getElementById("search_field");
        newPlace.innerHTML = "<span class='shLabel'>Search side effects for my symptoms:</span><br/>"  + searchField.innerHTML;

        // remove the old searchField so that field with the same
        // name is not submitted
        searchField.innerHTML = '';
        moveViewSelector();
}

function changeViewSelectOnChange() {
        var viewSelect = document.getElementById('P4002_SURVEY_VIEW');
        if (viewSelect == null) { 
            viewSelect = document.getElementById('P4002_SURVEY_VIEW2');
        }
        var locationText = viewSelect.getAttribute('onchange') + '';
        locationText  = getRequestParamater(locationText);

        viewSelect.onchange = function(){disableThenSubmit(locationText);};

}

function changeViewSelectOnChange600() {
        var viewSelect = document.getElementById('P3003_VIEW_SELECT');
        var locationText = viewSelect.getAttribute('onchange') + '';
        locationText  = getRequestParamater(locationText);
        viewSelect.onchange = function(){disableThenSubmit(locationText);};
}

function enablePage() {
   if (document.getElementById('wholePage')) {
      document.getElementById('wholePage').style.display = "none";
      document.getElementById('processingPage').style.display = "none";
   }
}
 
function disablePage() {
       document.getElementById('wholePage').style.display = "inline";
//       document.getElementById('processingPage').style.display = "inline";
}

function disablePageForPrinting() {
   var myDiv = document.getElementById('wholePage');
   if (myDiv) {
       myDiv.style.display = "inline";
       myDiv.style.cursor = 'default';
       myDiv.style.opacity = 0;
       myDiv.style.filter = 'alpha(opacity=0)';
   }
}

function disableThenRedirect(address) {
   disablePage();
   location.href = address;
}

function disableThenSubmit(request) {
   disablePage();
   doSubmit(request);
}

function getRequestParamater(locationText) {
  var start = locationText .indexOf("'");
  var end = locationText .lastIndexOf("'");
  return locationText .substring(start+1, end);
}

function moveFirstDataRowToHeader() {
        var dataTable = document.getElementById("zpGrid0DataTableTable");
        var headerTable = document.getElementById("zpGrid0Head").parentNode.parentNode;
        headerTable.tBodies[0].appendChild(dataTable.rows[0]);

        var fixedLeftFirstRow = document.getElementById("zpGrid0Row0Fixed");
        var fixedLeftTableBody = fixedLeftFirstRow.parentNode;
        var fixedLeftHeaderBody = document.getElementById("zpGrid0HeadFixed").parentNode;
        fixedLeftHeaderBody.appendChild(fixedLeftFirstRow);
}

function showSearchBox() {
    var errorMessage = document.getElementById("errorMessage");
    var searchField=document.getElementById("search_field");    
    var viewSelect = document.getElementById("view_select");
    var table = 
     '<table cellpadding="0" cellspacing="0">' +
      '<tr>' +
         '<td class="shLabel">View:&nbsp;</td>' +
         '<td class="shEntryField" id="new_view_select">' +
           viewSelect.innerHTML +
         '</td>' +
      '</tr>' +
      '<tr>' +
         '<td class="shLabel">Search side effects for my symptoms:&nbsp;</td>' +
         '<td class="shEntryField" id="new_view_select">' + 
            searchField.innerHTML + 
         '</td>' +
     '</tr>' +
    '</table>';
	    errorMessage.innerHTML = table + 
                                     errorMessage.innerHTML;
    errorMessage.style.marginTop = "1px";
    viewSelect.innerHTML = '';
    searchField.innerHTML = '';

    changeViewSelectOnChange();
}

function showViewSelectBox() {
    var errorMessage = document.getElementById("errorMessage");
    var viewSelect = document.getElementById("view_select");
    var table =
     '<table cellpadding="0" cellspacing="0">' +
      '<tr>' +
         '<td class="shLabel">View:&nbsp;</td>' +
         '<td class="shEntryField" id="new_view_select">' +
           viewSelect.innerHTML +
         '</td>' +
      '</tr>' +
    '</table>';
            errorMessage.innerHTML = table +
                                     errorMessage.innerHTML;
    errorMessage.style.marginTop = "1px";
    viewSelect.innerHTML = '';

    changeViewSelectOnChange();
}

function hideLabels() {
 var sourceTable=document.getElementById("innerSurveyTable");
 var tableHead = sourceTable.tHead;
 tableHead.rows[0].cells[0].innerHTML = '&nbsp;';
 tableHead.rows[1].cells[0].innerHTML = '&nbsp;';
}


function checkForAndRunTemplates(table) {
  var tHead = table.tHead;
  var numRows = tHead.rows.length;
  var i;
  for (i = 0; i < numRows; i++) {
    var row = tHead.rows[i];
    var numCells = row.cells.length;
    var j;
    for (j = 0; j < numCells; j++) {
       checkForAndRunTemplate(row.cells[j]);
    }
  }
}


function checkForAndRunTemplate(cell) {
  var checkHere = cell.firstChild;
  if (checkHere && checkHere.nodeName.toUpperCase() == "DIV") {
     var className = checkHere.getAttribute("class");
     if (className == null) {
         className = checkHere.className;
     }

     if (className == "template") {
        var values = checkHere.innerHTML;
        var indexOfFirstSeparator = values.indexOf(":::");
        var templateName = values.substring(0, indexOfFirstSeparator);
        values = values.substring(indexOfFirstSeparator + 3, values.length);
        var valueArray = values.split(":::");
        var names = getNamesForTemplate(templateName);
        var template = getTemplateByName(templateName);
        cell.innerHTML = runTemplate(template, names, valueArray);
     }
  }
}

function runTemplate(template, names, values) {
   var length = names.length;
   var i = 0;
   for (i = 0; i < length; i++) {
      var value = values[i];
      var name = names[i];
      
      var r = new RegExp(name, 'g');
      template = template.replace(r, value); 
   }
   template = template.replace(/&APP_ID./, getAppId());
   template = template.replace(/&APP_SESSION./, getSessionId());
   return template;
}

function templatizeDrugHeader(cell, drugTemplate) {
  var value = cell.firstChild.innerHTML;
  var values = value.split(":::");
  values[1] = values[1].substring(0, 4);

  var names = new Array(4);
  names[0] = "\\*MEDICATION_ID\\*";
  names[1] = "\\*DRUG_DISPLAY_NAME\\*";
  names[2] = "\\*ESCAPED_DRUG_DISPLAY_NAME\\*";
  names[3] = "\\*MED_SECTION\\*";

  cell.innerHTML = runTemplate(drugTemplate, names, values);
}

function getFirstDrugIndex(row) {
   for (var i = 0; i < row.cells.length; i++) {
       var cell = row.cells[i];
       var className = cell.className;
       if (className == "shCurrentDrugs") {
            return i;
       }
   }
}

function prepareSourceTable(numMeds, imageDirectory, drugTemplate) {
 var sourceTable=document.getElementById("innerSurveyTable");
 var tableHead = sourceTable.tHead;

 var firstRow = tableHead.rows[1];
 var magicWidth = 60; //135;
 var firstDataRow = sourceTable.tBodies[0].rows[1];
 var firstDrugCell = getFirstDrugIndex(firstRow);

 firstRow.cells[firstDrugCell].setAttribute("span", numMeds);
 var minDrugWidth = 60; //70;
 if (numMeds == 1 && magicWidth > firstRow.cells[firstDrugCell].scrollWidth) {
     templatizeDrugHeader(firstRow.cells[firstDrugCell], drugTemplate);
 } else {
   for (var i = firstDrugCell; i < firstRow.cells.length; i++) {
       var newWidth = minDrugWidth;
       var cell = firstRow.cells[i];
       templatizeDrugHeader(cell, drugTemplate);
   }
 }

 moveTopPaginationToBottomLeft();
}

function isChrome() {
   return navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
}

function isIE() {
   return (navigator.appName.indexOf('Internet Explorer') != -1);
}

var finalPagDiv = document.getElementById('finalPagDiv');
var finalPagDivWidth = 450;
var currentFinalPagDivLeft = 0;

function moveTopPaginationToBottomLeft() {
   var topPag = document.getElementById('topPagination');
   var mainTableBody = document.getElementById('innerSurveyTable').parentNode.parentNode.parentNode;
   var row = mainTableBody.lastChild;
   var cell = row.lastChild;
   cell.setAttribute("align", "left");
   var numRowSelectRegion = document.getElementById('numRowsToDisplay');
   cell.innerHTML = "<div style='position: relative; left: 0px' id='finalPagDiv'><table cellpadding='0' cellspacing='0' width='" + finalPagDivWidth + "px'><tr><td align='left'>" + numRowSelectRegion.innerHTML + "</td><td align='right'>" + cell.innerHTML + "</td></tr></table></div>";
   numRowSelectRegion.innerHTML = "";
}

function movePagination() {
  if (finalPagDiv) {
    var windowWidth = getScrollWidth();
    var elementLeft = getLeft(finalPagDiv);
    var windowLeft = XDSOC();
    var windowRight = windowWidth + windowLeft;
    var maxWidth = document.getElementById('innerSurveyTable').offsetWidth;
    var reachedEdge = false;
    while (windowLeft > elementLeft && !reachedEdge) {
        windowLeft = XDSOC();
        elementLeft = getLeft(finalPagDiv);

        currentFinalPagDivLeft +=  10;

        if (currentFinalPagDivLeft + finalPagDivWidth > maxWidth) {
           currentFinalPagDivLeft = maxWidth - finalPagDivWidth;
           reachedEdge = true;
        }

        finalPagDiv.style.left = currentFinalPagDivLeft + "px";
    }
    windowRight = windowWidth + windowLeft;
    var elementRight = elementLeft + finalPagDivWidth;
    reachedEdge = false;
    while (elementRight > windowRight && !reachedEdge) {
        currentFinalPagDivLeft -= 10;
        if (currentFinalPagDivLeft < 0) {
           currentFinalPagDivLeft = 0;
           reachedEdge = true;
        }
        finalPagDiv.style.left = currentFinalPagDivLeft + "px";
        
        elementLeft = getLeft(finalPagDiv);
        windowLeft = XDSOC();
        windowRight = windowWidth + windowLeft;
        elementRight = elementLeft + finalPagDivWidth;
    }
    

  }
  else {
    finalPagDiv = document.getElementById('finalPagDiv');
  }

}

function moveNewSurveyButton() {
        var addMedsButton=document.getElementById("new_survey_button");
        var newPlace = document.getElementById("spotForNewSurveyButton");
        if (addMedsButton && newPlace) {
           newPlace.innerHTML = addMedsButton.innerHTML;
           addMedsButton.innerHTML = "";
        }
}

function addRecordNow(recordType, page, app) {
    window.location="f?p="+app+":4020:0::RP,4002:4020:AI_RECORD_TYPE_CD,AI_ORIGINATING_PAGE:" + recordType + "," + page;
}

function gotoRecordMedListNow(recordId, medListId, app, nextPage) {
    if (!nextPage) { nextPage= 4003; }
  
    window.location="f?p="+app+":"+nextPage+":0:::RP,4002:AI_SELECTED_MEDS_LIST_ID,AI_SELECTED_RECORD_ID:" + medListId + "," + recordId;
}

function addRecordMedListNow(recordId, page, app) {
    window.location="f?p="+app+":4005:0:::4002:P4005_MEDS_LIST_ID,AI_ORIGINATING_PAGE,AI_SELECTED_RECORD_ID:-1," + page + "," + recordId;
}

function gotoImportMedsNow(recordId, app) {
    window.location="f?p="+app+":4025:0:::4002,4027,4028:AI_SELECTED_RECORD_ID:" + recordId;
}

var AutocompleterPS = null;
if (isChrome() || (Prototype.Browser.IE && "undefined" == typeof document.documentMode || Prototype.Browser.IE && document.documentMode < 8)) {
  // In IE7 and earlier and IE8 in quirks mode, the Ajax.Autocompleter will disappear if the user
  // clicks on the window's scrollbar since this causes the auto-completer to blur. Under IE8 and
  // and later in standards mode and Firefox the scrollbar does not cause the auto-completer to blur.
  // This fix works around this issue by delaying the blur by 200ms and determining if the user has
  // clicked on a real HTML element or not.
  // See http://www.nabble.com/AutoComplete-results-disappear-when-using-scrollbar-in-IE-td23612503.html
  // for discussion of this issue.
  AutocompleterPS = Class.create(Ajax.Autocompleter, {
    initialize: function($super, element, update, url, options) {
      $super(element, update, url, options);
      this.clicked_outside = false;
      Event.observe(document, "click", this.onDocumentClick.bindAsEventListener(this));
      this.element.stopObserving("blur");
      this.element.observe("focus", this.onFocusOverride.bindAsEventListener(this));
      this.element.observe("blur", this.onBlurOverride.bindAsEventListener(this));
    },
    //render: function() {
       // shawn hasn't figured out how to get this render to override
       // the render in scriptaculous/controls.js, so for now he has
       // changed render in Autocompleter directly. if controls.js is
       // ever updated make sure the corrispondig change currently there
       // makes its way into the new source file
    //},
    onDocumentClick: function(event) {
      if (this.element.id != event.target.id) {
        this.clicked_outside = true;
      }
    },
    onFocusOverride: function(event) {
      var thisObject = this;
      thisObject.clicked_outside = false;
    },
    onBlurOverride: function(event) {
      var thisObject = this;
      var callback = function() {
        if (thisObject.clicked_outside) {
          thisObject.clicked_outside = false;
          thisObject.onBlur(event);
        }
        else {
          thisObject.element.focus();
        }
      };
      setTimeout(callback, 200);
    }
  });
}
else {
  AutocompleterPS = Ajax.Autocompleter;
}

function setMatchedCss(field) {
   field.style.color = "blue";
}

function setUnmatchCss(field, choices) {
    var fieldValue = field.value.toLowerCase();
    var theList = choices.firstChild;
    for (var i = 0; i < theList.childNodes.length; i++) {
        var node = theList.childNodes[i];
        if (fieldValue == node.innerHTML.toLowerCase()) {
           field.style.color = "blue";
           return;
        }
    }
    field.style.color = "red";
}

var matchNotChecked = /checkmark-notcheck.gif/g;
var matchGrayed = /checkmark-grayed.gif/g;
var matchChecked = /checkmark.gif/g;

var recordChanged = false;
function updateChangeStatus(theImage) {
     recordChanged = true;
     var headers = theImage.parentNode.parentNode.parentNode.parentNode.rows[0].cells;
     var cells = theImage.parentNode.parentNode.parentNode.cells;

     for (var i = 0; i < cells.length; i++) {
        if (headers[i].id == "CHANGE_STATUS") {
            cells[i].innerHTML = "modified";
        }
     }
}

function getPreviousSibling(cell) {
      while (true) {
          cell= cell.previousSibling;
          if (cell== null || cell.nodeName == "td" || cell.nodeName == "TD") {
             return cell;
          }
      }
}

function focusOnMedication() {
  if(document.getElementById('P4003_MEDICATION')) {
     document.getElementById('P4003_MEDICATION').focus();
  }
  if (document.getElementById('P4028_ROUTED_MED')) {
    document.getElementById('P4028_ROUTED_MED').focus();
  }
  if (document.getElementById('P4006_SEARCH_DRUG_NAME')) {
    document.getElementById('P4006_SEARCH_DRUG_NAME').focus();
  }

}


function switchConditionType(field) {
    var offCell = document.getElementById("OFF_LABEL_CELL");
    var onCell = document.getElementById("ON_LABEL_CELL"); 
    if (field && field.value == "On") {
        offCell.style.display = "none";
        document.getElementById("P4021_OFF_LABEL_CONDITION").value = '';
        getPreviousSibling(offCell).style.display = "none";
        onCell.style.display = "";
        getPreviousSibling(onCell).style.display = "";
    }
    else {
        if (field) {
           getPreviousSibling(onCell).style.display = "none";
           getPreviousSibling(offCell).style.display = "";
           onCell.style.display = "none";
           document.getElementById("P4021_ROUTED_COND_ON_LABEL").value = '*null*';

        }
        getPreviousSibling(offCell).style.display = "";
        offCell.style.display = "";
    }
}

function clearHeaderTotals() {
     var message = 'Click to Map Risks';
     var stats = document.getElementById('sideEffectsStats');
     if (stats) { stats.innerHTML = message; }
     stats = document.getElementById('interactionsStats');
     if (stats) { stats.innerHTML = message; }
     stats = document.getElementById('contraindicationsStats');
     if (stats) { stats.innerHTML = message; }
}

function updateMedMap(checkboxid, conditionId, medId) {
    changeCheckBoxDisplayed(checkboxid, null);
    updateCondMedMap(conditionId, medId);
}

function updateCondMedMap(conditionId, medId) {
     var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=UPDATE_COND_MED_MAP',0);
     get.add('TF_MED_ID', medId);
     get.add('TF_CONDITION_ID', conditionId);
     gReturn = get.get('XML');
}

function changeCheckBoxDisplayed(checkboxId, countId) {
     var theImage = document.getElementById(checkboxId);
     var count = document.getElementById(countId);
     var countValue = (count)?count.innerHTML:0;
     if (theImage.src.match(matchNotChecked)) {
        theImage.src = theImage.src.replace(matchNotChecked, "checkmark.gif");
        countValue++;
     }
     else {
        theImage.src = theImage.src.replace(matchChecked, "checkmark-notcheck.gif");
        countValue--;
     }
     return countValue;
}

// This updates the checkboxes appropriately along with making
// a request back to server to update all of the values in 
// the database
function updateShowInSurvey(checkboxId, countId) {
     var theImage = document.getElementById(checkboxId);
     var routedDrugId = theImage.getAttribute("routeddrugid"); 
     var medId = theImage.getAttribute("medicationid");
     if (theImage.src.match(matchGrayed)) {
         theImage.focus = false;
         return;
     }
     var countValue = changeCheckBoxDisplayed(checkboxId, countId);
     var count = document.getElementById(countId);

     if (count) {
        count.innerHTML = countValue;
     }
     updateChangeStatus(theImage);
     updateSameRoutedDrugs(routedDrugId, medId);
     clearHeaderTotals();
     showEditButtons();
     // order of these two calls matter
     updateIncludeInSurveyColumns(medId);
     updateRecordLabel();
}

function showEditButtons() {
     var div = document.getElementById('copyButtonSection');
     if (div) { div.style.display = ''; }
}

function updateRecordLabel() {
     var recordLabel = document.getElementById("recordModLabel");
     if (recordLabel) {
         var modLabel = getItem("AI_MODIFIED_LABEL", getAppId(), getSessionId());
         recordLabel.innerHTML = modLabel;
     }
}

function updateIncludeInSurveyColumns(medId, action) {
     var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=SET_SHOW_IN_SURVEY',0);
     get.add('TF_MED_ID', medId);
     get.add('TF_CHECKBOX_ACTION', action);
     gReturn = get.get('XML');
}

function removeAllRoutedDrugs(checkboxId) {
     var theImage = document.getElementById(checkboxId);
     var routedDrugId = theImage.getAttribute("routeddrugid");
     var medId = theImage.getAttribute("medicationid");

     // uncheck everything, even the current drug since it won't match -1
     updateSameRoutedDrugs(routedDrugId, -1);
     updateChangeStatus(theImage);
     // order of these two calls matter 
     updateIncludeInSurveyColumns(medId, "REMOVE_ALL");
     updateRecordLabel();     
}

function invertRoutedDrugSelection(checkboxId) {
     var theImage = document.getElementById(checkboxId);
     var routedDrugId = theImage.getAttribute("routeddrugid");
     var medId = theImage.getAttribute("medicationid");

     var groups = ["REG", "PROPOSED", "INACTIVE"];
     for (var i = 0; i < groups.length; i++) {
        for (var j = 1; true; j++) {
            var id = "check" + groups[i] + j;
            var element = document.getElementById(id);
            if (element) {
               var curRoutedDrugId = element.getAttribute("routeddrugid");
               if (curRoutedDrugId == routedDrugId) {
                   if (element.src.match(matchGrayed)) {
                      element.src = element.src.replace(matchGrayed, "checkmark.gif");
                   }
                   else {
                      element.src = element.src.replace(matchChecked, "checkmark-grayed.gif");

                  }
                  updateChangeStatus(element);
               }
            }
            else {
               break;
            }
        }
     }

     updateChangeStatus(theImage);
     // order of these two calls matter
     updateIncludeInSurveyColumns(medId, "FLIP_ROUTED");
     updateRecordLabel();

}

// Update all unchecked drugs that share a routed drug id
// with a grayed out checkbox or a notchecked chechbox
function updateSameRoutedDrugs(routedDrugId, medId) {
     var groups = ["REG", "PROPOSED", "INACTIVE"];
     for (var i = 0; i < groups.length; i++) { 
        for (var j = 1; true; j++) {
            var id = "check" + groups[i] + j;
            var element = document.getElementById(id);
            if (element) {
               var curRoutedDrugId = element.getAttribute("routeddrugid");
               var curMedId =  element.getAttribute("medicationid");
               if (curMedId != medId && curRoutedDrugId == routedDrugId) {
                   if (element.src.match(matchNotChecked)) {
                      element.src = element.src.replace(matchNotChecked, "checkmark-grayed.gif");
                   }
                   else {
                      element.src = element.src.replace(matchGrayed, "checkmark-notcheck.gif");
                      element.src = element.src.replace(matchChecked, "checkmark-notcheck.gif");
                  }
                  updateChangeStatus(element);
               }
            }
            else {
               break;
            }
        } 
     }

}

function showGrayedOutRoutedInfoBox(event, element) {

   if (element.src.match(matchGrayed)) {

      var region = document.getElementById('genericPopup');
      var routedDesc = element.getAttribute("routeddrugdesc");
      var routedDrugId = element.getAttribute("routeddrugid");
      var imageId = element.id;

      region.innerHTML = "<div class=\"duplicateRoutedDrug\" style=\"text-align:center\">Loading...</div>";
      showMenu(event, element, '', 0, 12, '',  'genericPopup');

      var get = new htmldb_Get(
        null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=GET_ROUTED_GROUP_INCLUDED',0);
      get.add('TF_MED_ID', routedDrugId);
      var section = get.get();

   

      region.innerHTML =
        "<div class=\"duplicateRoutedDrug\"><strong>" + routedDesc + "</strong><br/>" +
        "A row for " + routedDesc + " in " +  section + " is already included in the risk maps." +
        "<div class=\"duplicateRoutedDrugAction\"><a href=\"javascript:removeAllRoutedDrugs('" + imageId + "')\">Do not include " + routedDesc + " in the risk maps</a></div>" +
        "<div class=\"duplicateRoutedDrugAction\"><a href=\"javascript:invertRoutedDrugSelection('" + imageId + "')\">Include this row of " + routedDesc + " in the risk maps</a></div></div>";
   }

}

function updateMedSection (updateMapItReminder) {
   if (document.getElementById('P4028_MED_END_DATE')) {
      var proposed = document.getElementById('P4028_PROSPECTIVE_USE_FLAG_0').checked;
      var endDate = document.getElementById('P4028_MED_END_DATE').value;
      var startDate = document.getElementById('P4028_MED_START_DATE').value;
      var section = document.getElementById('medSection');
      section.innerHTML = (endDate == null || endDate == "")?(proposed?"Proposed Meds":(startDate == null || startDate == "")?"Set the Med Group using the fields below":"Active Meds"):"Inactive Meds";
      var hintDiv = document.getElementById("mapItReminder");
      if (updateMapItReminder && hintDiv) {
         hintDiv.style.display = "inline";
      }
   }
}

// Close the div when what is clicked is not contianed in the div
function closeMenuWhenClickedElseWhere(event) {
  event = event || window.event;
  var target = event.target || event.srcElement;

  if (!checkContainedId(target, "viewThisQuickLinks") && 
      !checkContainedId(target, "surveySelector")) {
    
      document.getElementById("viewThisQuickLinks").style.display = "none";
      unregisterEventHandler(document, 'click', closeMenuWhenClickedElseWhere);
  }
}

// return true if node or one of its parents
// has the specified id
function checkContainedId(node, id) {
   if (node == null) {
     return false;
   }
   if (node.id == id) {
     return true;
   }
   return checkContainedId(node.parentNode, id);
}

// register an event handler on a node
function registerEventHandler(node, event, handler) {
  if (typeof node.addEventListener == "function")
    node.addEventListener(event, handler, false);
  else
    node.attachEvent("on" + event, handler);
}

// unregister an event handler on a node
function unregisterEventHandler(node, event, handler) {
  if (typeof node.removeEventListener == "function")
    node.removeEventListener(event, handler, false);
  else
    node.detachEvent("on" + event, handler);
}

// if the menu is closed then open it. if it is open then close it
function toggleMenu(event, element, name, id, leftOffset, titleDivName, popupDivName, popupWidth, fromDelay) {

    popupWidth=320;
    if (document.getElementById(popupDivName).style.display == "none") {
        if (isIE() && popupDivName == 'viewThisQuickLinks') {
           document.getElementById(popupDivName).style.width="335px";
           popupWidth = 335;
        }
        showMenu(event, element, name, id, leftOffset, titleDivName, popupDivName, popupWidth, fromDelay, true);
        registerEventHandler(document, 'click', closeMenuWhenClickedElseWhere);
    }
    else {
        closeCurrent(popupDivName);
        unregisterEventHandler(document, 'click', closeMenuWhenClickedElseWhere);
    }
}

function ignoreClicksForPrinting(event) {
  Event.stop(event);
  var result = true;
  return result;
//  var target = event.target || event.srcElement;
//  return (checkContainedId(target, "CLOSE"));
}

  function getNextRow(row) {
      while (true) {
          row = row.nextSibling;
          if (row == null || row.nodeName == "tr" || row.nodeName == "TR") {
             return row;
          }
      }
  }

  function showOpenChildren(row) {
     var level = parseInt(row.getAttribute("level"));
     var nextRow = row;
     while (true) {
        var nextRow = getNextRow(nextRow);
        if (nextRow == null) {
          break;
        }
        var nextLevel = parseInt(nextRow.getAttribute("level"));
        if (nextLevel == null || nextLevel == level) {
           break;
        }

        if (nextLevel == level + 1) {
           nextRow.style.display = "";
           if (nextRow.innerHTML.indexOf("minus") != -1) {
              showOpenChildren(nextRow);
           }     
        }
        if (nextLevel <= level) {
           break;
        }
     }
  }

  function hideAllChildren(row) {
    var level = parseInt(row.getAttribute("level"));
    nextRow = row;
    while (true) {
        var nextRow = getNextRow(nextRow);
        if (nextRow == null) {
          break;
        }
        var nextLevel = parseInt(nextRow.getAttribute("level"));
        if (nextLevel == null || nextLevel <= level) {
           break;
        }
        
        nextRow.style.display = "none";
    }
  }


  function switchtreeview(rowNum, level, nodeId) {
      var rowName = "level" + level + "treerow" + rowNum;
      var row = document.getElementById(rowName);
      if (row.innerHTML.indexOf("plus") != -1) {
          switchImage(row, "plus.gif", "minus.gif");
          showOpenChildren(row);
          new Ajax.Request('/dcls/updateselector?nodeId=' + nodeId + 
                           '&action=open', { method:'post' });
      }
      else {
          hideAllChildren(row);
          switchImage(row, "minus.gif", "plus.gif");
          new Ajax.Request('/dcls/updateselector?nodeId=' + nodeId + 
                           '&action=close', { method:'post' });
      }
  }

  function switchImage(row, oldString, newString) {
     var innerTable = row.cells[0].firstChild;
     var cell = innerTable.tBodies[0].rows[0].cells[0];
     var myImage = cell.firstChild.firstChild;
     myImage.src = myImage.src.replace(oldString, newString);
  }

function gotoExampleMedList(recordId, medListId, app) {
   gotoRecordMedList(recordId, medListId, app, 4002);
}

function gotoRecordMedList(recordId, medListId, app, nextPage) {
    if(confirmIfUnsaved()) {
       gotoRecordMedListNow(recordId, medListId, app, nextPage);
    }
}

function gotoImportMeds(recordId, app) {
    if(confirmIfUnsaved()) {
       gotoImportMedsNow(recordId, app);
    }
}

function addRecordMedlist(recordId, page, app) {
    if(confirmIfUnsaved()) {
       addRecordMedListNow(recordId, page, app);
    }
}

function addRecord(recordType, page, app) {
    if(confirmIfUnsaved()) {
       addRecordNow(recordType, page, app);
    }
}

function saveNewPatientImport() {
    var name = document.getElementById('P0_RECORD_NAME');
    var birthDate = document.getElementById('P0_BIRTHYEAR');
    if (name.value == null || name.value == '') {
       alert('Please enter a name for the new record.');
    }
    else if (!recordDoesNotExist(name.value, 'P')) {
       alert ('A Patient named ' + name.value + ' already exists. Please enter a different Name.');
    }
    else if (birthDate.value != null && birthDate.value != '' && !checkDate(birthDate)) {
       return;
    }
    else {
       doSubmit("NEW_PATIENT_IMPORT");
    }
}

function checkNameField(element) {
    var name = document.getElementById('P0_REFERENCE_NAME');
    if (element.value == -1) {
        name.disabled = false;
    }
    else {
        name.disabled = true;
    }
}

function saveNewReferenceImport() {
    var name = document.getElementById('P0_REFERENCE_NAME');
    var id = document.getElementById('P0_REFERENCE_ID');
    var medListName = document.getElementById('P0_MED_LIST_NAME');

    if ((name.value == null || name.value == '') && id.value == -1) {
       alert('Please enter a name for the new reference record. Or select an existing one.');
    }
    else if (medListName.value == null || medListName.value == '') {
       alert("Please enter a name for the new Medication List.");
    }
    else if (id.value != -1 && !medlistDoesNotExist(medListName.value, id.value)) {
       alert ('A MedList named ' + medListName.value + ' already exists in the selected Reference Folder. Please enter a different Name.');
    }
    else if (id.value == -1 && !recordDoesNotExist(name.value, 'R')) {
       alert ('A Reference Folder named ' + name.value + ' already exists. Please enter a different Name.');
    }
    else {
       doSubmit("NEW_REFERENCE_IMPORT");
    }
}

function checkDate(fld) {
    var mo, day, yr;
    var entry = fld.value;
    var re = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
    if (re.test(entry)) {
        var delimChar = (entry.indexOf("/") != -1) ? "/" : "-";
        var delim1 = entry.indexOf(delimChar);
        var delim2 = entry.lastIndexOf(delimChar);
        mo = parseInt(entry.substring(0, delim1), 10);
        day = parseInt(entry.substring(delim1+1, delim2), 10);
        yr = parseInt(entry.substring(delim2+1), 10);
        var testDate = new Date(yr, mo-1, day);
        if (testDate.getDate() == day) {
            if (testDate.getMonth() + 1 == mo) {
                if (testDate.getFullYear() == yr) {
                    return true;
                } else {
                    alert("There is a problem with the year entry.");
                }
            } else {
                alert("There is a problem with the month entry.");
            }
        } else {
            alert("There is a problem with the date entry.");
        }
    } else {
        alert("Incorrect date format. Enter as mm/dd/yyyy.");
    }
    field.focus();
    return false;
}

function copyPatientRecord() {
    var name = document.getElementById('P0_RECORD_NAME2');
    if (name.value == null || name.value == '') {
       alert('Please enter a name for the new record.');
    }
    else if (!recordDoesNotExist(name.value, 'P')) {
       alert ('A Patient named ' + name.value + ' already exists. Please enter a different Name.');
    }
    else {
       doSubmit("COPY_PATIENT");
    }
}

