// go to add med page based on record type
function addMedFromMaps() {
   if (getRecordType() == 'P') {
      window.location = "f?p=" + getAppId() + ":4028:0::NO:RP,4028:AI_ORIGINATING_PAGE:4002";
   }
   else {
      window.location = "f?p=" + getAppId() + ":4006:0::NO:RP,4006:AI_ORIGINATING_PAGE:4002";
   }
}

// append another function call to the end of body onload handler
function addLoadEvent(func) { 
  var oldonload = window.onload; 
  if (typeof window.onload != 'function') { 
    window.onload = func; 
  } 
  else { 
    window.onload = function() { 
      if (oldonload) { 
        oldonload(); 
      } 
      func(); 
    } 
  } 
} 

// if the search field doesn't have a value then set the value
// to a hint on usage and gray it out.
function setSearchHint() {
   var searchField = document.getElementById("P0_SEARCH");
   if(!searchField ) {
     searchField = document.getElementById("P4004_SEARCH");
   }

   if (searchField && (searchField.value == null || searchField.value == "" || searchField.value == getSearchHintText())) {
       searchField.style.color = "#777777";
       searchField.value = getSearchHintText();
   }
}

// if the search field text is the search hint
// then change it to the empty string and make the
// text color black.
function searchFieldFocus() {
    var searchField = document.getElementById("P0_SEARCH");
    if (!searchField) {
       searchField = document.getElementById("P4004_SEARCH");
    }
    if (searchField && searchField.value  == getSearchHintText()) {
       searchField.value = '';
       searchField.style.color = "red";
   }
} 

// Clears the search summary information out of the map accordions
function clearSearchSummary() {
    var searchStatDiv = document.getElementById('interactionsSearchStats');
    if (searchStatDiv) {
	searchStatDiv.innerHTML = "";
    }

    searchStatDiv = document.getElementById('sidEffectsSearchStats');
    if (searchStatDiv) {
	searchStatDiv.innerHTML = "";
    }

    searchStatDiv = document.getElementById('contraindicationsSearchStats');
    if (searchStatDiv) {
	searchStatDiv.innerHTML = "";
    }
}

// update search summary for interactions, based on the lucene xml results
function setInteractionSearchSummary2(xml) {
    var searchStatDiv = getSearchSummaryRegion('interactionsSearchStats');
    if (delimitedSearchTerm && delimitedSearchTerm != EMPTY_STRING) {
	var searchCount = 0;
	var severeCount = 0;
	var seriousCount = 0;
	var moderateCount = 0;
	if (xml) {
	    for (var i = 0; i < xml.childNodes.length; i++) {
		var node = xml.childNodes[i];
		if (node) {
		    var id = node.getAttribute("id");
		    var severity = interactions['I' + id];
		    var severityCount = interactionsCount['I' + id];
		    // this implies there were no interactions to even search for.
		    //          if (! severityCount) { break; }
		    if (severityCount) {
			searchCount += severityCount;
			if (severity == "SEVERE") {
			    severeCount += severityCount;
			}
			else if (severity == "SERIOUS") {
			    seriousCount += severityCount;;
			}
			else if (severity == "MODERATE") {
			    moderateCount += severityCount;;
			}
		    }
		}
	    }
	}
	if (searchStatDiv) {
	    searchStatDiv.innerHTML = "Search: " + searchCount + " hits";
	    if (searchCount > 0) {
		searchStatDiv.innerHTML += " - ";
		if (severeCount > 0) {
		    searchStatDiv.innerHTML += severeCount + " Severe";
		}
		else if (seriousCount > 0) {
		    searchStatDiv.innerHTML += seriousCount + " Serious";
		}
		else if (moderateCount > 0) {
		    searchStatDiv.innerHTML += moderateCount + " Moderate";
		}
		else {
		    searchStatDiv.innerHTML += searchCount + " Unknown";
		}
	    }
	}
    }
    else {
	searchStatDiv.innerHTML = "";
    }
}

// update search summary for contraindications
function setContraSearchSummary() {
    var searchStatDiv = getSearchSummaryRegion('contraindicationsSearchStats');
    if (delimitedSearchTerm && delimitedSearchTerm != EMPTY_STRING) {
	if (searchStatDiv) {
	    var grid;
            for (var i = 0; i < Grids.length; i++) {
		grid = Grids[i];
		if (grid.id == "contra_grid") {
		    break;
		}
	    }

	    if (grid) {
		var body = grid.XB;
		
		var row = grid.GetFirst(body, 0);
		row = grid.GetNext(row, 0);
		var searchCount = 0;
		
		while (row) {
		    if (row.Visible) {
			var desc = grid.GetValue(row, "D");          
			var advisory = grid.GetValue(row, "A");          
			var found = testSearchValue(desc, false) || testSearchValue(advisory, false);
			if (found) {
			    searchCount++;
			}
		    }
		    row = grid.GetNext(row, 0);
		}
		
		searchStatDiv.innerHTML = "Search: " + searchCount + " hits";
	    }
	}
    }
    else {
	if (searchStatDiv) {    
	    searchStatDiv.innerHTML = "";
	}
    }
}


// fetches either tha named region or if the named region isn't found
// a default region.
function getSearchSummaryRegion(regionName) {
    var searchStatDiv = document.getElementById(regionName);
    if (!searchStatDiv) {
	searchStatDiv = document.getElementById("mapSearchStats");
    }
    return searchStatDiv;
}

// update search summary for side effects
function setSideEffectsSearchSummary() {

    var searchStatDiv = getSearchSummaryRegion('sidEffectsSearchStats');
    if (delimitedSearchTerm && delimitedSearchTerm != EMPTY_STRING) {
	var grid = Grids[0];
	var body = grid.XB;
	
	var row = grid.GetFirst(body, 0);
	row = grid.GetNext(row, 0);
	var searchCount = 0;
	var criticalCount = 0; 
	var minorCount = 0;
	while (row) {
	    if (row.Visible) {
		var desc = grid.GetValue(row, "D");  
		if (testSearchValue(desc, false)) {
		    searchCount++;
		    var col = grid.GetValue(row, "N");
		    if (col == "Critical") {
			criticalCount++;
		    }
		    else if (col == "Minor") {
			minorCount++;
		    }
		}
	    }
	    row = grid.GetNext(row, 0);
	}
	
	if (searchStatDiv) {
	    searchStatDiv.innerHTML = "Search: " + searchCount + " hits";
	    if (searchCount > 0) {
		searchStatDiv.innerHTML += " - ";
		if (criticalCount > 0) {
		    searchStatDiv.innerHTML += criticalCount + " Critical";
		}
		else if (minorCount > 0) {
		    searchStatDiv.innerHTML += minorCount + " Minor";
		}
		else {
		    searchStatDiv.innerHTML += searchCount + " Unknown";
		}
	    }
	}
    }
    else {
	if (searchStatDiv) {
	    searchStatDiv.innerHTML = "";
	}
    }
}

// Converts a string into an XML dom object.
function StringtoXML(text){
   if (window.ActiveXObject){
       var doc=new ActiveXObject('Microsoft.XMLDOM');
       doc.async='false';
       doc.loadXML(text);
   } else {
       var parser=new DOMParser();
       var doc=parser.parseFromString(text,'text/xml');
   }
   return doc;
}

// change any interaction monograph to red if it matches a search
function processInteractionMonographSearch2 (transport) {
    var monos = (transport  && transport.responseXML)?transport.responseXML.firstChild:null;
    var intRegion = document.getElementById("intRegion");
    if (intRegion) {
	var grid = Grids[1];
	var body = grid.XB;
	
	var row = grid.GetFirst(body, 0);
	var intIdPat = /interactionid="([0-9]*)"/i;
	
	while (row) {
	    var col = grid.GetValue(row, "D");
	    
	    if (col != "" && col != null) {
		var myArray = intIdPat.exec(col);
		var intId = myArray[1];
		var m = getXMLById(intId, monos);
		if (m) {
		    col = col.replace("mono.gif", "mono_red.gif");
		}
		else {
		    col = col.replace("mono_red.gif", "mono.gif");
		}
		grid.SetValue(row, "D", col, true);
	    }  
	    row = grid.GetNext(row, 0);
	}
    }
    setInteractionSearchSummary2(monos);
}

// highlight a tab if there are matching search results in the tab
// we highlight by turning the tab text to red
function highlightMonographTabs(transport) {
   var response = transport.responseXML;
   var drugs = response.firstChild;
   for (i = 0; i < drugs.childNodes.length; i++) {
     var drug = drugs.childNodes[i];
     for (j = 0; j < drug.childNodes.length; j++) {
       var section = drug.childNodes[j];
       var sectionName = section.getAttribute("name");
       if (sectionName == "contraindications") {
           sectionName = "precautions"
       }   
       var e = document.getElementById(sectionName + "Tab");
       e.style.color = "red";
     }
   }

   
}

// change any drug monograph to red that has tabs that match
// the search parameters
function processMonographSearch2(transport) {
   var response = transport.responseXML;
   var drugs = response.firstChild;
   for (var i in monographMeds) {
        if (i) {
	    var monographNames = ["drugMonographse" + monographMeds[i], "drugMonographint" + monographMeds[i], "drugMonographcontra" + monographMeds[i]];
           i = i.substring(1);
           var drug = getXMLById(i, drugs);
           var newImage = getImagePrefix() + 
	       "themes/theme_106/" + 
	       ((drug && hasMoreThanSideEffectsRisks(drug))?"mono_red.gif":"mono.gif");

           for (var j = 0; j < monographNames.length; j++ ) {
	       var monograph = document.getElementById(monographNames[j]);
               if (monograph) {
	          monograph.src = newImage;
	       }
	   }
       }
   }
}

// clear all drug monographs
function clearMonographSearch(mapTypeSearched) {
   for (var i in monographMeds) {
        if (i) {
           var monographName = "drugMonograph" + mapTypeSearched  + monographMeds[i];
           var monograph = document.getElementById(monographName);
	   if (monograph) {
	       monograph.src = getImagePrefix() + 
		   "themes/theme_106/mono.gif";
	   }
        }
   }

   // if interaction map is being cleared then also clear interaction monographs
   if (mapTypeSearched == "int") {
       var grid = Grids[1];
       var body = grid.XB;
       
       var row = grid.GetFirst(body, 0);
       while (row) {
	   var col = grid.GetValue(row, "D");

	   if (col != "" && col != null) {
	       col = col.replace("mono_red.gif", "mono.gif");
	       grid.SetValue(row, "D", col, true);
	   }  

	   row = grid.GetNext(row, 0);
       }
   }
}

// caluculate which tab should be active when a monograph is
// opened, this is based on which section of the map the user is
// currently in.
function defaultDrugMonographSection() {
   var mapSection = getMapSection();
   var section = "SIDEEFFECTS";

   if (mapSection == "Interactions") {
       section = "INTERACTIONS";
   }
   else if (mapSection == "Contraindications") {
       section = "PRECAUTIONS";
   }

   return section;
}

// return true if the search matches more than just the
// side effects risks tab
function hasMoreThanSideEffectsRisks(drug) {
   var result = false;
   for (var i = 0; i < drug.childNodes.length; i++) {
     var s = drug.childNodes[i];
     if (s.getAttribute("name") != "conditions") {
         result = true;
         break;
     }
   }
   return result;
}

// given a drug create a "-" string of each section that
// has a search match
function getDrugMonographSections(drug) {
   var section = "";
   for (i = 0; i < drug.childNodes.length; i++) {
     if (section != "") { 
         section += "-";
     }
     var s = drug.childNodes[i];
     section += s.getAttribute("name");
   }
   return section;
}

// search an xml document for a node with the given id attribute
function getXMLById(id, xml) {
   if (xml) {
      for (var i = 0; i < xml.childNodes.length; i++) {
          var node = xml.childNodes[i];
          if (node) {
             var tmpId = node.getAttribute("id");
             if (tmpId  == id) {
                return node;
             }
          }
      }
   }   
   return false;
}


// show a div with name popupDivName that is
// located just below the parent element specified.
function showDivBelowParent(event, element, popupDivName, shiftLeft, upShift) {
    var parentNode = element.parentNode;
    var h = (element.clientHeight)?element.clientHeight:(element.scrollHeight + 2);
    var div = document.getElementById(popupDivName);

    var left = getLeft(element);
    if (shiftLeft) {
	left -= shiftLeft;
    }
    div.style.left = left + 'px';
    div.style.top = (getTop(element) + h + ((upShift)?upShift:0)) + 'px';
    div.style.display = "inline";
}

// show the Health 2.0 Accelerator level one panel
function showH2ALevelOne(event, element, memberName) {
    var one = document.getElementById("h2apanell1");
    var two = document.getElementById("h2apanell2");
    if (! isIE()) {
       one.style.width="150px";
       two.style.width="150px";
    }

    getLevelOneData(memberName);
    showDivBelowParent(event, element, 'h2apanell1');
}

