var objectArrayIndex = 0;
var TermsArray = new Array();
var SearchString;
var focused="nofocus";
//var whichASC;
if (document.layers)
	{
	document.captureEvents(Event.KEYUP);
	document.onkeyup=CheckAndParseTerms; 
	}
function CheckAndParseTerms(keypress)
	{
	objectArrayIndex = 0;
	DisplayTerms('Your search terms:<BR><FONT size=-2>(click a hyperlinked search term below to use the MeSH browser to find its best synonym):</FONT>','envelope1','suggestions')
	DisplayTerms('','envelope2','term1')
	DisplayTerms('','envelope3','term2')
	DisplayTerms('','envelope4','term3')
	DisplayTerms('','envelope5','term4')
	DisplayTerms('','envelope6','other')
	var i=1;
	var pos=0;
	var posand=0;
	var posor=0;
	var posnot=0;
	SearchString=document.SEARCHFORM.SearchString.value.toUpperCase();
	//if (SearchString.substr(SearchString.length-1,1)!=" "){SearchString+=" "}
	//var result="";
	var term;
	while (i<SearchString.length)
		{
		posand=SearchString.indexOf(" AND ", pos);
			i=posand;
		posor=SearchString.indexOf(" OR ", pos);
		if ((posor>0 && posor<i) || i==-1)
			{i=posor};
		posnot=SearchString.indexOf(" NOT ", pos);
		if ((posnot>0 && posnot<i) || i==-1)
			{i=posnot};
		if (i==-1){i=SearchString.length};
		TermsArray[objectArrayIndex++]=SearchString.substring(pos,i+1);
		if (objectArrayIndex<5)
			{
			DisplayTerms(TermsArray[objectArrayIndex-1], 'envelope'+(objectArrayIndex+1),'term'+(objectArrayIndex))
			}
		if (posand==i)
			{
			pos=i+5
			}
		else if (posnot==i)
			{
			pos=i+5
			}
		else	
			{
			pos=i+4
			};
		}
	//DisplayOtherWarnings('', 'envelope6','other')
	objectArrayIndex=0;
	return true;
	}
//Check individual terms
function DisplayTerms(display,nestref,id)
	{
	//var TooManyWords="";
	//var Abbreviation="";
	//var Comma="";
	//var msg="";
	var Warnings="";
	if (id!='suggestions' && display.length>0)
		{
		if (display.substr(display.length-1,1)==" ")
			{
			Warnings=CheckTerms (display)
			//alert(display + "\n\n"+ Warnings.length)
			if (Warnings.length>3)
				{
				Warnings=" - " + Warnings;
				}
			}
		//display="<A href=javascript:void(window.open('http://www.ncbi.nlm.nih.gov/entrez/meshbrowser.cgi?retrievestring=&mbdetail=n&term="+Replacer(display,' ','+')+"','','scrollbars=yes,menubar=yes,toolbar=yes,resizable=yes,width=640,height=480'))>"+display+"</A>"+Warnings;	
		//New 5/7/2003
		display="<A href=javascript:void(window.open('http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=mesh&orig_db=mesh&cmd=search&cmd_current=&term="+Replacer(display,' ','+')+"','','scrollbars=yes,menubar=yes,toolbar=yes,resizable=yes,width=640,height=480'))>"+display+"</A>"+Warnings;	
		}
	 WriteLayer(display,nestref,id)
	}
