//copyright 2001 Robert M. Hanson, St. Olaf College, Northfield, MN 55057
//netscape bugs require occasional                   gaps in code
//note! arosyn.htm?substrate?product  starts with that!
//for example: arosyn.htm?H,Br?NO2,Br
//version BH 4:36 PM 3/17/01 includes naming!
going=false
sdebug=""
maxsteps=6
nmax=6
sloadinfo=""

Cmpdlist=new Array()
Cmpdlist[0]=new Array()
Cmpdlist[1]=new Array()


function findcmpd(icmpd){
 if(icmpd>1)return 0
 var s=""
 for(var i=1;i<Cmpdlist[icmpd].length;i++){
	if(issamecmpd(Cmpdlist[icmpd][i],Compound[icmpd]))return i
 }
 return 0
}

function setreagent(ireag){
 var d=getdivlistbox("infor","formr.thereagent")
 if(ireag){
  for(var i=1;i<d.length;i++){
	if(d[i].text==Reagenttype[ireag][0]){
		d.selectedIndex=i
		setname(2)
		return
	}
  }
 }
 d.selectedIndex=0
 setname(2)
}

function setname(icmpd,i){
	if(icmpd==2){
		var d=getdivlistbox("infor","formr.thereagent")
		i=d.selectedIndex
	}else{
		var d=getdivlistbox("info"+icmpd,"form"+icmpd+".thecmpd")
		d[0].text=(i<=0?getname(icmpd):"")
	}
	if(i<0)i=0
	if(icmpd<2)d.selectedIndex=i
	Name[icmpd]=d[i].text
	if(icmpd<2 && Name[icmpd].length==0)Name[icmpd]=(icmpd?"this product":"this starting material")
	return i
}

function checkit(icmpd){
	setname(icmpd,findcmpd(icmpd))	
}

//////drawing part//////

//styles are all set here
infotop=10
infotopr=infotop+50
starttop=infotop+100
starttop2=starttop
startleft=new Array(50,500)
startleftr=270
starttopr=starttop
msgleft=0
msgtop=275
Places=new Array(49,-15, 107,17, 107,80, 49,104, -8,80, -10,17)//left,top

function setdivpositions(){
 divanchor("anchor")
 divmove("info0",startleft[0]-20,infotop)
 divmove("infor",startleftr,infotopr)
 divmove("info1",startleft[1]-20,infotop)
 divmove("compound",startleft[0],starttop)
 for(var i=0;i<6;i++)divmove("H0"+i+"",(startleft[0]+Places[2*i]),(starttop+Places[2*i+1]))
 divmove("reagent",startleftr,starttopr)
 divmove("product",startleft[1],starttop2)
 for(var i=0;i<6;i++)divmove("H1"+i+"",(startleft[1]+Places[2*i]),(starttop2+Places[2*i+1]))
 divmove("message",msgleft,msgtop)

}

function drawreagent(sinfo){
 writediv("reagent",sinfo)
}

function showreactant(){
 var smsg=""
 var j=0
 //showmessage(smsg)
 for(var i=0;i<6;i++){
	j=Compound[0][i]
	if(j!=0)smsg+=(i+1)+": "+groupname(j)+" "+Grouptype[j]+"\n"
 }
 //showmessage(smsg)
 showreagent("",true)
}

function showreagent(sreag,isynthesis){
 var d=getdivlistbox("infor","formr.thereagent")
 sreag+="||||"
 var D=sreag.split("|")
 D[5]=D[4]
 D[4]=D[3]
 D[3]="<img src=dataa.gif>"
 if(d.selectedIndex>0 && sreag=="||||")D[2]="&nbsp;&nbsp;&nbsp;<a href='javascript:doreact()'>React</a>"
 if(isynthesis && sreag=="||||" && !issamecmpd(Compound[0],Compound[1]))D[4]="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='javascript:dosynthesis(0)'>Synthesize</a>"
 sreag=D.join("<br>\n")
 drawreagent(sreag)
}


function showreaction(nr){
 var S=new Array()
 var P=new Array()
 var r=0
 copyarray(Compound[0],P,-1)
 for(var i=1;i<arguments.length;i++){
	copyarray(P,S,-1)
	r=arguments[i]
	getproduct(S,r,P,true)
	setreagent(r)
 }
 copyarray(P,Compound[1],-1)
 showproduct(S,Compound[1])
 checkit(1)
}

function showproduct(S,P){
	for(var i=0;i<6;i++)drawsub(1,i,P[i],S[i]!=P[i])
}