// get the data from freebase that is used in the 
// Health 2.0 Accelerator level one panel
function getLevelOneData(memberName) {
    var envelope = {                       
        query : [{
           "type": "/base/health20accelerator/member",
           "name": memberName,
           "complemented_by": [{
              "supported_task": [{
                 "name":         null,
                 "display_name": null
              }]
          }]
       }]
    };

    var envelopeString = JSON.stringify(envelope);
   // Invoke mqlread and call the function below when it is done.
    // Adding callback=? to the URL makes jQuery do JSONP instead of XHR.
    jQuery.getJSON("http://api.freebase.com/api/service/mqlread?callback=?",
                   {query: envelopeString},   // URL parameters
                   displayLevelOneResults);    


    var panel = jQuery("#h2apanel1results");
    panel.html("");

    // This function is invoked when we get the result of our MQL query
    function displayLevelOneResults(response) {  
        if (response.code == "/api/status/ok" && response.result) { 
            var complements = response.result[0].complemented_by;
            var unique = {};

            for (var i = 0 ; i < complements.size(); i++) { 
                var tasks = complements[i].supported_task;
                for (var j = 0; j < tasks.size(); j++) {
                   var task = tasks[j];
                   if (unique[task.name] != 1) {
                      panel.append("<a href=\"javascript:showH2ALevelTwo('"+ memberName + "', '" + task.name+ "', '" + task.display_name+ "')\">" + task.display_name + "</a><br/>"); 
                      unique[task.name] = 1;
                   }
                }
            }

        }
        else {                                          
            panel.append("None");   
        }
        panel.show();
    }     
}

// show the Health 2.0 Accelerator level two panel
function showH2ALevelTwo(partnerName, taskName, displayName) {
    var levelTwo = jQuery("#h2apanell2");
    var levelOne = jQuery("#h2apanell1");
    var parentNode = document.getElementById("h2apanell1");
    var childNode = document.getElementById("h2apanell2");
    childNode.style.top = (getTop(parentNode) + 10) + 'px';
    childNode.style.left = (getLeft(parentNode) - 10) + 'px';

    var offset = levelOne.offset();
    getLevelTwoData(partnerName, taskName, displayName);

    levelTwo.show();
}


// get the data from freebase that is used in the 
// Health 2.0 Accelerator level two panel
function getLevelTwoData(memberName, taskName, displayName) {
    var envelope = {                       
        query : [{
          "type": "/base/health20accelerator/member",
          "name": memberName,
          "complemented_by": [{
             "supported_task": taskName,
             "name":          null,
             "service_url":   null
          }]
        }]
    };

    var envelopeString = JSON.stringify(envelope);
   // Invoke mqlread and call the function below when it is done.
    // Adding callback=? to the URL makes jQuery do JSONP instead of XHR.
    jQuery.getJSON("http://api.freebase.com/api/service/mqlread?callback=?",
                   {query: envelopeString},   // URL parameters
                   displayLevelTwoResults);    

    var panelTitle = jQuery("#h2apanel2title");
    panelTitle.html(displayName);

    var panel = jQuery("#h2apanel2results");
    panel.html("");

    // This function is invoked when we get the result of our MQL query
    function displayLevelTwoResults(response) {  
        if (response.code == "/api/status/ok" && response.result) { 
            var complements = response.result[0].complemented_by;

            for (var i = 0 ; i < complements.size(); i++) { 
                var comp = complements[i];
                panel.append("<a href=\"" + comp.service_url + "\" target=\"_new\">" + comp.name + "</a><br/>"); 
            }

        }
        else {                                          
            panel.append("None");   
        }
        panel.show();
    }     
}

function removeAllMeds() {
  if (confirm("Do you really want to remove all meds for comparison?")) {
     var compareTable = document.getElementById('compareListReportTable');
     var rows = compareTable.tBodies[0].rows;

     var minRows = getPageNumber()=='4004'?2:1;

     if (rows.length > minRows) {
        removeAllCompareMedsDB();
     }
     while (rows.length>minRows) {
        var link = rows[minRows].cells[0].childNodes[0];
        var href = link.getAttribute("href");
        var id = href.substring(href.indexOf("(")+1, href.indexOf(")"));
        removeCompareMedRow(id);
        changeCheckBoxCompareState(id+"cb");
     }
  }
}

// add all meds current displayed to the comparison list
function addAllMeds() {
   var reportTable = document.getElementById('reportTable'); 
   var sTable = reportTable.tBodies[0].rows[1].cells[0].childNodes[0];
   var rows = sTable.tBodies[0].rows;
   var medsToAdd = '';
   for (var i = 1; i < rows.length; i++) {
      var cell = rows[i].cells[2];
      var img = cell.childNodes[0].childNodes[0];
      if (img) {
         var id = img.id;
         var medId = id.substring(0, id.length-2);
         if (medNotAddedYet(id)) {
            medsToAdd += medId + ",";
            changeCheckBoxCompareState(id);
            addCompareMedRow(medId);
         }
      }
   }

   if (medsToAdd != '') {
     addAllCompareMedsDB(medsToAdd.substring(0, medsToAdd.length-1));
   }
}

// update the db to know that all meds have been removed from the compare lists
function removeAllCompareMedsDB() {
     var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=REMOVE_ALL_COMPARE_MEDS',0);
     gReturn = get.get('XML');
}

// update the db with all the med ids
function addAllCompareMedsDB(ids) {
     var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=ADD_COMPARE_MEDS',0);
     get.add('TF_MED_IDS', ids);
     gReturn = get.get('XML');
}

// switch checkbox state from checked/uncheckedk and remove or add
// the drug from the comparision list (both the html version and the db)
function switchCompareMedState(medId) {
   var element = document.getElementById("P4007_REGEN_SURVEY");
   if (element) {
      element.value = "TRUE";
   }

   if (changeCheckBoxCompareState(medId+"cb")) {
       addCompareMedDB(medId);
       addCompareMedRow(medId);
   }
   else {
        removeCompareMedDB(medId);
        removeCompareMedRow(medId);
   }
}

// remove the html row of the drug with medid 
// from the compare list 
function removeCompareMedRow(medId) {
   var row = document.getElementById(medId + "row");
   var parentNode = row.parentNode;
   parentNode.removeChild(row);
}

// add a new row to the compare list with medId, the text 
// for the new row is gathered dynamically from the 
// list of meds and inserted in alpha order.
function addCompareMedRow(medId) {
   var compareTable = document.getElementById("compareListReportTable");

   var newRow = document.createElement('tr');
   newRow.id = medId + 'row';
   var newCell = document.createElement('td');
   newCell.className = "t106data";
   newCell.setAttribute("align", "center");
   newCell.innerHTML = '<a href="javascript:switchCompareMedState(' +
                        medId + ')"><img src="' + htmldb_Img_Dir + 
                       'themes/theme_106/checkmark.gif"/></a>';
   newRow.appendChild(newCell);
   newCell = document.createElement('td');
   newCell.className = "t106data";
   drugName = document.getElementById(medId+"cb");
   drugName = drugName.parentNode.parentNode.nextSibling;
   drugName = drugName.innerHTML;
   newCell.innerHTML = drugName;
   newRow.appendChild(newCell);
   var tbody = compareTable.tBodies[0];

   var minRow = getPageNumber()=="4004"?2:1;

   if (tbody.rows.length <= minRow) {
       tbody.appendChild(newRow);
   }
   else {
       for (i = minRow; i < tbody.rows.length; i++) {
          var curName = tbody.rows[i].cells[1];
          if ( curName.innerHTML.toUpperCase() > drugName.toUpperCase() ) {
              tbody.insertBefore(newRow, tbody.rows[i]);
              break;
          }
          else if (i == tbody.rows.length-1) {
              tbody.appendChild(newRow);
          } 
        }
   }
}

// return true if the checkboxId has already been added indicated
// by the fact that it is checked
function medNotAddedYet(checkboxId) {
     var theImage = document.getElementById(checkboxId);
     var checked = false;
     if (theImage) {
        checked = theImage.src.match(matchNotChecked);
     }
     return checked;
}

// switch between a unchecked checkbox and a checked checkbox
function changeCheckBoxCompareState(checkboxId) {
     var theImage = document.getElementById(checkboxId);
     var checked = false;
     if (theImage) {
        if (theImage.src.match(matchNotChecked)) {
           theImage.src = 
              theImage.src.replace(matchNotChecked, "checkmark.gif");
           checked = true;
        }
        else {
           theImage.src = 
              theImage.src.replace(matchChecked, "checkmark-notcheck.gif");
           checked = false;
        }
     }
     return checked;
}


// add a single medication (medId) to the 
// compare list in the db
function addCompareMedDB(medId) {
     var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=ADD_COMPARE_MED',0);
     get.add('TF_MED_ID', medId);
     gReturn = get.get('XML');
}

// add a single medication (medId) from the 
// compare list in the db
function removeCompareMedDB(medId) {
     var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=REMOVE_COMPARE_MED',0);
     get.add('TF_MED_ID', medId);
     gReturn = get.get('XML');
}

// switch the hint state (open or closed) in the database
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();
}

// switch the hint subsection state (open or closed) in the database
function switchHintSubSectionState(hintSubsectionId, hintSectionId) {
      var get = new htmldb_Get(
        null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=SWITCH_HINT_SUBSECTION_STATE',0);
      get.add('TF_HINT_SUBSECTION_ID', hintSubsectionId);
      get.add('TF_HINT_SECTION_ID', hintSectionId);
      var section = get.get();
}


// switch hint state in both DB and html
function hideOrShowHint(hintId, hintSectionId) {
   hideOrShowElement("hint" + hintId);
   switchHintState(hintId, hintSectionId);
}

// switch hint subsection state in both DB and html
function hideOrShowHintSubsection(hintSubsectionId, hintSectionId) {
   var action = hideOrShowElement("subsection" + hintSubsectionId);
   var div = document.getElementById("subsectionTitle" + hintSubsectionId);
   var image = document.getElementById("subsectionImage" + hintSubsectionId);

   if (action == "show") {
       div.className = 'sh1HintsSubHeader sh1HintsSubHeaderOpened';
       image.src = getImagePrefix() + "themes/theme_106/hints_opened_arrow.gif";
   }
   else {
       div.className = 'sh1HintsSubHeader sh1HintsSubHeaderClosed';
       image.src = getImagePrefix() + "themes/theme_106/hints_closed_arrow.gif";
   }
   switchHintSubSectionState(hintSubsectionId, hintSectionId);
}

// get current style of an element. 
// this looks through the css definitions
function getStyle(oElm, strCssRule){
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}


// if the element exists then show it
function showElement(elementName) {
    var region = document.getElementById(elementName);
    if (region) {
	region.style.display = "inline";
    }
}

// if the element is visible then hide it
// if it is hidden then show it
function hideOrShowElement(elementName, show) {
    var region = document.getElementById(elementName);
    if (region) {
       var style = getStyle(region, 'display');
       if (style == 'none') {
          if (show) {
             region.style.display = show;
          }
          else {
             region.style.display = "";
          }
          return "show";
       }
       else {
          region.style.display = "none";
          return "hide";
       }
    }
} 

// hide the the element/region
function hideRegion(regionName) {
    var region = document.getElementById(regionName);
    if (region) { region.style.display = 'none'; }
}

// perform the selected action (save, copy, etc)
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');
    }
    else if (optionValue =="MERGE_INTO_EMR") {
         importInto(getAppId(), null, null); 
    }
}

// hides the import map it setting div
function closeImportMapItSettingDiv() {
    var div = document.getElementById('selectMapItStateDiv');
    div.style.display = "none";
    document.getElementById('wholePage').style.display = "none";
}

// show div that starts the import process from the current
// med list to a new or existing list
function enableImportDiv(divName) {
   var div = document.getElementById(divName);
   if (div) {
       div.style.display = "inline";
       document.getElementById('wholePage').style.display = "inline";
   }
}

// save a new survey, check that it has a description first
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");
   }
}

// hide all the divs possibly opened as part 
// of the save process and revert field values to defaults
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";
   document.getElementById("importFromReferenceDiv").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 = '';

}

// show the div that has controls to do a med list "save as"
function enableSaveAsDiv() {
   var div = document.getElementById("saveSurveyAs");
   if (div) {
       div.style.display = "inline";
       document.getElementById('wholePage').style.display = "inline";
   }

}

// display tooltip for side effects severity rollover
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');
}

// display rollover that lets the user know the condition
// or medication already exists in the medlist
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');
}

// display tooltip for contraindication severity rollover
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');
}

// display tooltip for pregnancy precaution severity rollover
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);
}

// display tooltip for general precautions severity rollover
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);
   }
}

// display tooltip for interaction severity rollover
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');
}

// get the scroll width of the entire browser window
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;
} 

// get the left coordinate for the window
function windowLeftCord() {
    var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;

    return document.all? iebody.scrollLeft : pageXOffset;
}

// prevents IE from making ding noise when enter is pressed 
// while a field has focus
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 that does nothing, 
// useful for other methods to call
function nothing() { return; };

// run abbey's survey asyncronously
function runAbbySurvey(isAbbySurvey) {
   if (isAbbySurvey == 'TRUE') {
     var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=generateNewAbbySurvey',0
     );
     gReturn = get.GetAsync(nothing);
   }

}

// checks if abby's survey is done runninging
// if it is done then enable the button to view
// results, if not then schedule another check for later
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;
 }

// prevents return from submiting the page
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;}
} 

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;
 }

// return true if the record exists
 function recordDoesNotExist(recordName, recordType) {
    return objectDoesNotExist(recordName, "recordDoesNotExist", recordType);
 }

// return true if the medlist exists
 function medlistDoesNotExist(listName, recordId) {
    return objectDoesNotExist(listName, "medlistDoesNotExist", recordId);
 }

// return true if the object does not exists
 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 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]);
     } 
   }
 }

//set a field color style to the given color
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;
}