function CheckTerms(display)
	{
	var result="";
	var msg="";
	//check for abbreviation
	var secondspace=display.indexOf(" ",display.indexOf(" ",1)+1);
	if ((display.length<5 || display.indexOf(" ")<4) && display.length>0)
		{
		result+="<LI>Is "+display.substr(0,3)+" an abbreviation? <A HREF=\"javascript:alert('Most journals avoid abbreviations in their abstracts so abbreviations are not good search terms.\n\nThere are a few abbreviations that map to MeSH terms and are safe to use.')\">Suggestions.</A>?"
		}
		//alert(display +'\n\nsecondspace: ' + secondspace + '\n\ndisplay.length: ' + display.length)
	//check for three or more words
	if (secondspace>0 && secondspace < display.length-1)
		{
		result+="<LI>More than two words. <A HREF=\"javascript:alert('Unless this is a MeSH term, insert AND between concepts.')\">Suggestion</A>."
		}
	var comma=display.indexOf(",");
	if (comma>0)
		{
		var alternative=display.substring(comma+1)+" "+display.substring(0,comma)
		//result+="<LI>Comma used. '<A href=\"javascript:void(window.open('http://www.ncbi.nlm.nih.gov/entrez/meshbrowser.cgi?retrievestring=&mbdetail=n&term="+Replacer(alternative," ","+")+"','','scrollbars=yes,menubar=yes,toolbar=yes,resizable=yes,width=640,height=480'))\">"+alternative+"</A>' may be a better term. <A HREF=\"javascript:alert('Although "+display+" may be MeSH term, "+alternative+" may be *associated* with " +display+".\n\n If the terms are associated, then you should choose the term that is the more common sequence of textwords. Click the hyperlink labeled "+alternative+" and carefully read the MeSH browser for the word *associated*.')\">Explanation</A>";
		//Below started 5/7/2003
		result+="<LI>Comma used! '<A href=\"javascript:void(window.open('http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=mesh&orig_db=mesh&cmd=search&cmd_current=&term="+Replacer(alternative," ","+")+"','','scrollbars=yes,menubar=yes,toolbar=yes,resizable=yes,width=640,height=480'))\">"+alternative+"</A>' is probably a better term. <A HREF=\"javascript:alert('Although "+display+" may be MeSH term, "+alternative+" may be *associated* with " +display+".\n\n If the terms are associated, then you should choose the term that is the more common sequence of textwords. \n\nClick the hyperlink labeled "+alternative+" and see if searching for "+alternative+" finds "+display+". If so, then use "+alternative+".')\">Explanation</A>";
		}
	//If ends in s, suggest truncation
	//alert("*"+display.substr(display.length-2)+"*")
	if (display.substr(display.length-2)=="S ")
		{
		result+="<LI><I><B>If</B></I> this is a plural text word (and not a MeSH term), consider truncating:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'"+display.substr(0,display.length-2)+"*'"
		}
	//check whether suggests need for filter
	msg+=NeedFilter(display,"advers","adverse","adverse effects")
	msg+=NeedFilter(display,"prognos","prognosis","prognosis")
	msg+=NeedFilter(display,"cause","cause","etiology/casuation")
	msg+=NeedFilter(display,"etiol","etiology","etiology/casuation")
	msg+=NeedFilter(display,"risk","risk","etiology/casuation")
	msg+=NeedFilter(display,"treat","treat","treatment")
	msg+=NeedFilter(display,"diagnos","diagnosis","diagnosis")
	msg+=NeedFilter(display,"sensitivit","senstivity","diagnosis")
	msg+=NeedFilter(display,"specific","specificity","diagnosis")
	msg+=NeedFilter(display,"accurac","accuracy","diagnosis")
	msg+=NeedFilter(display,"physical","physical","physical findings")
	msg+=NeedFilter(display,"screen","screening","screening-prevention")
	msg+=NeedFilter(display,"prevent","prevention","screening-prevention")
	//alert(display + "/n/n"+msg.length+"\n"+msg)
	if (msg.length>10)
		{
		result+="<LI>Filter may be needed. <A href=\"javascript:alert(\'"+msg+"\')\">Suggestion.</A><BR>";
		msg="";
		}
	if (result.length>0)
		{return "<FONT color=red>Warning</FONT>: "+result}
	else
		{return ""}
	}
function NeedFilter(display, root, word, better)
	{
	if (display.indexOf(root.toUpperCase())>-1)
	  {
	  msg="Your search line includes "+word.toUpperCase()+". \n\n";
	  msg+="Consider removing this and instead clicking the "+better+" focus button.\n\n\n"
          return msg+"\n";
	  }
	else
	  {
	  return "";
	  }
	}