function showmod(icmpd){
 if(icmpd==0){showreactant()}else{showreagent("",true)}
}

function showmessage(smsg){
 writedivtextarea("message","formm.list",smsg)
}

function showalert(salert){
 if(salert==""){
  checkit(0)
  checkit(1)
  salert="Click on \"Synthesize\" to see the path from "+Name[0]+" to "+Name[1]+"."
 }
 alert(salert)
}


////// calc part //////

function generateproduct(title){	
 var P=new Array()
 copyarray(Compound[1],P,-1)
 Compound[1]=new Array(0,0,0,0,0,0)
 var s=""
 var smsg=""
 var d=getdivlistbox("infor","formr.thereagent")
 var r=d[d.selectedIndex].value
 var sreag=setsubs(Reagenttype[r][0],0)
 if(!getproduct(Compound[0],r,Compound[1],true)){
	showalert(Name[2]+" is incompatible with "+Name[0]+".")
	setreagent(0)
	copyarray(P,Compound[1],-1)
	showreagent("",true)
	return 0
 }
 showreagent("||&nbsp;&nbsp;&nbsp;"+sreag,true)
 showproduct(Compound[0],Compound[1])
 return 1
}

function findpathway(P){
 var nr0=REAG[0]
 var ss=""
 for(var i=0;i<nr0;i++)ss+="  "
 if(issamecmpd(SM,P)){
	sdebug+=ss+"SUCCESS!\n"
	dosynthesis(9999)
	going=false
	return true
 }
 if(!going)return false
 if(nr0>=maxsteps){
	dosynthesis(-1)
	going=false
	return true
 }
 if(nr0>=nmax){
	return false
 }	
 if(nr0==0){//main level
  Q0=new Array()
  for(var i=0;i<6;i++)Q0[i]=new Array()
  copyarray(P,PR,-1)
  if(!getpossiblereagents(Q0,PR)){dosynthesis(-1);going=false;return false}
  setTimeout("findintermediate("+nr0+",'',0,Q0,PR,true)",10)
 }else{
  var Q=new Array()
  for(var i=0;i<6;i++)Q[i]=new Array()
  if (getpossiblereagents(Q,P)){

   for(var i=0;i<6;i++){
	if(P[i]!=0 && findintermediate(nr0,ss,i,Q,P,0)||!going)return going
   }
   for(var i=0;i<6;i++){
	if(P[i]==0 && findintermediate(nr0,ss,i,Q,P,0)||!going)return going
   }
  }
 }
 return false
}

function findintermediate(nr0,ss,ipt,Q,P,mainptr){
 if(!going)return false
 var i=ipt % 6
 if(!mainptr || P[i]!=0 && i==ipt || P[i]==0 && i!=ipt){	  
	var r=0
	var I=new Array()
	for(var j=0;j<Q[i].length;j++){
		copyarray(P,I,i)
		r=Q[i][j]
		if(Reagenttype[r][2]>=0)I[i]=Reagenttype[r][2]
		if(isreaction(I,r,P)){
		 	sdebug+=ss+listof(P)+"=="+Reagenttype[r][0]+"==> "+listof(I)+"\n"
			REAG[0]++
			REAG[REAG[0]]=r
			if(findpathway(I)){sdebug+=ss+"ok\n";return true}
			REAG[0]=nr0
		}
		if(!going)break
	}
 }
 if(mainptr){
	i=ipt+1
 	if(i==12){
		setTimeout("dosynthesis("+nmax+")",10)
	}else{
		setTimeout("findintermediate("+nr0+",'"+ss+"',"+i+",Q0,PR,true)",10)
	}
 }
 return false
}

function issamecmpd(A,B){
 var slist=A.join(",")
 var s=reversejoin(A)+","
 slist+=","+slist+", "+s+s
 var s=","+B.join(",")+","
 return(slist.indexOf(s)>=0)
}

function reversejoin(A){
 var s=""
 for(var i=0;i<A.length;i++)s=A[i]+(s.length?",":"")+s
 return s
}

function getpossiblereagents(Q,P){
 var n=0
// sdebug+="allows"+allowsulfonic+"\n"
 for(var i=0;i<6;i++){
	if(  SM[i]!=P[i] ||P[i]!=0 || P[i]==0 && allowsulfonic){
		Q[i]=Group[P[i]][5]
		//note! this is a SYMBOLIC LINK!!! (pointer only)
		if(Q[i].length==0)return false
	}
	n+=Q[i].length
 }
 return (n>0)
}

function listof(P){
 var s=""
 for(var i=0;i<6;i++)s+=groupname(P[i])+" "
 return s
}