// hide and show a collapsible region
// update database with current state
function switchCollapsibleRegionState(id) {
   var result = hideOrShowElement(id + "opened", "block");
   result = hideOrShowElement(id + "closed", "block");
   result = hideOrShowElement(id + "buttons", "block");
   result = hideOrShowElement(id + "body", "block");

   var get = new htmldb_Get(
      null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=SWITCH_MEDLIST_STATE',0);

   get.add('TS_MEDLIST_SECTION', id);

   gReturn = get.get('');
}

// hide and show a medlist section, 
// update database with current state
function switchMedlistAccordion(id) {
   var result = hideOrShowElement("medlistSection" + id, "inline");
   var image = document.getElementById("medlistImage" + id);

   if (image) {
      if (result == "show") {
         image.src = getImagePrefix() + 
                     "themes/theme_106/region-opened-arrow.gif";
      }
      else {
         image.src = getImagePrefix() +
                     "themes/theme_106/region-closed-arrow.gif";
      }  
   }

   var get = new htmldb_Get(
      null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=SWITCH_MEDLIST_STATE',0);

   get.add('TS_MEDLIST_SECTION', id);

   gReturn = get.get('');
}

// causes the page to refresh the the exact same url
function refresh() {
    window.location.href = window.location.href;
}

// 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, pageId, hasErrors) {

  if ((pageId != 4003 && pageId != 4006) || ((pageId == 4003 || pageId == 4006) && hasErrors != "TRUE")) {
     var requested = getItem('AI_PAGE_REQUESTED', appId, sessionId);

     if (requested == "NO") {
         refresh();
     }
     else {
         setItem('AI_PAGE_REQUESTED', "NO",appId, sessionId);
     }
  }
}

// move search box to a new location
// this is required because apex makes it hard
// to put items in arbitrary places 
// (unless you have region positions to spare)
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 = '';
}

// display the search box in its current location (don't move it)
function showSearchBox() {
    var riskTab=document.getElementById("risk_tab");    
    var searchField=document.getElementById("search_field");    
    riskTab.style.display = "inline";
    searchField.style.display = "inline";

}

// move the number of rows to display drop down to the bottom of the report
// if there are fewer rows than the max number of displayable rows then don't
// show the select list to select a different set of rows
function moveNumRowsToDisplayToTable(div, rowsToDisplayName, maxRowsWithoutSearch, rowCount) {
     moveNumRowsToDisplayToTableBool(div, rowsToDisplayName, rowCount > maxRowsWithoutSearch);
}

// move the number of rows to display drop down to the bottom of the report
// if showSelect is true then display the select list that allows the user
// to select a different set (range) of rows
function moveNumRowsToDisplayToTableBool(div, rowsToDisplayName, showSelect) {
     if (div) {
        var numRowSelectRegion = document.getElementById(rowsToDisplayName);
        var table = div.getElementsByTagName('table')[0];
        var numRowSelectRegion = document.getElementById(rowsToDisplayName);
        var table = div.getElementsByTagName('table')[0];
        if (table) {
           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 = "";
           }
	}
     }
}

// move the compare list of meds to a new location. This is done
// because without spare region positions we couldn't get
// the list where we wanted it at at page render time
function moveCompareList() {
   var sourceDiv = document.getElementById('compareMedListSource');
   var destDiv = document.getElementById('compareMedListDest');
   if (sourceDiv && destDiv) {
      destDiv.innerHTML = sourceDiv.innerHTML;
      sourceDiv.innerHTML = '';
   }
}

// add custom sort arrows to any of the "merge" tables that exist
function addSortArrowsToMergeTables(imageDirectory) {
     addSortArrowsToTable('mergetoreference', imageDirectory);
     addSortArrowsToTable('mergetomedcabinet', imageDirectory);
     addSortArrowsToTable('mergetargetlist', imageDirectory);
}

// add custom sort arrows to any of the medlist tables that exist
function addSortArrowsToMedListTables(imageDirectory) {
     addSortArrowsToTable('basicmedlistreport', imageDirectory);
     addSortArrowsToTable('activemedlistreport', imageDirectory);
     addSortArrowsToTable('proposedmedlistreport', imageDirectory);
     addSortArrowsToTable('inactivemedlistreport', imageDirectory);
     addSortArrowsToTable('conditionlistreport', imageDirectory);
     addSortArrowsToTable('actionplanlistreport', imageDirectory);
     addSortArrowsToTable('concernslistreport', imageDirectory);

}

// add custom sort arrows to a report. mainly linda
// wanted a different type of arrow for the sorted column
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 == "SPAN") { return; }

         if (outterTable.nodeName != "TABLE") {
            outterTable = document.getElementById("reportTable");
         }
         if (!outterTable || outterTable.nodeName == "SPAN") {
            return;
         }

         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 (anchor.nodeName != "A") {
		    anchor = anchor.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];
		   if (!img) {
		       img = header.childNodes[0].childNodes[1];
		   }
                   anchor.appendChild(img);
                }  
             }
         }
      }      
      catch (e) { return; }
   }
}

// start the import process
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");
}

// start the import process
function importFrom(recordId, medListId) {
   document.getElementById('P0_IMP_RECORD_ID').value = recordId;
   document.getElementById('P0_IMP_MED_LIST_ID').value = medListId;
   doSubmit("IMPORT_FROM_MEDLIST");
}


// open div that let's user choose which refrence list to import from
function openReferenceListSelector() {
    var div = document.getElementById("importFromReferenceDiv");
    div.style.display="inline";
    document.getElementById('wholePage').style.display = "inline";
}

// display div that contains controls appopriate for editing a med list
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>";
       }
       if (userType != 'EXTERNAL') {
          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/>";
       } 
       else if (recordType == 'R') {
               region.innerHTML += "<div class=\"saveOption\"><a href=\"javascript:takeSurveyEditAction('" + surveyId + "', 'MERGE_INTO_EMR');\">Merge Meds into EMR Data</a></div>";

               region.innerHTML += "<br/><br/>";
       }

       region.innerHTML +=
            "<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') && getRecordType() != 'E' && (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') && getRecordType() != 'E' && (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;

// show informational rolloer for the current interaction
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);
}

var curConditionId = null;
var curMedicationId = null;
var curConditions = null;
var curMedications = null;

// open the page the shows what conditions are treated by the current med.
function gotoConditionsTreatedByMed(appId) {
     window.location =
         "f?p="+appId+
         ":4029:0:::RP,4029:AI_ORIGINATING_PAGE,P4029_MEDICATION_ID:4003,"+curMedicationId;
}

// open the page that shows what medications treat the current condition
function gotoMedsTreatingCondition(appId) {
     window.location = 
         "f?p="+appId+
         ":4023:0:::RP,4023:AI_ORIGINATING_PAGE,P4023_CONDITION_ID:4003,"+curConditionId;
}

// show context menu for ading conditions to a drug
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);
}

// open the page that shows what conditions are treated by the current medication
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);
}

// display the "select" rollover from the alternate selection page comparison map
function showSelectAltMenu(event, element, oName, oId, leftOffset) {
    var notInList = document.getElementById('mednotinlist');
    var inList = document.getElementById('medalreadyinlist');
    if (currentMedsArray["R" + oId] == 1) {
	notInList.style.display = "none";
        inList.style.display = "";
    }
    else {
	notInList.style.display = "";
        inList.style.display = "none";
    }

     var div = document.getElementById("alternateMedName");
     if (div) { div.innerHTML  = oName; }

     var pick = document.getElementById('mednotinlist');
     var existAlready = document.getElementById('medalreadyinlist');

     if (currentMedsArray["R" + oId]) {
          pick.style.display = "none";
          existAlready.style.display = "";
     }
     else {
          pick.style.display = "";
          existAlready.style.display = "none";
     }

     if (getPageNumber() == '4007') {
         var cell = document.getElementById("altRolloverSubHeader");
         cell.style.display = "none";
         cell = document.getElementById("altRolloverSubInfo");
         cell.style.display = "none";
         var text = document.getElementById('atlSelectText');
         if (text) {
            text.innerHTML = 'Add Med';
         }
     }

     showMenuDelayed(event, element, oName, oId, leftOffset, "changeDrugTitle", "selectAltPopup", 260, 500);
}

// select the current drug as the new alternate med
function selectCurrentDrug() {
    hideRegion('selectAltPopup');

    if (getPageNumber() == '4004') {
	replaceDrug(curDeleteId, curDeleteName);
    }
    else {
	addMed(curDeleteId, curDeleteName);
    }
}

// display the "edit" rollover menu for a drug
function showEditDrugMenu(event, element, deleteName, deleteId, leftOffset, groupName, medStartDate, replacedMedId, replacedMedicationDesc) {
     var width = 260;
     var groupCell = document.getElementById('changeDrugGroup');
     groupCell.innerHTML = groupName;
     if (medStartDate != "" && medStartDate != null) {
        groupCell.innerHTML += "<br/>Start Date: " + medStartDate;
     }

     if (getRecordType() == 'E') {
       width = 310;
       var row = document.getElementById("deleteMedRolloverOption");
       if (groupName == 'Active Meds' || groupName == 'Inactive Meds') {
          row.style.display = "none";
       }
       else {
          row.style.display = "";
       }
       if (groupName == 'Active Meds') {
          row = document.getElementById("actionPlanRolloverPrescribe");
          row.style.display = "none";
          row = document.getElementById("actionPlanRolloverUnprescribe");
          row.style.display = "";
          row = document.getElementById("actionPlanRolloverReplace");
          row.style.display = "none";
          if (replacedMedId == null || replacedMedId == '') {
              row = document.getElementById("actionPlanRolloverReplace");
              row.style.display = "none";
          }
          else {
              row = document.getElementById("actionPlanRolloverReplace");
              row.style.display = "";
              var div = document.getElementById("replaceCurrentMedName");
              div.innerHTML = deleteName;
              div = document.getElementById("replaceAlternateMedName");
              div.innerHTML = replacedMedicationDesc;
          }
       }
       else {
          row = document.getElementById("actionPlanRolloverUnprescribe");
          row.style.display = "none";
          row = document.getElementById("actionPlanRolloverPrescribe");
          row.style.display = "";
          if (replacedMedId == null || replacedMedId == '') {
              row = document.getElementById("actionPlanRolloverReplace");
              row.style.display = "none";
          }
          else {
              row = document.getElementById("actionPlanRolloverReplace");
              row.style.display = "";
              var div = document.getElementById("replaceCurrentMedName");
              div.innerHTML = replacedMedicationDesc;
              div = document.getElementById("replaceAlternateMedName");
              div.innerHTML = deleteName;
          }
       }
     }
     else {
        var row = document.getElementById("actionPlanRolloverHeader");
        row.style.display = "none";
        row = document.getElementById("actionPlanRolloverPrescribe");
        row.style.display = "none";
        row = document.getElementById("actionPlanRolloverUnprescribe");
        row.style.display = "none";
        row = document.getElementById("actionPlanRolloverReplace");
        row.style.display = "none";

     }

     showMenuDelayed(event, element, deleteName, deleteId, leftOffset, "changeDrugTitle", "editMedPopup", width, 500);
}

// display the "edit" rollover menu for a condition
function showEditCondMenu(event, element, conditionName, conditionId, leftOffset) {
     showMenuDelayed(event, element, conditionName, conditionId, leftOffset, "changeCondTitle", "editCondPopup", 0, 500);
}

// shows the first step menu, the other steps don't have special functions. this one
// this one requires ones because in IE the medication field cursor would bleed
// through and show up in the menu unless the field is disabled
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;
   }

}

// close any other menu that is open
// then after a very brief delay open the specified menu
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);
}

// immediately show a div
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;
}

// closes either the specified div or the current div
function closeCurrent(popupDivName) {

  if (! popupDivName) {
     popupDivName = curDivName;
  }
  if (popupDivName) {
     timer = true;
     closePopup(curElement, curDivName);
  }
}

// close the specified div
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";
  }
}

// after a delay close the popup
// the closing will be cancelled if the mouse
// moves back over the popup
function closePopupCountDown(element, popupDivName, delay) {
   if (!delay) { delay = 500; }
   curPopupId = null;
   var func_def = "closePopup(curElement, '" + popupDivName + "')";
   timer = true;
   setTimeout(func_def, delay);
}

// get coordinate of left border of an elmeent
function getLeft(element) {
    if (element.offsetParent) {
       return element.offsetLeft + getLeft(element.offsetParent);
    }
    else {
       return 0;
    }
}

// get coordinate of top border of an element
function getTop(element) {
    if (element.offsetParent) {
       return element.offsetTop + getTop(element.offsetParent);
    }
    else {
       return 0;
    }
}

// return true if containee is a child of container
function containsDOM (container, containee) {
  var isParent = false;
  do {
    if ((isParent = container == containee))
      break;
    containee = containee.parentNode;
  }
  while (containee != null);
  return isParent;
}

// return true if mouse has entered the element
function checkMouseEnter (element, evt) {
  if (element.contains && evt.fromElement) {
    return !element.contains(evt.fromElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

// return true if mouse has left the element
function checkMouseLeave (element, evt) {
  if (element.contains && evt.toElement) {
    return !element.contains(evt.toElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

// add custom sort arrows to the map tables
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;
      var headerTitle = cell.innerHTML;
      // interaction, side effect column
      var image = (colNum == 6 || colNum==7)?"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>";
      
   }
 }
}

// prepare the map table for finally viewing in app 600. 
// This basically moves around elements that apex would
// not allow us to place where we wanted and set up
// custom sort funcationality
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();
}

// add label next to the search fields (for app 600)
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;

}

// set colspan for header based on number of drugs in the survey
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);
    }
  }
}

// hide the pagination count if all the rows shows up in the current page
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";
      }
    }
}

// relocate the pagination at the top of the region to the bottom 
// apex puts it at the top, but we want it at the bottom
// specific to app 600
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 = '';
}