//Checking over-all query structure
function DisplayOtherWarnings (display,nestref,id)
	{
	var msg="";
	var ShowOther="no";
	//if (focused=="nofocus")
	//alert(document.SEARCHFORM.Focus.value)
	if (document.SEARCHFORM.Focus.value=="none" || document.SEARCHFORM.Focus.value=="nofocus")
		{
		display+="<FONT color=red>Warning</FONT>: Consider focusing your search (see below).<BR>";	
		ShowOther="yes";
		}
	var Complicated=0;
	if (SearchString.indexOf(" OR ")>0)
		{
		Complicated=SearchString.indexOf(" AND",SearchString.indexOf(" OR "))
		}
	if (Complicated<1 && SearchString.indexOf(" AND ")>0)
		{
		Complicated=SearchString.indexOf(" OR ",SearchString.indexOf(" AND "))
		}
	if (Complicated<1 && SearchString.indexOf(" NOT ")>0)
		{
		Complicated=SearchString.indexOf(" OR ",SearchString.indexOf(" NOT "))
		}
	if (Complicated<1 && SearchString.indexOf(" NOT ")>0)
		{
		Complicated=SearchString.indexOf(" AND ",SearchString.indexOf(" NOT "))
		}
	if (Complicated>0)
		{
		msg="Complicated search:\\n\\n";
		msg+="When you mix connectors (\\'AND\\' and \\'OR\\' and \\'NOT\\') in a query, the sequence in terms is critical.\n\n"
		msg+="Parentheses will be automatically inserted starting with the left terms. You query will become:\\n\\n"
		msg+="("+SearchString.substring(0,Complicated)+")"+SearchString.substring(Complicated)+"\\n\\n"
		msg+="If this is not correct, change the sequence of your search terms. Unfortunately, SUMSearch cannot accept parentheses."
		display+="<FONT color=red>Warning</FONT>: Mixed connectors? <A href=\"javascript:alert(\'"+msg+"\')\">Suggestion</A>.<BR>";	
		ShowOther="yes";
		msg="";
		}
	//parentheses
	if (document.SEARCHFORM.SearchString.value.indexOf(")")>-1 || document.SEARCHFORM.SearchString.value.indexOf("]")>0 || document.SEARCHFORM.SearchString.value.indexOf("}")>0)
		{
		msg+="Sorry, but SUMSearch does not accept parentheses.\n\n";
		msg+="However, if you enter 3 or more terms, parentheses are automatically placed starting with the first two terms and continuing to the last terms.\n\n"
		msg+="Example:\n\n"
		msg+="postpartum or pregnancy and hypertension\n\n"
		msg+="  will automatically become\n\n"
		msg+="(postpartum or pregnancy) and hypertension\n\n\n"
		msg+="After you close this warning, you may remove the parentheses and search again.\n\n"
		display+="<FONT color=red>Error</FONT>: Parenthesis used. <A href=\"javascript:alert(\'"+msg+"\')\">Suggestion</A>.<BR>";	
		ShowOther="yes";
		msg="";
		}
	if (ShowOther=="yes")
		{
		WriteLayer(display,nestref,id)
		}
	else
		{
		WriteLayer("No problems in search logic detected (other than any listed above). Spelling will be checked after the search starts.",nestref,id)
		}
 	}
function checkstrategy()
	{
	SetCookie ("LastSearch", document.SEARCHFORM.SearchString.value,7)
	SetCookie ("LastFocus", document.SEARCHFORM.Focus.value,7)
	if (document.SEARCHFORM.SearchString.value.substr(document.SEARCHFORM.SearchString.value.length-1,1)!=" ")
		{
		document.SEARCHFORM.SearchString.value=document.SEARCHFORM.SearchString.value+' ';
		}
	CheckAndParseTerms();
	DisplayOtherWarnings('', 'envelope6','other')
	}