function isreaction(S,r,P){
 var T=new Array(0,0,0,0,0,0)
 if (!getproduct(S,r,T,true))return false
 return issamecmpd(T,P)  
}

////user interface////

//overloaded:
function doclick(icmpd,which){
	var d=getdivlistbox("message","formg.thegroup")
	ipt=d.selectedIndex-1
	var i=-1
	while(i<0){
		ipt++
		i=d[ipt].value
	}
	d.selectedIndex=ipt
        if(Compound[icmpd][which]==i)i=0
        Compound[icmpd][which]=i
 	drawsub(icmpd,which,i,0)
	showmod(icmpd)
	checkit(icmpd)
}

function docopy(icmpd0,icmpd1){
 for(var i=0;i<6;i++){
        Compound[icmpd1][i]=Compound[icmpd0][i]
        drawsub(icmpd1,i,Compound[icmpd1][i],0)
 }
 showreagent("",false)
 checkit(icmpd1)
}

function dosynthesis(nsteps){
 checkit(0)
 checkit(1)
 setreagent(0)
 //9999 success
 var nr=0
 var slist=""
 var sreag=""
 if(nsteps==9999){
	going=false
	slist= REAG[0]+""
	for(var i=1;i<=REAG[0];i++)slist+=","+REAG[i]
	slist=strsub(slist+",",","+ifromsulfonic+","+itosulfonic+",",",")
	slist+="0"
	REAG=slist.split(",")
	nr=REAG.length-2
	sreag="|||"
	sreag=(nr<3?sreag.substring(0,3-nr):"")
	slist=""+nr
	for(var i=nr;i>0;i--){
		slist=slist+","+REAG[i]
		sreag+="&nbsp;&nbsp;&nbsp;"+(nr==1?"":"<a href='javascript:showreaction("+slist+")'>"+(nr-i+1)+".</a> ")+setsubs(Reagenttype[REAG[i]][0],0)+(i==1?"":"|")
	}
	showreagent(sreag,true)
	if(nr==1)setreagent(REAG[1])
	showproduct(Compound[0],Compound[1])
	//showmessage(sdebug)
	sdebug=""
	return
 }
 if(nsteps<0||nsteps>=maxsteps){
	going=false
	showreagent("",true)
	//showmessage(sdebug)
	sdebug=""
	showalert("No pathway was found for the synthesis of "+Name[1]+" from "+Name[0]+".")
	return
 }
 going=true
 nsteps++
 sdebug=""
 //showmessage(sdebug)
 REAG[0]=0
 showreagent("|||&nbsp;&nbsp;&nbsp;<a href=javascript:dosynthesis(-1)>stop at stage "+nsteps+"</a>",true)
 //sdebug="Compound[0]+" ---> "+Compound[1]+"\n"
 SM=Compound[0]
 nmax=nsteps
 findpathway(Compound[1])
}

function dothereagent(){
 setname(2)
 showreagent("",true)
}

function doreact(){
 checkit(0)
 checkit(1)
 if(!generateproduct(""))return
 checkit(1)
 if(issamecmpd(Compound[0],Compound[1]))showalert("There is no information in the database regarding the reaction of "+Name[2]+" with "+Name[0]+".")
}

function showthecmpd(icmpd,swhat){
        var s=swhat+",H,H,H,H,H,H"
	Compound[icmpd]=new Array()
        getCompoundfromlist(Compound[icmpd],s)
        for(var i=0;i<6;i++)drawsub(icmpd,i,Compound[icmpd][i],0)
	showmod(icmpd)
}


function dothecmpd(icmpd){
	var d=getdivlistbox("info"+icmpd,"form"+icmpd+".thecmpd")
	var i=d[d.selectedIndex].value
	if(i==0 && d[i].text.length)return
	var s=eval("Cmpd"+icmpd+"[i]")
	s=s.substring(s.indexOf("|")+1,s.length)
	d[0].text=""
	showthecmpd(icmpd,s)
}

////initialization////