// set background color for each cell in the survey
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;
          }
        }
    }
 }
}

// open a printer friendly version of the page
// in a new window
function printPage(appId, pageNum, sessionId) {
     var address = "f?p=" + appId + ":" + pageNum + 
	":0::::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();
}

// open a printer friendly version of the page
// with all MRM accordions open 
function printMRMReport() {
     var address = "f?p=" + getAppId() + ":" + getPageNumber() + 
        ":0::::AI_PRINTER_FRIENDLY,AI_OPEN_ALL_ACCORDIONS:YES,YES";
     var myWindow =
     window.open (address,
"print","location=0,status=1,scrollbars=1,menubar=1,toolbar=0, height=950, width=900");
     myWindow.focus();
}

// open informational window (usually a link to an external site)
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();

}

// open partner website in a new window
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();

}


// open static file in a new window	
function openFile(address) { 
     var myWindow = 
     window.open (address,
"","location=1,status=1,scrollbars=1,menubar=1,toolbar=1,height=600, width=800");
     myWindow.focus();

}

// parse the given HTML and extract the medication names from it
function getMedicationsFromHTML(medRow, firstMedIndex) {
    var medNames = [];
    var j = 0;
    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[j++] = html;
    }
    return medNames;
}

// parse HTML table rows for section names of each medication
function getMedSections(medRow, firstMedIndex, medIDs) {
    var medSection = [];
    var j = 0;
    for (var i = firstMedIndex; i < medRow.cells.length; i++) {
       var element = document.getElementById("MEDINFO" +medIDs[i+1]);
       if (element) {
          medSection[j++] = element.getAttribute("medsection");
       }
    }
    return medSection;
}

// parse the HTML table rows for ids of each medication
function getMedicationIDsFromHTML(medRow, firstMedIndex) {
    var medIDs = [];
    var j = 0;
    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[j++] = html;
    }
    return medIDs;
}

// parse HTML table rows for section names of each medication
// specific to app 600 html
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;
}

// set the mouse over event for contraindications
function setAllContraMouseovers(imageDirectory) {
 var x=document.getElementById("innerSurveyTable");
 var tableBody = x.tBodies[0];
 var medicationRow = x.tHead.rows[1];
 var medNames = getMedicationsFromHTML(medicationRow, 2);
 var medName;
 for (var i = 1; i < tableBody.rows.length; i++) {
    var row = tableBody.rows[i];
    var firstColumnToConvert;
    var k = 0;
    for (var j = 0; j < row.cells.length; j++) {
      firstColumnToConvert = j;
      var value = row.cells[j].innerHTML;
      if (value.indexOf('participate.gif') != -1) {
         medName = medNames[k-5];
         var severity = stripHTML(row.cells[1].lastChild.innerHTML);
         severity = severity.replace(":", ": ");
         var advisory = row.cells[3].firstChild.firstChild.innerHTML;
         advisory = advisory.substring(0, advisory.indexOf(":"));
         var condition = row.cells[2].firstChild.firstChild.getAttribute("laymanterm");
         addContraMouseover(row.cells[j], medName, severity, advisory, condition);
         break;
      }
      k++;
    }
 }
}

// show contraindication informational rollover
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);
}

// add contraindication mouseover to a specific cell
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'); };
}


// add mouseovers to interactions
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('participate.gif') != -1) {
          addInteractionMouseover(row.cells[j], name1, name2, severity, id);
      }
    }
}

// add mouseover to a single specific interaction cell
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'); };
}

// add informational mouseovers to side affect graphs (not really graphs anymore)
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 && value.indexOf('risk-') != -1) {
         break;
      }
      else if (element.className == 'adeFeature' || element.className == "drugInfoAdeFeature") {
         ade = element.innerHTML;
      }
    }
    if (surveyType == "Compare") {
      var k = 0;
      for (var j = firstColumnToConvert; j < row.cells.length; j++) {
        addGraphMouseover(row.cells[j], medNames[k], medIDs[k] ,ade, medSections[k]);
        k++;
      }
    }
    else if (surveyType == "Combined") {
      var k = 0;
      for (var j = firstColumnToConvert+1; j < row.cells.length; j++) {
        addGraphMouseover(row.cells[j], medNames[k], medIDs[k] ,ade, medSections[k]);
        k++;
      }
      addCombinedGraphMouseover(row.cells[firstColumnToConvert], ade);
    }
    else if (surveyType == "Monograph") {
      for (var j = firstColumnToConvert; j < row.cells.length; j++) {
        addMonographRiskMouseover(row.cells[j], ade);
      }

    }
 }
}

// add mouseover to the side effects combined column graphics
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'); };
   }
}

// add mouseover to an individual side effect cell
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'); };
   }
}

// add a mouseover to side affect risk graphic for the monograph version of a map
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'); };

   }
}

// convert the risk graphic name into a percentage range.
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;
}


// set interaction names for app 600 
// this includes updating the interaction description
// with the name of each drug involved in the interaction
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; 
 }
}

// set interaction names 
// this includes updating the interaction description
// with the name of each drug involved in the interaction
function setInteractionNames(imageDirectory) {
 var x=document.getElementById("innerSurveyTable");
 var tableBody = x.tBodies[0];
 var medicationRow = x.tHead.rows[1];
 var medNames = getMedicationsFromHTML(medicationRow, 2);
 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('risk-yes.gif') != -1) {
         firstColumnToConvert++;
         break;
      }
    }
 
    var name1 = null;
    var name2 = null;
    var k = 0;
    for (var j = firstColumnToConvert; j < row.cells.length; j++) {
      var value = row.cells[j].innerHTML;
      var inInteraction = (value != undefined && value.indexOf('participate.gif') != -1);
      if (inInteraction) {
        if (name1 == null) {
          name1 = medNames[k];
        }
        else {
          name2 = medNames[k];
        }
      }
      k++;
    }

    var severity;
    var interaction;

    for (var j = 0; j<row.cells.length; j++) {
       var cell = row.cells[j];
       if (cell.getAttribute("headers") == 'Severity') {
           severity = row.cells[j].lastChild.innerHTML;
       }
       if (cell.getAttribute("headers") == 'Interaction') {
          interaction = row.cells[j];
       }
    }

    var interactionText = interaction.lastChild;

    var myHREF = interactionText.getAttribute("href");
    var interactionID = myHREF.substring(myHREF.indexOf("(") +1, myHREF.indexOf(")"));

    interactionText.innerHTML = "<img src='" + imageDirectory + "mono.gif' height='15' width='15' style='float:right; vertical-align: middle;'id='interactionMonograph" + i + "' interactionId='" + interactionID + "'/>" + interactionText.innerHTML;

    if (name1 != null) {
       addInteractionMouseovers(name1, name2, row, severity, interactionID);
    }
 }
}

// move the radio buttons used to select the map view
function moveViewSelector(mapType) {
        var newPlace = document.getElementById("new_view_select");
        var viewSelect=document.getElementById("view_select");

        newPlace.innerHTML = viewSelect.innerHTML;
        viewSelect.innerHTML = '';
        
        newPlace = document.getElementById("contra_view_radios");
        viewSelect=document.getElementById("contra_select");
        if (newPlace && viewSelect) {
           newPlace.innerHTML = viewSelect.innerHTML;
           viewSelect.innerHTML = '';
        }
}

// move the search fields to a new location
function moveSearchFields() {
        var  newPlace = document.getElementById("new_search_field");;
        var searchField=document.getElementById("search_field");
        newPlace.innerHTML=searchField.innerHTML;

        // remove the old searchField so that field with the same
        // name is not submitted
        searchField.innerHTML = '';
}

// set the on change event handler for whichever survey view selector 
// has been rendered
function changeViewSelectOnChange() {
        var viewSelect = document.getElementById('P4002_SURVEY_VIEW');
        if (viewSelect == null) { 
            viewSelect = document.getElementById('P4002_SURVEY_VIEW2');
        }
        if (viewSelect == null) {
            viewSelect = document.getElementById('P4004_SURVEY_VIEW');
        }
        if (viewSelect == null) {
            viewSelect = document.getElementById('P4004_SURVEY_VIEW2');
        }
        if (viewSelect) {
           var locationText = viewSelect.getAttribute('onchange') + '';
           locationText  = getRequestParamater(locationText);

           viewSelect.onchange = function(){disableThenSubmit(locationText);};
        }

}

// move the view selector to a new location (for app 600)
// also set its onchange event handler
function changeViewSelectOnChange600() {
        var viewSelect = document.getElementById('P3003_VIEW_SELECT');
        var locationText = viewSelect.getAttribute('onchange') + '';
        locationText  = getRequestParamater(locationText);
        viewSelect.onchange = function(){disableThenSubmit(locationText);};
}

// remove the div enabled by disablePage()
function enablePage() {
   if (document.getElementById('wholePage')) {
      document.getElementById('wholePage').style.display = "none";
      document.getElementById('processingPage').style.display = "none";
   }
}
 
// enable a div that covers the entire screen and makes the content
// underneith unclickable
function disablePage() {
       document.getElementById('wholePage').style.display = "inline";
}

// disable the page content by covering it with a transparent div
// make sure the div is not too big otherwise printers will
// print a bunch of blank pages
function disablePageForPrinting() {
   var myDiv = document.getElementById('wholePage');
   if (myDiv) {

       var mh = getDocumentHeight();
       var mw = getDocumentWidth();
       if (mh > 0) {
           myDiv.style.height = mh;
           myDiv.style.width = mw;
       }
       myDiv.style.display = "inline";
       myDiv.style.cursor = 'default';
       myDiv.style.opacity = 0;
       myDiv.style.filter = 'alpha(opacity=0)';
   }
}

// calculate the height of the window
function getDocumentHeight() {
   var dde = document.getElementById('allcontent');
   return (dde)?dde.offsetHeight:0;
}

// calculate the width of the window
function getDocumentWidth() {
   var dde = document.getElementById('allcontent');
   return (dde)?dde.offsetWidth:0;
}

// disable the page and then redirect to the specified address
function disableThenRedirect(address) {
   disablePage();
   location.href = address;
}

// disable the page and then submit the form
function disableThenSubmit(request) {
   disablePage();
   doSubmit(request);
}

// parse a string of the form "functionName('PARAMETER_VALUE')"
// extracting PARAMETER_VALUE
function getRequestParamater(locationText) {
  var start = locationText .indexOf("'");
  var end = locationText .lastIndexOf("'");
  return locationText .substring(start+1, end);
}

// show the search fields in their current location
// as opposed to moving them
// this is used when no results have been found
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();
}

// show the view selector in its current location
// as opposed to moving it
// this is used when no results have been found
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();
}

// hide any labels that would have otherwise show up
// this is used when no results are found
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;';
}

// check a table for templated data and then templatize the data
// and display it
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]);
    }
  }
}

// check an individual cell for templated data and then (if found) 
// templatize the data and display it
// template data is specified in the form VALUE1:::VALUE2:::...:::VALUEN
// and should have the className of "template"
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);
     }
  }
}

var matchLookup = /{.*}/;
// if you add parameters, or reorder variables in this function
// you must check that it still works when compressed.
// in particular you'll want to make sure that "f" used
// in the eval is still defined as f after name compression
//
//given a template and an array of names and corrisponding values
// replace every instance of a name with the value in the template
function runTemplate(template, names, values) {
   var length = names.length;
   var i = 0;
   var index = 0;
   for (i = 0; i < length; i++) {
      var f = values[i];
      var name = names[i];
      if (i == 0) { index = f; }

      if (f.match(matchLookup)) {
         var arrayName = f.substring(1, f.length-1);
         var exp = 'f = (typeof(' + arrayName + ") != 'undefined')?" + arrayName + '[' + index + ']:""';
         eval(exp);      
      }
      var r = new RegExp(name, 'g');
      template = template.replace(r, f); 
   }
   template = template.replace(/&APP_ID./, getAppId());
   template = template.replace(/&APP_SESSION./, getSessionId());
   return template;
}

// run the drug header template on a given cell
function templatizeDrugHeader(cell, drugTemplate) {
  var value = cell.firstChild.innerHTML;
  var values = value.split(":::");
  values[2] = values[2].substring(0, 4);

  var names = new Array(5);
  names[0] = "\\*MEDICATION_ID\\*";
  names[1] = "\\*ROUTED_DRUG_ID\\*";
  names[2] = "\\*DRUG_DISPLAY_NAME\\*";
  names[3] = "\\*ESCAPED_DRUG_DISPLAY_NAME\\*";
  names[4] = "\\*MED_SECTION\\*";
  names[5] = "\\*MED_START_DATE\\*";
  names[6] = "\\*EXTRA_INFO\\*";
  names[7] = "\\*REPLACEMENT_MED_ID\\*";
  names[8] = "\\*REPLACEMENT_MED_DESC\\*";

  cell.innerHTML = runTemplate(drugTemplate, names, values);
}

// get column index of the first drug in the map
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;
       }
   }
}

// prepare the comparison alternate selection map table for final viewing
// this includes setting column widths and templatizing the drug headers
function prepareReplaceSourceTable(numMeds, imageDirectory, drugTemplate, currentDrugTemplate, medId) {
 var sourceTable=document.getElementById("innerSurveyTable");
 var tableHead = sourceTable.tHead;

 var firstRow = tableHead.rows[1];
 var magicWidth = 60; //135;
 
 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], currentDrugTemplate);
 } else {
   for (var i = firstDrugCell; i < firstRow.cells.length; i++) {
       var newWidth = minDrugWidth;
       var cell = firstRow.cells[i];
       var data = cell.childNodes[0].innerHTML;
       var index = data.indexOf(":::");
       var currentId = data.substring(0, index);
       var template = (currentId == medId)?currentDrugTemplate:drugTemplate;
       templatizeDrugHeader(cell, template);
   }
 }
}