function presubmit()
	{
	document.SEARCHFORM.bttnSubmit.disabled=true;
	document.SEARCHFORM.bttnCheck.disabled=true;	
	SetCookie ("LastSearch", document.SEARCHFORM.SearchString.value,7)
	SetCookie ("LastFocus", document.SEARCHFORM.Focus.value,7)
	ShowJnlNews();
       	}
//Utilities from here on
function WriteLayer(text,nestref,id)
	{
	if (document.layers) //NS4 only
		{
		//alert ("nesterf=" + nestref + "\nid=" + id)
		display="<TABLE width=100% border=0><TR><TD>"+display+"</TD></TR></TABLE>"
		var myElement = (nestref)? eval('document.'+nestref+'.document.'+id) : document.layers[id];
		myElement.document.open();
		myElement.document.write(text);
		myElement.document.close();
		//alert(display +'\n\n'+ nestref + ' ' + id + '\n\n'+ myElement+'\n\n'+myElement.visibility)
		}
	else //IE and NS6
		{
		var myElement = document.getElementById(id);
		myElement.backgroundColor="yellow";
		myElement.innerHTML=text;
		//alert (myElement)
		}
	}

function Replacer(itxt,OldChars,NewChars)
	{
	if (itxt==null){itxt=""};
	var i=0;
	while (i!=-1)
		{
		i = itxt.indexOf(OldChars, i);
		if (i>-1){itxt=itxt.substring(0,i)+NewChars+itxt.substring(i+OldChars.length)};
		}
	return itxt;
	}

function GetCookie(Name)
{
   var search = Name + "="
   if (document.cookie.length > 0) { // if there are any cookies
      offset = document.cookie.indexOf(search) 
      if (offset != -1) { // if cookie exists 
         offset += search.length 
         // set index of beginning of value
         end = document.cookie.indexOf(";", offset) 
         // set index of end of cookie value
         if (end == -1) 
            end = document.cookie.length
         return unescape(document.cookie.substring(offset, end))
      }}
}
function SetCookie(name, value, days)
{
   var today = new Date();
   var expires = new Date();
   expires.setTime(today.getTime() + 1000*60*60*24*days);
   document.cookie = name + "=" + escape(value)
   + ((days == 0) ? "" : ("; expires=" + expires.toGMTString()))
   + ("localhost","");
}
function load()
	{
	document.SEARCHFORM.bttnSubmit.disabled=false;
	document.SEARCHFORM.bttnCheck.disabled=false;	
	if (GetCookie("news")!=null)
		{
		document.SEARCHFORM.news.value=GetCookie("news")
		}
	document.SEARCHFORM.SearchString.value="";
	if (GetCookie("LastSearch")!=null)
		{
		document.SEARCHFORM.SearchString.value=GetCookie("LastSearch")
		}
	if (GetCookie("LastFocus")!=null)
		{
		document.SEARCHFORM.Focus.value=GetCookie("LastFocus")
		}


	// Get CGI input variable pairs
	var Vars = new Array("Name","Value");
	var VarsIndex = 0;

	var i=0;
	var posamp;
	var pair;
	while (i<location.search.length)
		{
		posamp=location.search.indexOf("&", posamp);
		if (posamp==-1){posamp=location.search.length};
		pair=location.search.substring(i+1,posamp);
		Vars[VarsIndex] = new Array("Name","Value")
		Vars[VarsIndex][0] = pair.substring(0,pair.indexOf("="));
		Vars[VarsIndex][1] = pair.substring(pair.indexOf("=")+1);
//No work	alert(Vars[VarsIndex]["Name"]+'\n'+Vars[VarsIndex]["Value"]);
//Works		alert(Vars[VarsIndex][0]+'\n'+Vars[VarsIndex][1]);
		i=posamp;
		posamp=posamp+pair.length
		VarsIndex=VarsIndex+1;
		}
	if (VarsIndex>0)
		{
		if (Vars[0][1].length>1)
			{
			Vars[0][1]=Replacer(Vars[0][1],"+"," ");
			Vars[0][1]=Replacer(Vars[0][1],"%20"," ");
			document.SEARCHFORM.SearchString.value=Vars[0][1];
			}
		if (Vars[1][1].length>1)
			{
			document.SEARCHFORM.Focus.value=Vars[1][1];
			}
		}
	//alert(location.href.indexOf("http://80-"))
	SetProxyValue();
	//document.SEARCHFORM.Proxy.value=GetCookie("Proxy")
	//StartProxy();
	document.SEARCHFORM.SearchString.focus();
	}