function loadinfo(){
var s=""
var s2=""
var i=0
initdivs()
setdivpositions()
s="<html><form name=form1>"
s+="<b>PRODUCT</b>"
s+=setselect(1,"thecmpd",Cmpd1,defaultproduct,"XXXXXXXXXXXXXXXXXXXXXXXXXXXX")
//s+='<a href="javascript:dothecmpd(1)">Load</a>'
s+='</form></html>'
writediv("info1",s)

s="<html><form name=form0>"
s+="<b>REACTANT</b>"
s+=setselect(0,"thecmpd",Cmpd0,defaultreactant,"XXXXXXXXXXXXXXXXXXXXXXXXXXXX")
//s+='<a href="javascript:dothecmpd(0)">Load</a>'
s+="</form></html>"
writediv("info0",s)

s="<html><form name=formr>"
s+="<b>&nbsp;&nbsp;REAGENT</b>"
s+=setselect(0,"thereagent",Reagent,0,"")
s+="</form></html>"
writediv("infor",s)

//s="<html><form name=formm>"
//s+="<a name=second>Reaction Information and Retrosynthetic Operations:</a>"
//s+="<br><textarea wrap=virtual name=list rows=10 cols=70></textarea><a href=#atop>top</a>"
//s+="</form></html>"
//s+=setselect(-1,"thegroup",Group,39)

s="<html><form name=formg>"
s+=setselect(-1,"thegroup",Group,3)
s+=" With this selection box, you can create your own compounds."
s+=" To change a substituent, select it from the list and click <B>on the carbon</B>"
s+=" where you want the group to appear. If you click on a carbon already"
s+=" having the selected group, that position will revert to H."
s+=" If the name can be determined easily, it will appear in the appropriate reaction or product selection box."
s+="<a name=how><h3>How It Works: Retrosynthetic Analysis</h3></a>This calculator works from a database containing information about the "
s+="ortho/para- and meta-directing ability of groups around a benzene ring. When you select a reagent and then click on \"React,\" a calculation is done that "
s+="returns the most probable location of reaction for an electrophile. "
s+="When you click on \"Synthesize,\" all possible reactions leading to the desired product (from anything) are determined. "
s+="Only reactions that are compatible with the pre-existing functional groups of the reactant are considered. "
s+="If the reactant is found, then a one-step reaction is returned. If the desired reactant is not found, then all of the reactants of those reactions are "
s+="considered possible \"synthetic intermediates,\" and the process is repeated for reactions leading to <i>them</i>. "
s+="This process is repeated up to five times, at which point the program has either found a route or gives up. "
s+="<a name=caveat><h3>Caveats</h3></a>Ortho products are not displayed even though they may, in fact, be the major product. Many of these reactions would give mixtures. Benzyne intermediates are not considered. "
s+="It's a pretty good calculator, but it can make mistakes. Chemical reactivity isn't really quite this predictable."
s+="</form></html>"
writediv("message",s)
setgrouptypes()
setreagenttypes()
setcompoundlist()

var s=unescape(document.location)
var i=s.indexOf("?")
if(i>=0){
 s2=s.substring(i+1,s.length)
 i=s2.indexOf("?")
 if(i<0){ 
	s=""
 }else{
	s="showthecmpd(0,'"+s2.substring(0,i)+"');"
	s2=s2.substring(i+1,s2.length)
 }
 s+="showthecmpd(1,'"+s2+"');showalert('')"
}else{
 sloadinfo="Select a reactant and a reagent to see the product of a reaction, or select a reactant and a product to search for a pathway. Once the pathway is "
 sloadinfo+="displayed, click on a step number to see the product of that particular step."
 sloadinfo+="\n\nThis page is best viewed full-screen."
 s="dothecmpd(0);dothecmpd(1);showreagent('',true);showalert(sloadinfo)"
}
setTimeout(s,100)
}

function setcompoundlist(){
 var s=""
 for(var i=1;i<Cmpd0.length;i++){
	s=Cmpd0[i]
	s=s.substring(s.indexOf("|")+1,s.length)+",H,H,H,H,H,H"
	Cmpdlist[0][i]=new Array()
        getCompoundfromlist(Cmpdlist[0][i],s)
 }
 for(var i=1;i<Cmpd1.length;i++){
	s=Cmpd1[i]
	s=s.substring(s.indexOf("|")+1,s.length)+",H,H,H,H,H,H"
	Cmpdlist[1][i]=new Array()
        getCompoundfromlist(Cmpdlist[1][i],s)
 }
}

function setgrouptypes(){
 var s=""
 var slist=""
 var d=getdivlistbox("message","formg.thegroup")
 metadeactivators=""
 for(var i=0;i<Group.length;i++){
  slist=d[i].text
  if(slist.indexOf("__")==0){
	if(slist.indexOf("____")!=0)s=slist
  }else{
	Grouptype[i]=s
        if(s.indexOf("meta")>=0)metadeactivators+=(metadeactivators.length?",":"")+groupname(i)
  }
 } 
 //also initializes isulfonic, the removable group
 for(var i=0;i<Group.length;i++){
	Group[i][5]=new Array()
 }
}