// prepare the map table for final viewing
// this includes setting column widths and templatizing the drug headers
function prepareSourceTable(numMeds, imageDirectory, drugTemplate) {
 var sourceTable=document.getElementById("innerSurveyTable");
 var tableHead = sourceTable.tHead;

 var firstRow = tableHead.rows[1];
 var magicWidth = 60; //135;
 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);
   }
 }

}

// return true if this is a firefox browser
function isFirefox() {
   return navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
}

// return true if this is a safari browser
function isSafari() {
   return navigator.userAgent.toLowerCase().indexOf('safari') > -1;
}

// return true if this is a chrome browser
function isChrome() {
   return navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
}

// return true if this is an IE browser
function isIE() {
   return (navigator.appName.indexOf('Internet Explorer') != -1);
}

// return true if this is an iPhone
function isIPhone() {
   return (navigator.userAgent.toLowerCase().indexOf('iphone') != -1);
}

// return true if this is an iPad
function isIPad() {
   return (navigator.userAgent.toLowerCase().indexOf('ipad') != -1);
}

var finalPagDiv = document.getElementById('finalPagDiv');
var finalPagDivWidth = 450;
var currentFinalPagDivLeft = 0;

// relocate the pagination at the top of the region to the bottom
// apex puts it at the top, but we want it at the bottom
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 = "";
}

// when scrolling left/right move the pagination so that it always shows up on screen
function movePagination() {
  if (finalPagDiv) {
    var windowWidth = getScrollWidth();
    var elementLeft = getLeft(finalPagDiv);
    var windowLeft = windowLeftCord();
    var windowRight = windowWidth + windowLeft;
    var maxWidth = document.getElementById('innerSurveyTable').offsetWidth;
    var reachedEdge = false;
    while (windowLeft > elementLeft && !reachedEdge) {
        windowLeft = windowLeftCord();
        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 = windowLeftCord();
        windowRight = windowWidth + windowLeft;
        elementRight = elementLeft + finalPagDivWidth;
    }
    

  }
  else {
    finalPagDiv = document.getElementById('finalPagDiv');
  }

}

// move new survey button from original spot to new div
// this is required because apex won't let you arbitarily place buttons/links
// this actually moves the save survey link
function moveNewSurveyButton() {
        var addMedsButton=document.getElementById("new_survey_button");
        var newPlace = document.getElementById("spotForNewSurveyButton");
        if (addMedsButton && newPlace) {
           newPlace.innerHTML = addMedsButton.innerHTML;
           addMedsButton.innerHTML = "";
        }
}

// navigate to page to create a new record of the specified type
function addRecordNow(recordType, page, app) {
    window.location="f?p="+app+":4020:0::RP,4002:4020:AI_RECORD_TYPE_CD,AI_ORIGINATING_PAGE:" + recordType + "," + page;
}

// navigate to the specified record med list
function gotoRecordMedListNow(recordId, medListId, app, nextPage) {
    if (!nextPage) { nextPage= 4003; }
  
    window.location="f?p="+app+":"+nextPage+":0:::RP,4002:P4002_OPEN_ONE,AI_SELECTED_MEDS_LIST_ID,AI_SELECTED_RECORD_ID:SE," + medListId + "," + recordId;
}

// navigate to the specified record med list
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;
}

// navigate to the import meds page
function gotoImportMedsNow(recordId, app) {
    window.location="f?p="+app+":4025:0:::4002,4027,4028:AI_SELECTED_RECORD_ID:" + recordId;
}

// set the styling for a field that matches autocomplete drop down
function setMatchedCss(field) {
   field.style.color = "blue";
}

// set the styling for a field that does not matche autocomplete drop down
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;
// update text on page
// find field i header with id of "CHANGE_STATUS"
// set it to "modified"
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";
	}
    }
}

// get a cells previous sibling, specifically a td
function getPreviousSibling(cell) {
      while (true) {
          cell= cell.previousSibling;
          if (cell== null || cell.nodeName == "td" || cell.nodeName == "TD") {
             return cell;
          }
      }
}

// set cursor focus on whichever medication field has been rendered
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_MEDICATION')) {
    document.getElementById('P4006_MEDICATION').focus();
  }

}

// switch condition type between on label and off label
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 = "";
    }
}

// remove the statistics from the map headers
// used when any drug/condition state has changed which requires
// a recalculation of statistics
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; }

     stats = document.getElementById('sideEffectsSearchStats');
     if (stats) { stats.innerHTML = "&nbsp;"; }
     stats = document.getElementById('interactionsSearchStats');
     if (stats) { stats.innerHTML = "&nbsp;"; }
     stats = document.getElementById('contraindicationsSearchStats');
     if (stats) { stats.innerHTML = "&nbsp;"; }
}

// change the checkbox repesentation (from checked or unchecked)
// and update the database 
// the map here is the mapping between a medication and a condition
function updateMedMap(checkboxid, conditionId, medId) {
    changeCheckBoxDisplayed(checkboxid, null);
    updateCondMedMap(conditionId, medId);
}

// switch the mapping status in the database 
// this is whether a condition is being treated by a med
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');
}

// switch between checked and unchecked state of a checkbox
// also return the new count value based on the countid
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);
     updateSameRoutedDrugs(routedDrugId, medId);
     if (getPageNumber() == 4003) {
	 var count = document.getElementById(countId);
	 if (count) {
	     count.innerHTML = countValue;
	 }
	 updateChangeStatus(theImage);
	 clearHeaderTotals();
	 showEditButtons();
	 // order of these two calls matter
	 updateIncludeInSurveyColumns(medId);
	 updateRecordLabel();
     }
}

// show edit controls 
function showEditButtons() {
     var div = document.getElementById('copyButtonSection');
     if (div) { div.style.display = ''; }
}

// update the record description label to include "modified"
function updateRecordLabel() {
     var recordLabel = document.getElementById("recordModLabel");
     if (recordLabel) {
         var modLabel = getItem("AI_MODIFIED_LABEL", getAppId(), getSessionId());
         recordLabel.innerHTML = modLabel;
     }
}

// update show in survey flag in the database (switches state)
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');
}

// unmap all routed drugs that match the routed drug for the given checkbox
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);
     if (getPageNumber() == 4003) {
	 updateChangeStatus(theImage);
	 showEditButtons();
	 // order of these two calls matter 
	 updateIncludeInSurveyColumns(medId, "REMOVE_ALL");
	 updateRecordLabel();     
     }
}

// uncheck the currently checked routed drug
// and check the current drug instead.
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");
		   }
		   if (getPageNumber() == 4003) {
		       updateChangeStatus(element);
		   }
               }
            }
            else {
               break;
            }
        }
     }

     if (getPageNumber() == 4003) {
	 updateChangeStatus(theImage);
	 showEditButtons();
	 // 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");
		   }
		   if (getPageNumber() == 4003) {
		       updateChangeStatus(element);
		   }
               }
            }
            else {
               break;
            }
        } 
     }

}

// display information div for a routed drug that
// is grayed out due to another drug with the same
// routed id being selected as a mapped drug
function showGrayedOutRoutedInfoBox(event, element) {

   if (element.src.match(matchGrayed)) {

      var region = document.getElementById('genericPopupTitle');
      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>";
   }

}

// recalculate the med section based on the values of the input fields
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);
    }
}

// return row after current row
function getNextRow(row) {
      while (true) {
          row = row.nextSibling;
          if (row == null || row.nodeName == "tr" || row.nodeName == "TR") {
             return row;
          }
      }
}

// based on state show all open children of the current 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;
        }
     }
}

// hide every child row regardless of state
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";
    }
}

// if tree node is open then close it
// and hide all of its children
// if it is closed then open it
// and show all of its children
// and expand its open children
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' });
      }
}

// find image with old string name and replace
// with a new string name
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);
}

// navigate to an example med list
function gotoExampleMedList(recordId, medListId, app) {
   gotoRecordMedList(recordId, medListId, app, 4002);
}

// navigate to an example med list
// confirm before leaving the current page
function gotoRecordMedList(recordId, medListId, app, nextPage) {
    if(confirmIfUnsaved()) {
       gotoRecordMedListNow(recordId, medListId, app, nextPage);
    }
}

// goto the import meds page
// confirm before leaving current page
function gotoImportMeds(recordId, app) {
    if(confirmIfUnsaved()) {
       gotoImportMedsNow(recordId, app);
    }
}

// goto the new record med list page
// confirm before leaving current page
function addRecordMedlist(recordId, page, app) {
    if(confirmIfUnsaved()) {
       addRecordMedListNow(recordId, page, app);
    }
}

// goto the new record page
// confirm before leaving the current page
function addRecord(recordType, page, app) {
    if(confirmIfUnsaved()) {
       addRecordNow(recordType, page, app);
    }
}

// validate patient fields and save into new patient record
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");
    }
}

// disable the reference name field if 
// the passed in element's value is not -1
function checkNameField(element) {
    var name = document.getElementById('P0_REFERENCE_NAME');
    if (element.value == -1) {
        name.disabled = false;
    }
    else {
        name.disabled = true;
    }
}

// validate reference fields and save into reference record and medlist
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");
    }
}

// validate proper date format
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;
}

// validate fields and make a copy of the current patient
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");
    }
}

// delete specified record folder
// check for user confirmation first if required
function deleteReferenceFolder(recordId) {
     if(confirmIfUnsaved()) {
          window.location = 'f?p=' + getAppId() + ':4003:0::NO::' + 
                            'P4003_REMOVE_ALL,P4003_EMPTY_RECORD_ID:TRUE,' +
                            recordId;
     }
}

// create a new adhoc basic med list
// check for user confirmation first if required
function newAdhoc() {
     if(confirmIfUnsaved()) {
          window.location = 'f?p=' + getAppId() + ':4003:0::' +
                            getDebug() + '::' + 
                            'P4003_REMOVE_ALL:TRUE';
     }
}

// remove an alternative from the comparison list
function unMapAlternative() {
    var element = document.getElementById('P4004_REMOVE_MED_ID');
    if (!element) {
       element = document.getElementById('P4007_REMOVE_MED_ID');
    }
    element.value = curDeleteId;
    doSubmit("REMOVE_COMPARE_MED");
}

// reimport the survey information from the ccd
// check for user confirmation first if required
function loadFromCCD() {
     if(confirmIfUnsaved()) {
          window.location = 'f?p=' + getAppId() + ':4003:0::' +
                            getDebug() + '::' +
                            'AI_LOAD_CCD_DATA:TRUE';
     }
}

// add the med actin plan specified
function medActionPlan(actionCodeValue) {
    var medId = document.getElementById("P0_ACTION_MED_ID");
    medId.value = curDeleteId;
    var actionCode = document.getElementById("P0_ACTION_CD");
    actionCode.value = actionCodeValue;

    if (actionCodeValue == "PM") { 
       alert("Prescribe this Med has been added to the EMR Action Plan. Be sure to Prescribe the Med when you return to the EMR for this patient.");
    } 
    else if (actionCodeValue == "UPM") {  
       alert("Discontinue this Med has been added to the EMR Action Plan. Be sure to Discontinue the Med when you return to the EMR for this patient.");
    }    doSubmit("ADD_MED_ACTION");
}

// remove the med action plan specified
function removeActionPlan(medicationId, actionCodeValue) {
    var medId = document.getElementById("P0_ACTION_MED_ID");
    medId.value = medicationId;
    var actionCode = document.getElementById("P0_ACTION_CD");
    actionCode.value = actionCodeValue;

    doSubmit("REMOVE_MED_ACTION");
}

// replace the "current" med with an "alternate"
// this just unprescribes the current and prescribees 
// the alternate (in the actino plan)
function replaceMedActionPlan() {
    var medId = document.getElementById("P0_ACTION_MED_ID");
    medId.value = curDeleteId;
    doSubmit("REPLACE_MED_ACTION");
}

// switch the state of the actionPlan check box. 
// This box changes the html checkbox image
// as well as updates the database.
function switchActionPlanTaken(actionPlanId) {
    changeCheckBoxCompareState("actionPlan"+actionPlanId);

    var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=SWITCH_ACTION_PLAN_STATE',0);
     get.add('TF_ACTION_PLAN_ID', actionPlanId);
     gReturn = get.get('XML');
}

// switch the state of the Med Cab Concern check box. 
// This box changes the html checkbox image
// as well as updates the database.
function switchConcern(concernId) {
    changeCheckBoxCompareState("concern"+concernId);
    var theImage = document.getElementById("concern"+concernId);

    var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=SWITCH_CONCERN_STATE',0);
     get.add('TF_CONCERN_ID', concernId);
     get.add('TF_CONCERN_ID', concernId);

    gReturn = get.get('XML');
    showEditButtons();
    updateRecordLabel();
    updateChangeStatus(theImage);
}


// update state of concern in the database
function switchFeatureConcernState(featureNo) {
    var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=SWITCH_FEATURE_CONCERN_STATE',0);
     get.add('TF_FEATURE_NO', featureNo);
     get.add('TF_PAGE_NUMBER', getPageNumber());

     gReturn = get.get('XML');
     showEditButtons();
     updateRecordLabel();
}