function ChangeProxy()
	{
	//SetCookie('Proxy',document.SEARCHFORM.Proxy.value, 7);
	StartProxy();
	}
function StartProxy()
	{
	//Inputs can come from a dropdown selection or a cookie
	var URL;
	if (document.SEARCHFORM.Proxy.value=="No" || document.SEARCHFORM.Proxy.value=="no" || document.SEARCHFORM.Proxy.value==null)
		{
		if (location.href.indexOf("libproxy")>=0)
			{
			URL="http://SUMSearch.uthscsa.edu?SearchString="+document.SEARCHFORM.SearchString.value+"&focus="+document.SEARCHFORM.Focus.value
			location.href=URL;
			return;
			}
		}
	if (document.SEARCHFORM.Proxy.value=="na" || document.SEARCHFORM.Proxy.value=="NA")
		{
		alert('Contact your medical library.')
		//if (location.href.indexOf("http://sumsearch.UTHSCSA.edu")<0)
		//	{
		//	URL="http://SUMSearch.uthscsa.edu?SearchString="+document.SEARCHFORM.SearchString.value+"&focus="+document.SEARCHFORM.Focus.value
		//	location.href=URL;
		//	return;
		//	}
		SetProxyValue();
		}
	if (document.SEARCHFORM.Proxy.value=="UTHSCSA")
		{
		if (location.href.indexOf("libproxy")<0)
			{
			var URL;
			//URL="http://liblog.uthscsa.edu/cgi-bin/ezpiii.cgi?url="
			//As of 2002/10/07
			//URL="http://libproxy.uthscsa.edu/login?url="
			//URL=URL+location.href+"?SearchString="+document.SEARCHFORM.SearchString.value+"&focus="+document.SEARCHFORM.Focus.value
			//As of 2004/08/10
			URL="http://sumsearch.uthscsa.edu.libproxy.uthscsa.edu?SearchString="+document.SEARCHFORM.SearchString.value+"&focus="+document.SEARCHFORM.Focus.value
			location.href=URL;
			}
		}

	SetCookie('Proxy',document.SEARCHFORM.Proxy.value, 365)
	}
function SetProxyValue()
	{
	if (location.href.indexOf("http://80-")>=0)
		{
		document.SEARCHFORM.Proxy.selectedIndex=1;
		}
	else
		{
		document.SEARCHFORM.Proxy.selectedIndex=0;
		}
	}
function ShowJnlNews()
	{
	if (GetCookie('news')!='yes'){return}
	var today=new Date();
	var target=today.getMinutes();
	var targetURL;
	if (target<9){target='NEJM';targetURL='content.nejm.org/current.shtml'}
	if (target<18){target='Annal of Internal Medicine';targetURL='www.annals.org'}
	if (target<25){target='Lancet';targetURL='www.thelancet.com/newlancet/current'}
	if (target<34){target='BMJ';targetURL='www.bmj.com/current.shtml'}
	if (target<43){target='JAMA';targetURL='jama.ama-assn.org'}
	if (target<52){target='ACP Journal Club';targetURL='www.acponline.org/journals/acpjc/jcmenu.htm'}
	if (target<61){target='Journal Watch';targetURL='www.jwatch.org/gm/'}
	if(document.layers)
		{
		//msg="*Netscape users* Your browser may say SUMSearch has stalled. Ignore this unless the search takes more than 2 minutes.\n\n"
		}
        NWindow=window.open('http://'+targetURL,'news',"scrollbars=yes,menubar=yes,toolbar=no,resizable=yes,width=600,height=450");
	}