// find all intereactions with this class id and switch their state
function switchAllInteractionConcerns(id) {
   var table = document.getElementById("innerSurveyTable");
   var rows = table.tBodies[0].rows;
   for (var i = 1; i < rows.length; i++) {
       var cell = rows[i].cells[0];
       var img = cell.childNodes[1].firstChild;
       if (img && (img.nodeName == "IMG" || img.nodeName == "img")) {
          var intClassId = img.getAttribute("intClassId");
          if (id == intClassId) {
             changeCheckBoxCompareState(img.id);
          } 
       }
          
   }
}

// updates concern state in the database.
function switchInteractionConcernState(interactionClassId) {
    var get = new htmldb_Get(
       null,html_GetElement('pFlowId').value,'APPLICATION_PROCESS=SWITCH_INTERACTION_CONCERN_STATE',0);
     get.add('TF_INTERACTION_CLASS_ID', interactionClassId);

     gReturn = get.get('XML');
     showEditButtons();
     updateRecordLabel();
}

// open or close the map and change its header to reflect the current state
// also update the db with the current state
function switchMapHeaderState(gridType) {
    var regionId = gridType + "Region";
    hideOrShowElement(regionId);

    
    var image = document.getElementById(regionId + "StateImg");
    if (image) {
	if (image.src.indexOf("region-opened-arrow.gif") != -1) {
	    image.src = getImagePrefix() + "themes/theme_106/region-closed-arrow.gif";
	}
	else {
	    image.src = getImagePrefix() + "themes/theme_106/region-opened-arrow.gif";
	}
	
    }

    var mapStateName = "P" + getPageNumber() + "_" + gridType.toUpperCase() + "_ACCORDION_STATE";
    var mapStateField = document.getElementById(mapStateName);
    if (mapStateField) {
	mapStateField.value =  (mapStateField.value == "CLOSED")?"OPEN":"CLOSED"; 
	setItem(mapStateName, mapStateField.value, getAppId(), 0);
    }

    // temporary work around until coqsoft updates grid code 
    // (new coqsoft code should be here by Oct 7th 2011)
    // also see bug 539
    for (var i = 0; i < Grids.length; i++) {
	var g = Grids[i];
	if (g.id == gridType + "_grid") {
	    setTimeout("updateGrid(" + i + ")", 100);
	}
    }
}

function updateGrid(gridIndex) {
    var g = Grids[gridIndex];
    g.Update();
}

// open or close the legend and change its header to reflect the current state
// also update the db with the current state
function switchLegendState(legendType) {
    var regionId = legendType + "Region";
    hideOrShowElement(regionId);

    
    var image = document.getElementById(regionId + "StateImg");
    if (image) {
	if (image.src.indexOf("region-opened-arrow.gif") != -1) {
	    image.src = getImagePrefix() + "themes/theme_106/region-closed-arrow.gif";
	}
	else {
	    image.src = getImagePrefix() + "themes/theme_106/region-opened-arrow.gif";
	}
	
    }

    var legendStateName = "P" + getPageNumber() + "_" + legendType.toUpperCase() + "_STATE";
    var legendStateField = document.getElementById(legendStateName);
    if (legendStateField) {
	legendStateField.value =  (legendStateField.value == "CLOSED")?"OPEN":"CLOSED"; 
	setItem(legendStateName, legendStateField.value, getAppId(), 0);
    }
}


// remove html tags from text
function stripHTML(text) {
       var matchTag = /<(?:.|\s)*?>/g;
       text = text.replace(matchTag, "");
       matchTag = /'/g;
       return text.replace(matchTag, "\\'");  /* " */
}

var EMPTY_STRING = "--EMPTY_STRING--";
var delimitedSearchTerm;
var delimitedSearchTermArray;
// parse the search string for use within the coqsoft framework
function prepareSearchTerm() {
   var DELIM_STR = ":DELIM";
   var field = document.getElementById('P0_SEARCH');
   if (!field) {
       field = document.getElementById('P3005_SEARCH');
   }
   if (!field) {
       field = document.getElementById('P4007_SEARCH');
   }
   if (!field) {
       field = document.getElementById('P4004_SEARCH');
   }
   if (!field) {
       field = document.getElementById('P3013_SEARCH');
   }
   if (!field) {
       field = document.getElementById('P3014_SEARCH');
   }
   

   var searchValue;
   if (field.value == getSearchHint()) {
       searchValue = "";
   }
   else {
      searchValue = field.value.toLowerCase();
   }

   if (searchValue) {
      searchValue = searchValue.replace(/^\s+|\s+$/g,"");
      var arr = searchValue.split("");
      var inQuote = false;
      delimitedSearchTerm = "";
      for (var i = 0; i < arr.length; i++) {
          var c = arr[i];
          if (c == " " && !inQuote) {
	      if (arr[i+1] == " ") {
		  continue;
	      }
             delimitedSearchTerm += DELIM_STR;
          }
          else if (c == '"') { // "
              inQuote = !inQuote;
              // no trailing delimiter
              if (i != arr.length -1) {
                 delimitedSearchTerm += DELIM_STR;
              }
          }
	  else {
              delimitedSearchTerm += c;
          }
      }

      delimitedSearchTerm = delimitedSearchTerm.replace(DELIM_STR + DELIM_STR, DELIM_STR);
      if (delimitedSearchTerm.indexOf(DELIM_STR) == 0) {
	  delimitedSearchTerm = delimitedSearchTerm.substring(DELIM_STR.length);
      }
      delimitedSearchTermArray = delimitedSearchTerm.split(DELIM_STR);
   }
   else {
      delimitedSearchTerm = EMPTY_STRING;
      delimitedSearchTermArray = [];
   }
}

// return true if the element is hidden
function isHidden(elementName) {
    var element = document.getElementById(elementName);
    var hidden = (element)?(element.style.display=="none"):true;
    return hidden;
}

// uncheck the checkbox and update the corresponding search 
// field to match the checkbox state
function uncheckSearch(checkboxName, hiddenFieldName) {
    var searchCheckbox = document.getElementById(checkboxName);
    var hiddenField =  document.getElementById(hiddenFieldName);
    if (searchCheckbox && hiddenField) {
	searchCheckbox.checked = false;
	if (hiddenField.value == "S") {
	    hiddenField.value = "";
	} else if (hiddenField.value == "S:C") {
	    hiddenField.value = "C";
	}
	setItem(hiddenFieldName, hiddenField.value, getAppId(), 0);
    }
}

// check the checkbox and update the corresponding search 
// field to match the checkbox state
function checkSearch(checkboxName, hiddenFieldName) {
   var searchCheckbox = document.getElementById(checkboxName);
   var hiddenField =  document.getElementById(hiddenFieldName);
   if (searchCheckbox && hiddenField) {
       searchCheckbox.checked = true;
       if (hiddenField.value == "") {
	   hiddenField.value = "S";
       } else if (hiddenField.value == "C") {
	   hiddenField.value = "S:C";
       }
       setItem(hiddenFieldName, hiddenField.value, getAppId(), 0);
   }
}

// clear the search field and uncheck all search checkboxes
// then run a new search
function clearCoQSoftSearch() {
    var searchField = getSearchField();
    var searchFieldName = searchField.id;
    
    if (searchField) {
	searchField.value = "";
	setItem(searchFieldName, "", getAppId(), 0);
    }
    
    if (getPageNumber() == 4002) {
	uncheckSearch("searchResultsint", "P4002_INT_VIEW");
	uncheckSearch("searchResultscontra", "P4002_CONTRA_VIEW");
	uncheckSearch("searchResultsse", "P4002_ADE_VIEW");
    }
    else if (getPageNumber() == 4004) {
	uncheckSearch("searchResultsse", "P4004_ADE_VIEW");
	uncheckSearch("searchResultscontra", "P4004_CONTRA_VIEW");
    }
    else if (getPageNumber() == 4007) {
	uncheckSearch("searchResultsse", "P4007_ADE_VIEW");
	uncheckSearch("searchResultscontra", "P4007_CONTRA_VIEW");
    }
    
    return doCoQSoftSearch();
}

// if the search field is empty then clear the search
// if it is not empty then check apprioprate show only search checkboxes
// and run the new search
function runCoQSoftSearchFromSearchField() {

    var searchField = getSearchField();
    var searchFieldName = searchField.id;

    if (isIPad() || isIPhone()) {
	searchField.blur();
    }

    if (searchField.value == "" || searchField.value == getSearchHintText()) {
	return clearCoQSoftSearch();
    }
    else {
	var oneIsOpen = false;
	if (getPageNumber() == 4002) {
	    if (!isHidden("intRegion")) {
		checkSearch("searchResultsint", "P4002_INT_VIEW");
		oneIsOpen = true;
	    }
	    if (!isHidden("contraRegion")) {
		checkSearch("searchResultscontra", "P4002_CONTRA_VIEW");
		oneIsOpen = true;
	    }
	    if (!isHidden("seRegion") || !oneIsOpen) {
		checkSearch("searchResultsse", "P4002_ADE_VIEW");
	    }
	}
	else if (getPageNumber() == 4004) {
	    if (!isHidden("contraRegion")) {
		oneIsOpen = true;
		checkSearch("searchResultscontra", "P4004_CONTRA_VIEW");
	    }
	    if (!isHidden("seRegion") || !oneIsOpen) {
		checkSearch("searchResultsse", "P4004_ADE_VIEW");
	    }
	    
	}
	else if (getPageNumber() == 4007) {
	    if (!isHidden("contraRegion")) {
		oneIsOpen = true;
		checkSearch("searchResultscontra", "P4007_CONTRA_VIEW");
	    }
	    if (!isHidden("seRegion") || !oneIsOpen) {
		checkSearch("searchResultsse", "P4007_ADE_VIEW");
	    }
	}
	
	return doCoQSoftSearch();
    }  
}

// prepare the search field
// then Call the lucene and also the coqsoft search process for every 
// grid on the page.
function doCoQSoftSearch() {
    var grid = Grids[0];
    if (!grid) {
	return true;
    }
    
    var searchField = getSearchField();
    var searchFieldName = searchField.id;

    setItem(searchFieldName, searchField.value, getAppId(), 0);
    
    prepareSearchTerm();
    if (getPageNumber() != 3005 && getPageNumber() != 2) {
	updateMonographGraphics(delimitedSearchTerm);
    }
    
    grid.SearchExpression = delimitedSearchTerm;
    grid.TmpSpaceCol="Filter,Select";
    grid.DoSearch("Filter,Select", false);
    
    grid = Grids[1];
    if (grid) {
       grid.SearchExpression = delimitedSearchTerm;
       grid.TmpSpaceCol="Filter,Select";
       grid.DoSearch("Filter,Select", false);
    }
    
    grid = Grids[2];
    if (grid) {
	grid.SearchExpression = delimitedSearchTerm;
	grid.TmpSpaceCol="Filter,Select";
	grid.DoSearch("Filter,Select", false);
    }
    
    return false;
}

function removeStopWords(value) {
    value = value.replace(/ (their|there|these|then|they|into|such|that|this|will|with|was|not|and|are|but|for|the|no|on|or|to|of|if|by|in|an|as|at|is|it|be|a) /g, ' ');
    return value;
}

// return true if the value matches one of the prepared search terms
// if the value is empty then return the defaultIfEmpty value.
// if defaultIfEmpty is not specified then return false when value is empty
function testSearchValue(value, defaultIfEmpty) {
   var matched = (delimitedSearchTerm && delimitedSearchTerm != EMPTY_STRING)?false:defaultIfEmpty;
   value = value.toLowerCase();
   var valueWithNoStopWords = removeStopWords(value);
   for (var i = 0; i < delimitedSearchTermArray.length; i++) {
        var term = delimitedSearchTermArray[i];
        if ((term.indexOf(" ") == -1 && valueWithNoStopWords.indexOf(term) != -1) ||
	    (term.indexOf(" ") != -1) && value.indexOf(term) != -1) {
            matched = true;
            break;
        }
   }
   return matched;
}


// if the event is the enter key then run the coqsoft search
function doCoqSoftSearchOnEnter(event) {
   var result = stopRKey(event);
   if (!result) {
      if (event.keyCode == 13) {
         runCoQSoftSearchFromSearchField();
      }
   }
   return result;
}


// figure out the search field name on the page for the given mapType
function getSearchViewFieldName(mapType) {
    var hiddenFieldName;
    if (getPageNumber() == 3013) {
	hiddenFieldName = "P3013_GRID_VIEW";
    }
    else {
	if (mapType == "se") {
	    hiddenFieldName = "P" + getPageNumber() + "_ADE_VIEW";
	}
	else if (mapType == "int") {
	    hiddenFieldName = "P" + getPageNumber() + "_INT_VIEW";
	}
	else if (mapType == "contra") {
	    hiddenFieldName = "P" + getPageNumber() + "_CONTRA_VIEW";
	}
    }
    return hiddenFieldName;
}


// when the radio value is changed for the contraindication filter
// update the underlying hidden field that stores the value
// and then run a new search.
function updateContraView(radio) {
    var radios = document.forms[0].contraView;
    for (var i = 0; i < radios.length; i++) {
	radios[i].checked = (radios[i] == radio);
    }

    var hiddenFieldName = "P" + getPageNumber() + "_SURVEY_VIEW2";
    var hiddenField = document.getElementById(hiddenFieldName);

    hiddenField.value = radio.value;

    setItem(hiddenFieldName, hiddenField.value, getAppId(), 0);

    doCoQSoftSearch();

}

// update the current search view value based on the fact that
// the show only search checkbox was just checked
// and then run a new search
function updateSearchView(mapType) {
    var hiddenFieldName = getSearchViewFieldName(mapType);

    var hiddenField = document.getElementById(hiddenFieldName);
    if (hiddenField) {
	var value = hiddenField.value;
	if (value == "") {
	    value = "S";
	}
	else if (value == "S") {
	    value = "";
	}
	else if (value == "C") {
	    value = "S:C";
	}
	else if (value == "S:C") {
	    value = "C";
	}
	hiddenField.value = value;
    }

    setItem(hiddenFieldName, hiddenField.value, getAppId(), 0);

    doCoQSoftSearch();
    
}

// update the current search view value based on the fact that
// the show only tracked concerns checkbox was just checked
// and then run a new search
function updateConcernsView(mapType) {
    var hiddenFieldName = getSearchViewFieldName(mapType);

    var hiddenField = document.getElementById(hiddenFieldName);
    if (hiddenField) {
	var value = hiddenField.value;
	if (value == "") {
	    value = "C";
	}
	else if (value == "S") {
	    value = "S:C";
	}
	else if (value == "C") {
	    value = "";
	}
	else if (value == "S:C") {
	    value = "S";
	}
	hiddenField.value = value;
    }

    setItem(hiddenFieldName, hiddenField.value, getAppId(), 0);

    doCoQSoftSearch();
    
}

// get the abbreviated map type based on the grid id
function getMapType(gridId) {
    var mapType;
    if (gridId == "se_grid") {
	mapType = "se";
    }
    else if (gridId == "int_grid") {
	mapType = "int";
    }
    else if (gridId == "contra_grid") {
	mapType = "contra";
    }
    return mapType;
}

// Coqsoft API
// update interaction monographs based on search criteria as part of search
function OnSearch(grid,action,Show) {
    if (!action) {
       action = "Filter,Select";
    }

    if (grid.id == "int_grid") { 
           updateIntMonographGraphics(delimitedSearchTerm);
    }
}

// Coqsoft API
// Update all the external controls that are in the grid after a sort
// this is done because a sort resets the controls to their default state
function OnSortFinish(grid) {
    updateExternalControls(grid.id);
}

// get the field that contains the SORTED_BY value
// based on the gridId and the current page
function getSortField(gridId) {
    var mapType = getMapType(gridId).toUpperCase();
    var fieldId = "P" + getPageNumber() + "_" + mapType + "_SORTED_BY";
    return document.getElementById(fieldId);
}

// Coqsoft API
// Store, in the session, the name of the column that the grid is sorted by
function OnSort(grid, col, sort) {
    var sortField = getSortField(grid.id);
    if (sortField) {
	sortField.value = sort;
	setItem(sortField.id, sortField.value, getAppId(), 0);
    }
}

// Coqsoft API
// Override Coqsoft filtering. Show rows that match the search term.
// used in the drug monograph grid search
function OnRowFilterSimple(grid, row, show) {
    var col = grid.GetValue(row, "D");
    show = testSearchValue(col, true);
    return show;
}

// Coqsoft API
// Override Coqsoft filtering. Show rows based on grid type 
// as well as the state of the grids show only checkboxes.
function OnRowFilter (grid, row, show) {
    var newShow = false;
    var mapType = getMapType(grid.id);
    var hiddenFieldName = getSearchViewFieldName(mapType);

    var hiddenField = document.getElementById(hiddenFieldName);

    if (hiddenField) {
	var value= hiddenField.value;
	var concern = grid.GetValue(row, "Concern");          

	if (value == "") {
	    newShow = true;
	}
	else if (value.indexOf("C") != -1 && concern == 1) {
	    newShow = true;
	}
	else if (value.indexOf("S") != -1) {
	    newShow = false;
	    if (grid.id == "int_grid" || grid.id == "se_grid") {
		var col = grid.GetValue(row, "D");
		if (grid.id == "int_grid") {
		    if (col.indexOf("mono_red.gif") != -1) {
			newShow = true;
		    }
		}
		if (!newShow ) {
		    newShow = testSearchValue(col, false);
		}
	    }
	    else if (grid.id == "contra_grid") {
		var desc = grid.GetValue(row, "D");          
		var advisory = grid.GetValue(row, "A");          
		newShow = testSearchValue(desc, false) || testSearchValue(advisory, false);		
	    }
	}
    }
 
    if (newShow && grid.id == "contra_grid") {
	newShow = checkConditionDomain(grid, row);
    }

    return newShow;
}

// return true if the domain for the condition matches the radio button condition type
function checkConditionDomain(grid, row) {
    var domain = grid.GetValue(row, "Domain");
    var contraView = document.getElementById("P" + getPageNumber() + "_SURVEY_VIEW2");
    return (contraView.value == "contraindications" ||
	    (contraView.value == "contra_related" && domain == "CONTRA_RELATED") ||
	    (contraView.value == "contra_primary" && domain != "CONTRA_RELATED")); 
}

// Coqsoft API
// return true if any of the searched fields match the search values
// this controls search result highlighting
function OnRowSearch (grid, row, col, found, func, userdata) {

    var newFound = false;
    var desc = grid.GetValue(row, "D");

    if (grid.id == "int_grid" || grid.id == "se_grid" && desc != null) {
       newFound = testSearchValue(desc, false);
    }
    else if (grid.id == "contra_grid") {
       var desc = grid.GetValue(row, "D");          
       var advisory = grid.GetValue(row, "A");          
       newFound = testSearchValue(desc, false) || testSearchValue(advisory, false);
    }   
 
    return newFound;
}

var gridCount = 0;
// Coqsoft API
// keep track of how many grids are on the page.
function OnRenderStart(grid) {
   gridCount++;
} 

// set the condition radio button checked values based on the hidden 
// field that stores the value for the session.
function setShowConditionRadio() {
    var hiddenFieldName = "P" + getPageNumber() + "_SURVEY_VIEW2";
    var hiddenField = document.getElementById(hiddenFieldName);
    var radio = document.forms[0].contraView;
    if (hiddenField && radio) {
	for (var i = 0; i < radio.length; i++) {
	    if (radio[i].value == hiddenField.value) {
		radio[i].checked = true;
		break;
	    }
	}
    }
}

// set the show only checkboxes checked values based on the hidden
// field that stores the values for the session
function setShowOnlyCheckboxes(gridId) {
    var hiddenFieldName;
    var extension = getMapType(gridId);
    var hiddenFieldName = getSearchViewFieldName(extension);

    var hiddenField = document.getElementById(hiddenFieldName);
    if (hiddenField) {
	var concerns = document.getElementById("showConcerns"+extension);
	var search = document.getElementById("searchResults"+extension);
	if (search) {
	    var value = hiddenField.value;
	    if (value.indexOf("S") != -1) {
		search.checked = true;
	    }
	    if (value.indexOf("C") != -1) {
		concerns.checked = true;
	    }
	}
    }
}

// update the show only checkboxes
// and if the grid is contraindications also update the condition radio
function updateExternalControls(gridId) {
    setShowOnlyCheckboxes(gridId);
    if (gridId == "contra_grid") {
	setShowConditionRadio();
    }
}

// Coqsoft API
// When grid is done rendering set its show only (and condition radios)
// to match the values in the session.
// if search terms are present then also update the monograph.
function OnRenderFinish(grid) {
    gridCount--;

    updateExternalControls(grid.id);

    if (gridCount == 0) {
        if (delimitedSearchTerm && delimitedSearchTerm != EMPTY_STRING) {
	    if (getPageNumber() != 3005 && getPageNumber() != 2) {
		updateMonographGraphics(delimitedSearchTerm);
	    }
        }
    }

    // temporary work around until coqsoft updates grid code 
    // (new coqsoft code should be here by Oct 7th 2011)
    // also see bug 539
    grid.Update();
}

// set the OnKeyPress event handler for the named field
// to be the coqsoftsearchonenter event handler
function setSearchFieldOnKeyPress(fieldName) {
    var searchFieldElement = document.getElementById(fieldName);
    if (document.all) {
	searchFieldElement.onkeypress = function()  {
	    return doCoqSoftSearchOnEnter(event);
	};
    } else {   
	searchFieldElement.onkeypress = function(e)  {
	    return doCoqSoftSearchOnEnter(e);
	};
    }   
}

// Coqsoft API
// Called whenver a cell changes in a grid
// the only cell we current edit from the grid is the concerns
// when it changes notify the database of the change
function OnAfterValueChanged (grid, row, col, val) {
    if (col == "Concern") {
       var id = grid.GetValue(row, "I");
       if (!OnRowFilter (grid, row, "true")) {
	   grid.HideRow(row);
       }

       if (grid.id == "int_grid") {
           // flip other interactions of the same class            
           var body = grid.XB;
           var iRow = grid.GetFirst(body, 0);

           while(iRow) {
	       var value = grid.GetValue(iRow, "I");
               if (value == id) {
                   grid.SetValue(iRow, "Concern", val, true);
		   if (!OnRowFilter (grid, row, "true")) {
		       grid.HideRow(iRow);
		   }
               }
               iRow = grid.GetNext(iRow, 0);
           }
           switchInteractionConcernState(id);
       }
       else {
          switchFeatureConcernState(id);
       }
    }
    return val;
}

// Coqsoft API
// Used when a concern is checked from a monograph window
// Called whenver a cell changes in a grid
// the only cell we current edit from the grid is the concerns
// when it changes notify the database of the change and refresh the parent window
// so that the user can see the added concern when they return.
function OnValueChangedMonograph (grid, row, col, val) {
    if (col == "Concern") {
       var id = grid.GetValue(row, "I");
       switchFeatureConcernState(id);
       if (window.opener) {
	   if (window.opener.getPageNumber() == 4002) {
	       window.opener.location.href = "f?p=" + getAppId() + ":4002:0";
	   }
       }
    }
    return val;
}

// figure out which search field is currently being displayed
// and return it
function getSearchField() {
    var searchFieldName = "P0_SEARCH";
    var searchField = document.getElementById(searchFieldName);
    if (!searchField) {
	searchFieldName = "P3005_SEARCH";
	searchField = document.getElementById(searchFieldName);
    }
    if (!searchField) {
	searchFieldName = "P4007_SEARCH";
	searchField = document.getElementById(searchFieldName);
    }
    if (!searchField) {
	searchFieldName = "P4004_SEARCH";
	searchField = document.getElementById(searchFieldName);
    }
    if (!searchField) {
	searchFieldName = "P3013_SEARCH";
	searchField = document.getElementById(searchFieldName);
    }
    if (!searchField) {
	searchFieldName = "P3014_SEARCH";
	searchField = document.getElementById(searchFieldName);
    }
    return searchField;
}

// Coqsoft API
// Run when search finishes. Set the search summaries for the varies grids on the page
// also sets custom NoData found message if the search has resulted in all rows being filtered
function OnSearchFinish(grid, action, show) {
    if (getPageNumber() != 3013 && getPageNumber() != 3014) {
	if (grid.id == "se_grid") {
	    setSideEffectsSearchSummary();
	}
	else if (grid.id == "contra_grid") {
	    setContraSearchSummary();
	}
	// the interaction summary gets set by the ajax process.
    }

    var solid = grid.XS;
    solid = solid.firstChild;
    if (solid.Kind == "NoData") {
	grid.SetValue(grid.GetRowById('NoData'),'Html',getNoDataFoundMessage(grid),1);
    }
}

// based on state of the search field, the show only checkboxes and the type of grid (and conditions radio)
// return a custom no data found message that is appropopriate.
function getNoDataFoundMessage(grid) {
    var message = "No Results Found";

    var searchField = getSearchField();
    var searchFieldName = searchField.id;

    var sfValue = "";
    if (searchField) {
	sfValue = searchField.value;
    }
    if (sfValue == getSearchHint()) {
	sfValue = "";
    }

    var extension = getMapType(grid.id);
    var hiddenFieldName = getSearchViewFieldName(extension);
    var hiddenField = document.getElementById(hiddenFieldName);
    var hiddenFieldValue = (hiddenField)?hiddenField.value:"";

    if (grid.id == "se_grid") {
	if (hiddenFieldValue == "") {
	    message = 'There are no Side Effects results.  This does not mean that these Meds are safe to use together. <br/><br/>Please review the other Risk Maps and the Med Info Sheets by clicking the <img src="' + getImagePrefix() + 'themes/theme_106/mono.gif" width="20" height="20"/> icon in each Med column.'
	}
	else if (hiddenFieldValue == "S:C" && sfValue == "") {
	    message = 'There are no Side Effects Risk Map results because no Search terms are entered and no Side Effects are being tracked as a Concern.<br/><br/>Enter a Search term above or uncheck the "Show Only" check boxes to see all Side Effects, where you can indicate those to track as a Concern using the check box in the Concern column.';
	}
	else if (hiddenFieldValue == "S:C" && sfValue != "") {
	    message = 'No Side Effects Risk Map results were found that match the entered Search terms and no Side Effects are being tracked as a Concern.<br/><br/>Review any Info Sheets indicated with an <img src="' + getImagePrefix() + 'themes/theme_106/mono_red.gif" width="20" height="20"/> icon, as your search terms are found in them.<br/><br/>Uncheck the "Show Only: Search Results" box above to see all Side Effects, where you can indicate those to track as a Concern using the check box in the Concern column.';
	}
	else if (hiddenFieldValue == "S" && sfValue == "") {
	    message = 'There are no Side Effects Risk Map results because no Search terms are entered.<br/><br/>Enter Search terms above or uncheck the "Show Only: Search Results" box above to see all Side Effects.';
	}
	else if (hiddenFieldValue == "S" && sfValue != "") {
	    message = 'No Side Effects Risk Map results were found that match the entered Search terms.<br/><br/>Review any Info Sheets indicated with an <img src="' + getImagePrefix() + 'themes/theme_106/mono_red.gif" width="20" height="20"/> icon, as your search terms are found in them.<br/><br/>Uncheck the "Show Only: Search Results" box above to see all Side Effects.';
	}
	else if (hiddenFieldValue == "C") {
	    message = 'No Side Effects are being tracked as a Concern. <br/><br/>Uncheck the "Show Only: Concerns" box above to see all Side Effects, where you can indicate those to track as a Concern using the check box in the Concern column.';
	}
    }
    else if (grid.id == "int_grid") {
	if (hiddenFieldValue == "") {
	    message = 'There are no Interactions Risk Map results.  This does not mean that these Meds are safe to use together. <br/><br/>Please review the other Risk Maps and the Med Info Sheets by clicking the <img src="' + getImagePrefix() + 'themes/theme_106/mono.gif" width="20" height="20"/> icon in each Med column.';
	}
	else if (hiddenFieldValue == "S:C" && sfValue == "") {
	    message = 'There are no Interactions Risk Map results because no Search terms are entered and no Interactions are being tracked as a Concern.<br/><br/>Enter a Search term above or uncheck the "Show Only" check boxes to see all Interactions, where you can indicate those to track as a Concern using the check box in the Concern column.';
	}
	else if (hiddenFieldValue == "S:C" && sfValue != "") {
	    message = 'No Interactions Risk Map results were found that match the entered Search terms and no Interactions are being tracked as a Concern.<br/><br/>Review any Info Sheets indicated with an <img src="' + getImagePrefix() + 'themes/theme_106/mono_red.gif" width="20" height="20"/> icon, as your search terms are found in them.<br/><br/>Uncheck the "Show Only: Search Results" box above to see all Interactions, where you can indicate those to track as a Concern using the check box in the Concern column.';
	}
	else if (hiddenFieldValue == "S" && sfValue == "") {
	    message = 'There are no Interactions Risk Map results because no Search terms are entered.<br/><br/>Enter Search terms above or uncheck the "Show Only: Search Results" box above to see all Interactions.';
	}
	else if (hiddenFieldValue == "S" && sfValue != "") {
	    message = 'No Interactions Risk Map results were found that match the entered Search terms.<br/><br/>Review any Info Sheets indicated with an <img src="' + getImagePrefix() + 'themes/theme_106/mono_red.gif" width="20" height="20"/> icon, as your search terms are found in them.<br/><br/>Uncheck the "Show Only: Search Results" box above to see all Interactions.';
	}
	else if (hiddenFieldValue == "C") {
	    message = 'No Interactions are being tracked as a Concern. <br/><br/>Uncheck the "Show Only: Concerns" box above to see all Interactions, where you can indicate those to track as a Concern using the check box in the Concern column.';
	}
    }
    else if (grid.id == "contra_grid") {
	if (hiddenFieldValue == "") {
	    message = 'There are no Contraindications Risk Map results.  This does not mean that these Meds are safe to use together. <br/><br/>Please review the other Risk Maps and the Med Info Sheets by clicking the <img src="' + getImagePrefix() + 'themes/theme_106/mono.gif" width="20" height="20"/> icon in each Med column.';
	}
	else if (hiddenFieldValue == "S:C" && sfValue == "") {
	    message = 'There are no Contraindications Risk Map results because no Search terms are entered and no Contraindications are being tracked as a Concern.<br/><br/>Enter a Search term above or uncheck the "Show Only" check boxes to see all Contraindications, where you can indicate those to track as a Concern using the check box in the Concern column.';
	}
	else if (hiddenFieldValue == "S:C" && sfValue != "") {
	    message = 'No Contraindications Risk Map results were found that match the entered Search terms and no Contraindications are being tracked as a Concern.<br/><br/>Review any Info Sheets indicated with an <img src="' + getImagePrefix() + 'themes/theme_106/mono_red.gif" width="20" height="20"/> icon, as your search terms are found in them.<br/><br/>Uncheck the "Show Only: Search Results" box above to see all Contraindications, where you can indicate those to track as a Concern using the check box in the Concern column.';
	}
	else if (hiddenFieldValue == "S" && sfValue == "") {
	    message = 'There are no Contraindications Risk Map results because no Search terms are entered.<br/><br/>Enter Search terms above or uncheck the "Show Only: Search Results" box above to see all Contraindications.';
	}
	else if (hiddenFieldValue == "S" && sfValue != "") {
	    message = 'No Contraindications Risk Map results were found that match the entered Search terms.<br/><br/>Review any Info Sheets indicated with an <img src="' + getImagePrefix() + 'themes/theme_106/mono_red.gif" width="20" height="20"/> icon, as your search terms are found in them.<br/><br/>Uncheck the "Show Only: Search Results" box above to see all Contraindications.';
	}
	else if (hiddenFieldValue == "C") {
	    message = 'No Contraindications are being tracked as a Concern. <br/><br/>Uncheck the "Show Only: Concerns" box above to see all Contraindications, where you can indicate those to track as a Concern using the check box in the Concern column.';
	}

	var contraView = document.getElementById("P" + getPageNumber() + "_SURVEY_VIEW2");
	if (contraView.value == "contra_primary") {
	    message += '<br/><br/>Try changing your view to show Related Patient Conditions.';
	}
	else if (contraView.value == "contra_related") {
	    message += '<br/><br/>Try changing your view to show Reported Patient Conditions.';
	}
    }
    
    return message;
}

// alter the grid to use BoolIcon="6" for the iPad and iPhone.
// then render the grid.
var layoutBonusNotFirefox = "<Cfg MaxVScroll='600' ConstHeight='0'/>";
var layoutBonusShowPrint = "<Solid><Topbar id='T1' Cells='CustomLabel,Select,Empty,Rows,Map,CustomPrint'/></Solid>";
var iDeviceLayoutBonus = "<LeftCols><C Name='Concern' BoolIcon='6' Editing='1'/></LeftCols>";
var viewBonusLayout = "";
function createTreeGrid(layoutUrl, dataUrl, layoutBonus, divName) {
    if (isIPad() || isIPhone()) {
	if (layoutBonus) {
	    layoutBonus = layoutBonus.replace("</Grid>", iDeviceLayoutBonus + "</Grid>");
	}
	else {
	    layoutBonus = "<Grid>" + iDeviceLayoutBonus + "</Grid>";
	}	
    }
    if (! isFirefox()) {
	if (layoutBonus) {
	    layoutBonus = layoutBonus.replace("</Grid>", layoutBonusNotFirefox + "</Grid>");
	}
	else {
	    layoutBonus = "<Grid>" + layoutBonusNotFirefox + "</Grid>";
	}	
    }

    if (getPageNumber() != 4002) {
	if (layoutBonus) {
	    layoutBonus = layoutBonus.replace("</Grid>", layoutBonusShowPrint + "</Grid>");
	}
	else {
	    layoutBonus = "<Grid>" + layoutBonusShowPrint + "</Grid>";
	}	
    }

    if (viewBonusLayout) {
	if (layoutBonus) {
	    layoutBonus = layoutBonus.replace("</Grid>", viewBonusLayout + "</Grid>");
	}
	else {
	    layoutBonus = "<Grid>" + viewBonusLayout + "</Grid>";
	}		
    }
    
    TreeGrid('<bdo Sync="' + (needsSyncGrids()?1:0) + '"  Layout_Url="' + layoutUrl + '" Data_Url="' + dataUrl + '" Layout_Bonus="' + layoutBonus + '"> </bdo>',divName);
}

// open map it menu in its default state.
function openMapItMenu(gridType) {
    closeAllMenus();
    var divName = "mapItMenu";
    var element = document.getElementById("mapItLink" + gridType);
    var header = document.getElementById("mapItHeaderText");
    var headerText;
    if (getPageNumber() == 4002) {
	headerText = getSurveyType() + " Risks";
    }
    else {
        headerText = "Compare Risks";
    }
    header.innerHTML = headerText;
    var adjustLeft = calculateWidthDifference(element.id, divName);

    showDivBelowParent(null, element, divName, adjustLeft);
    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 orgState = element.getAttribute("originalstate");
		element.src = orgState;
            }
            else {
		break;
            }
        }
    }
}

// put map it state into xml and submit
function submitMapItState() {
    var groups = ["REG", "PROPOSED", "INACTIVE"];
    var all = document.getElementById("P0_MAP_IT_SETTINGS");
    all.value = "";

    for (var i = 0; i < groups.length; i++) {
        for (var j = 1; true; j++) {
            var id = "check" + groups[i] + j;
            var theImage = document.getElementById(id);

            if (theImage) {
		var medicationId = theImage.getAttribute("medicationid");
		var routedDrugId = theImage.getAttribute("routeddrugid");

                var showInMap = 2;
		if (theImage.src.match(matchNotChecked)) {
		    showInMap = 0;
		}
		else if (theImage.src.match(matchChecked)) {
		    showInMap = 1;
		}
		
		all.value += '<med id="' + medicationId + '" showInMap="' + showInMap + '" routedDrugId="' + routedDrugId + '"/>';
            }
            else {
		break;
            }
        }
    }
    all.value = "<settings>" + all.value + "</settings>";

    apex.submit('UPDATE_MAP_IT_SETTINGS');
}

// cancel the map it changes.
function cancelMapItChange() {
    hideRegion('mapItMenu');
}

// in the compare maps inside of advanced search
// and simulate impact of alternate the checkboxes behave
// slightly differently. Just switch checked and unchecked
// state. Don't do anything for greyed out checkbox
function updateShowInCompareSurvey(checkboxId) {
     var theImage = document.getElementById(checkboxId);
     if (theImage.src.match(matchGrayed)) {
         theImage.focus = false;
         return;
     }

     changeCheckBoxDisplayed(checkboxId, null);
}

// calculate the width difference between two divs. 
function calculateWidthDifference(parentDivName, childDivName) {
    var parent = document.getElementById(parentDivName);
    var child = document.getElementById(childDivName);

    var parentWidth = parent.offsetWidth;
    child.style.display = "inline";
    var childWidth = child.offsetWidth;

    var result = childWidth - parentWidth;
    if (result < 0) {
        result *= -1;
    }

    return result;
}

function closeAllMenus() {
    var divNames = ["mapPrintReportOptions", "viewController", "mapItMenu"];
    for (var i = 0; i < divNames.length; i++) {
	hideRegion(divNames[i]);
    }
}

function openPrintReport() {
    closeAllMenus();
    var divName = "mapPrintReportOptions";
    var element = document.getElementById("mapsPrintReport");
    var adjustLeft = calculateWidthDifference("mapsPrintReport", divName);
    showDivBelowParent(null, element, divName, adjustLeft);
}

function openPrintAdditionalHelp() {
    hideOrShowElement("pageSetupInstructions");
}


function openViewController() {
    closeAllMenus();
    var divName = "viewController";
    var element = document.getElementById("viewControllerLink");
    var adjustLeft = calculateWidthDifference("viewControllerLink", divName);
    showDivBelowParent(null, element, divName, adjustLeft);
}

function cancelViewControls() {
    hideRegion('viewController');
}

function submitViewControls(surveyKey, surveyId, surveyType) {
    hideRegion('viewController');
    apex.submit("CHANGE_VIEW");
}

function submitPrintOptions(surveyKey, surveyId, surveyType) {
    var includes = "";
    for (var i = 0; i < 50; i++) {
	var include = document.getElementById("P0_PRINT_SECTIONS_" + i);
	if (include) {
	    if (include.checked) {
		if (includes != "") {
		    includes += "|";
		};
		includes += include.value;
	    }
	}
	else { break; }
    }

    var filter = getValueFromRadioFieldGroup("P0_PRINT_FILTER_OPTION");
    var sort = getValueFromRadioFieldGroup("P0_PRINT_SORT_OPTION");
    var width = getValueFromRadioFieldGroup("P0_PRINT_VIEW_WIDTH");

    hideRegion('mapPrintReportOptions');
    
    return void(html_PopUp('f?p=500:3014:0::::' + 
			   'P3014_SURVEY_TYPE,P3014_SURVEY_KEY,' + 
			   'P3014_SURVEY_ID,P3014_SOURCE_PAGE_NUMBER,P0_PRINT_SECTIONS_VAL,' +
			   'P0_PRINT_FILTER_OPTION,P0_PRINT_SORT_OPTION,P0_PRINT_VIEW_WIDTH:' + 
			   surveyType + ',' + surveyKey + "," +
			   surveyId + ',' + getPageNumber() + "," + includes + "," +
                           filter + "," + sort + "," + width,
			   'print',950,700));

}

function cancelPrintOptions() {
    hideRegion('mapPrintReportOptions');
    hideRegion('additionalPrintHelp');
}

function getValueFromRadioFieldGroup(fieldGroupName) {
    var fs = document.getElementById(fieldGroupName);
    var radio = fs.getElementsByTagName('input');
    for (i = 0; i < radio.length; i++) {
	var element = radio[i];
	if (element.checked) {
	    return element.value;
	}
    }
}

function openPopupHelp() {
    var element = document.getElementById("popupHelpLink");
    showDivBelowParent(null, element, "popupHelp");
}

function closePopupHelp() {
    hideRegion('popupHelp');
}

function printAndClose() {
    window.print();
    window.close();
    window.onfocus = function() { window.close(); };
}

function longestWordLength(words, separator) {
    var spaced = words.split(separator);
    var length = 0;
    for (var i = 0; i < spaced.length; i++) {
	var word = spaced[i];
	var curLength = (word.indexOf("-") != -1)?longestWordLength(word, "-"):word.length;
	if (curLength > length) {
	    length = curLength;
	}
    }
    return length;
}
