//alert('Hello nmrlab.js')
var oldbackground, highZ=999

function none() {
}
function OpenNewWindow(url,name,options) {
if (window.open) {
    mywindow=window.open(url,name,options)
}
else{
  alert('no popups allowed')
}
}
function OpenWindowMenu(lyrid,url,name,options,message) {
   lyr=xGetElementById(lyrid)
   textlyrid=lyrid+'_text'
   toptabid=lyrid+'_top'
  textlyr=xGetElementById(textlyrid)
  innertext=message+'<BR> If it did not open automatically, your browser may be blocking Pop Up Windows<BR><BR>'
+'<ul><LI><input type="button" OnClick="Javascript:window.open('+"'"+url+"','"+name+"','"+options+"'"+')" value="Manually open in a new window">'
+'<a href="'+url+'"><LI><input type="button" value="Open in this window"></a>'
+'<LI><input type="button"  OnClick="javascript:xDisplay('+"xGetElementById('plotlink'),'none')"+';" value="Close this Window"></ul>'
  xInnerHtml(textlyr,innertext)
  xDisplay(lyr,'block')
}
function EnterValueMenu(lyrid,varname,name,curvalue,form) {
lyr=xGetElementById(lyrid)
   textlyrid=lyrid+'_text'
   toptabid=lyrid+'_top'
   textlyr=xGetElementById(textlyrid)
   innertext='Enter new'+name+':<input name="'+varname+'" value="'+curvalue+'"><input type="button" value="submit">'
   xInnerHtml(textlyr,innertext)
}
function InitWindows(classname) {  //initialize moveable windows
//alert(classname)
moveable = new Array()
moveable=xGetElementsByClassName(classname);
//alert(moveable.length+' windows found')
for (i=0;i<moveable.length;i++) {
  mylyr=moveable[i]
  lyr=xGetElementById(mylyr)
  toptabid=lyr.id+'_top'
  textlyrid=lyr.id+'_text'
  toptab=xGetElementById(toptabid)
  textlyr=xGetElementById(textlyrid)
  lyr.onmouseover = ChangeWindowOnMouse
  lyr.onmouseout = ChangeWindowOnMouse
//  alert(xBackground(toptabid))
  olddisplay=xDisplay(lyr)
  closetabhtml='<div id="'+lyr.id+'_close" class="close" onClick="xDisplay('+"'"+lyr.id+"'"+','+"'"+'none'+"'"+')">&times;</div>'
  xInnerHtml(toptab,xInnerHtml(toptab)+closetabhtml)
  closetab=xGetElementById(lyr.id+'_close')
  xDisplay(lyr,'block')
//  xInnerHtml(toptab,xInnerHtml(toptab)+toptab.id+':'+xHeight(toptab.id)+textlyr.id+':'+xHeight(textlyr))
  xMoveTo(textlyr,0,xHeight(toptab))
  layerheight=Number(xHeight(toptab))+Number(xHeight(textlyr))+20
  layerwidth=Number(xWidth(lyr))
  borderwidth=Number(xGetComputedStyle(lyr,'border-width',true))+Number(xGetComputedStyle(textlyr,'margin',true))
  toptabwidth=layerwidth-borderwidth
//alert(toptabwidth+'='+Number(xWidth(lyr))+'-'+'2*Number('+xGetComputedStyle(lyr,'border-width',true)+')')
  closetableft=Number(toptabwidth)-Number(xWidth(closetab))
  xHeight(lyr,layerheight)
  xWidth(toptab,toptabwidth)
// alert(closetableft+'='+toptabwidth+'-'+xWidth(closetab)+closetabhtml)
  xLeft(closetab,Number(closetableft))
  if (classname == 'moveable') {DragSetup(lyr,toptab)}
  xDisplay(lyr,olddisplay)
//  xAddEventListener(lyr,'mouseover',ChangeWindowOnMouse)
//  xAddEventListener(lyr,'mouseout',ChangeWindowOnMouse)
//  xAddEventListener(toptab,'mouseover',ChangeWindowOnMouse)
//  xAddEventListener(toptab,'mouseout',ChangeWindowOnMouse)
//  xAddEventListener(textlyr,'mouseover',ChangeWindowOnMouse)
//  xAddEventListener(textlyr,'mouseout',ChangeWindowOnMouse)
//alert('Window '+i+'/'+moveable.length+': Added event listener to '+lyr.id)
}
}
function ChangeWindowOnMouse(evt) {
  var e = new xEvent(evt)
  lyrid=e.target.id 
  strg=lyrid.split('_') 
//  alert(lyrid+' '+strg.length)
  if (strg.length > 1) {lyrid=strg[0]}
  toptabid=lyrid+'_top'
  toptab=xGetElementById(toptabid);
  if (toptab != null) {
//     xInnerHtml(toptab.id,'Event:'+e.type+' on '+e.target.id+' changes'+toptabid)
     if (e.type == 'mouseover') { xBackground(toptabid,'#000088')}
     if (e.type == 'mouseout') { xBackground(toptabid,'#0000FF')}
  }
}
function DragSetup(lyr,movetab)
{

  lyrleft=xOffsetLeft(lyr)
  lyrtop=xOffsetTop(lyr)
  xMoveTo(lyr, lyrleft, lyrtop);
  xEnableDrag(movetab, OnDragStart, OnDrag, OnDragEnd);
  xShow(lyr);
}
function OnDragStart(ele, mx, my)
{
movelayer=xParent(ele,false)
 oldbackground=xBackground(movelayer)
 xZIndex(movelayer.id,highZ++)
// xBackground(movelayer,'transparent');
}
function OnDrag(ele, mdx, mdy)
{
movelayer=xParent(ele,false)
  xMoveTo(movelayer, xLeft(movelayer) + mdx, xTop(movelayer) + mdy);
}
function OnDragEnd(ele,mx,my) {
  movelayer=xParent(ele,true)
//  xBackground(movelayer,oldbackground)
}
function xDisplay(e, val) {
//alert('nmrlab_lib Function xDisplay 1')
  if(!(e=xGetElementById(e))) {return null}
  else {
  if(e.style && xDef(e.style.display)) {
          if (xStr(val)) e.style.display = val;
          val = e.style.display
  }
  else if(xDef(e.display)) {
     if (xStr(val)) e.display = val;
     val = e.display
  }
return val
}
}
// xDisplay, Copyright 2003-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

// This was alternative 1:

function xDisplay1(e,s)
{
//alert('Function xDisplay 2');
  if ((e=xGetElementById(e)) && e.style && xDef(e.style.display)) {
    if (document.layers) {alert('Netscape 4')} else {
      try { e.style.display = s; }
     catch (ex) { e.style.display = ''; } // Will this make IE use a default value
    }                                      // appropriate for the element?
    return(e.style.display);
  }
  return(null);
}

function xStyle(ele,prop,val) {
 if(!(ele=xGetElementById(ele))) { return}
 else {
   
  if(ele.style && xDef(ele.style.borderColor)) {
          if (xStr(val)) ele.style.prop = val;
          if (!(ele.style.prop == val)) failed='yes';
	  val = ele.style.prop
  }
  else if(xDef(ele.prop)) {
     if (xStr(val)) ele.prop = val;
     val = ele.prop
     if (!(ele.prov.val == val)) failed='yes';
  }
  return val 
  }
//alert(prop)
}
function InitBox(lyr,type,x,y,xwidth,yheight,boxtext) {
//xInnerHtml('diagnosvar1_text',lyr+' '+type+' '+x+' '+y+' '+xwidth+' '+yheight+' '+boxtext)
  mybox=xGetElementById(lyr)
  if (x < 1) x=1; if (y<1) y=1; 
  xDisplay(mybox,'block') 
//  xMoveTo(mybox,x,y)
//  imgheight=xHeight(myimage)
  if (type=='blackbar') {
     xBackground(mybox,'black')
//     xResizeTo(mybox,500,3)
//     xWidth(mybox,xwidth)
//     xHeight(mybox,yheight) 
     xResizeTo(mybox,xwidth,yheight)
     xMoveTo(mybox,x,y)
     mybox.style.borderStyle='none'
  } 
  if (type=='hide') {
     xDisplay(mybox,'none') 
  }
  if (type=='restore') {
      xDisplay(mybox,'block') 
  } 
  if (type=='redbar') {
     xBackground(mybox,'red')
     xResizeTo(mybox,3,3)
     xResizeTo(mybox,xwidth,yheight)
     xMoveTo(mybox,x,y)
     mybox.style.borderStyle='none' 
//     alert('hello x,y='+x+' '+y) 

  }
  if (type=='zoombox') {
     xDisplay(mybox,'inline')
     xBackground(mybox,'transparent')
     mybox.style.borderStyle='dashed'
     mybox.style.borderWidth='thin'
     mybox.style.borderColor='red'
     xMoveTo(mybox,x,y)
     xResizeTo(mybox,xwidth,yheight)
  }
  if (type == 'textbox') {
    xBackground(mybox,'white')
    xDisplay(mybox,'inline')
    xMoveTo(mybox,x,y)
    mybox.style.borderStyle='none'
  }

//xInnerHtml('diagnosvar1','width (actual/set)='+xWidth(mybox)+'/'+xwidth+'<BR> height (actual/set)='+xHeight(mybox)+'/'+yheight+'<BR> x/y = '+xLeft(mybox)+'/'+xTop(mybox)+'(set: '+x+'/'+y+')<BR>')
if (!(boxtext)) {boxtext=''}
    xInnerHtml(mybox,boxtext)
//     getImageLocation(lyr,'Box dimensions:')
}
function switchlayers (layershow,layerhide) {
mylayer=xGetElementById(layerhide)
xDisplay(mylayer,'none')
mylayer=xGetElementById(layershow)
xDisplay(mylayer,'block')
}
function ChangeButton(buttonname,newval,event,oldaction,newaction,isdisabled) {
   mybutton=xGetElementById(buttonname)
//   alert(mybutton.id)
   if (newval == 'same')  {newval=mybutton.value}
   if (event == 'none') {
      oldaction=''
      newaction=''
   }
    oldisdisabled=mybutton.disabled
    mybutton.value=newval
   xRemoveEventListener(mybutton,event,oldaction)
   xAddEventListener(mybutton,event,newaction)
   if (xDef(isdisabled)) {mybutton.disabled=isdisabled
//          alert(mybutton.id+': Disabled ? '+oldisdisabled+' passed variable: '+isdisabled+' New value: '+isdisabled)
} else {mybutton.disabled=oldisdisabled
//alert(mybutton.id+': Disabled ? '+oldisdisabled+'passed variable: '+isdisabled+' New value: '+oldisdisabled)
}
//cevt=new xEvent(evt)

//xInnerHtml('diagnosvar1_text',cevt.target.id+' '+cevt.type+': \nButton : '+mybutton.id+'\n changed to '+mybutton.value+'\n disabled ? ' +mybutton.disabled+' \n add '+newaction.toString().split('\n')[1]+'\n remove'+oldaction.toString().split('\n')[1])
}
function zoom() {
if (xWidth('cursor2') > 1 & xHeight('cursor2') > 1) { 
   leftmarg=0; rightmarg=0; topmarg=0; bottommarg=0
   expandinit=this.value
   expandinitnew=zoom
   expandinitold=submitform;
   //document.form3.expand.value='reset'
   //var width=imgwidth,height=imgheight;
   x1=xLeft('cursor2');
   x2=x1+xWidth('cursor2');
   y1=xTop('cursor2');
   y2=y1+xHeight('cursor2');
   ChangeButton('cancel','Reset Image','click',ResetCursor,ResetImage,false)
   ChangeButton('expand','Submit Changes','click',zoom,submitform,false)
   InitBox('cursor2','hide',x1,y1)
   InitBox(boxlayer,'blackbar',0,0)
   if (Math.abs(x1-x2) > 2) {factorx=Math.abs((imgwidth)/(x1-x2));}
   else {factorx=1;}
   if (Math.abs(y1-y2) > 2) {factory=Math.abs((imgheight)/(y1-y2));}
   else {factory=1;}
   //factorx=1; factory=1;
   message='x1-x2:'+x1+' '+x2+' y1-y2:'+y1-y2+'\nZoom Factor:'+factorx+' x '+factory;
   //alert(message);
 //  getImageLocation(image,'Previous Image');

   imgwidth=Math.round(imgwidth*factorx)
   imgheight=Math.round(imgheight*factory)
   xResizeTo(image,imgwidth,imgheight)

   if(y1 < y2) {itop=Math.round(y1*factory); ibottom=Math.round(y2*factory)} 
    else        {itop=Math.round(y2*factory); ibottom=Math.round(y1*factory)}
   if (x1 < x2) {ileft= Math.round(x1*factorx); iright=Math.round(x2*factorx)} 
     else         {ileft=Math.round(x2*factorx); iright=Math.round(x1*factorx)}
   xClip(image,itop,iright,ibottom,ileft);

   if (x1 > x2) {imgleft=imgleft-Math.round(factorx*x2)}
    else { imgleft=imgleft-Math.round(factorx*x1) }
   if (y1 > y2) {imgtop = imgtop-Math.round(factory*y2) }
    else { imgtop = imgtop-Math.round(factory*y1)}
   xMoveTo(image,imgleft,imgtop)

//   getImageLocation(image,'New Image Dimensions')
    
}
else {
   xInnerHtml(displaylayer,'Define Zoom Region first')
}
}
function ResetImage() {
mybutton=xGetElementById('expand')
if (mybutton != null) {
  ChangeButton(mybutton,expandinit,'click',expandinitold,expandinitnew)}
mybutton=xGetElementById('cancel')
if (mybutton != null) {
ChangeButton('cancel','Reset Selection','click',ResetImage,ResetCursor)}
InitBox('cursor2','restore',0,0)
imgwidth=imgwidth0; imgheight=imgheight0; imgleft=imgleft0; imgtop=imgtop0;
leftmarg=leftmarg0; rightmarg=rightmarg0; topmarg=topmarg0; bottommarg=bottommarg0;
// getImageLocation(image,'Old Image Dimensions:')
  xResizeTo(myimage,imgwidth,imgheight);
  xMoveTo(myimage,imgleft,imgtop);
  xClip(myimage,0,imgwidth,imgheight,0);
//getImageLocation(image,'Initialized Image Dimensions:')
}
function getImageLocation(img,title) {
lyr=xGetElementById(img)
if (!(lyr=xGetElementById(img))) return
var cwidth=xWidth(lyr)
var cheight=xHeight(lyr)
var cleft=xLeft(lyr)
var ctop=xTop(lyr)
var cclip
if (lyr.style) {cclip=lyr.style.clip } 
else if (lyr.clip) {
    cclpt=lyr.clip.top; cclpr=lyr.clip.right; cclpb=lyr.clip.bottom;
    cclpl=lyr.clip.left;
    cclip='rect('+cclpt+' '+cclpr+' '+cclpb+' '+cclpl+')'  
    }
else {cclip='not defined'}
var cborderstyle=lyr.style.borderStyle
var cbordercolor=lyr.style.borderColor
var cborderwidth=lyr.style.borderWidth
var cbg=xBackground(lyr)
var cevent= new xEvent(evt)
if (cevent.target) {ctarget=cevent.target.id } else {ctarget='undefined'}
message=title+'<BR>'+lyr.id+' '+cevent.type+' '+ctarget+':<BR>Image size:'+cwidth+'w '+cheight+'h <BR>Position'+cleft+'l '+ctop+'t <BR> Clip: '+cclip+'<BR> Background Color: '+cbg+'<BR>Border style color width:'+cborderstyle+' '+cbordercolor+' '+cborderwidth
xInnerHtml('diagnosvar1',message)

}
function xBorderColor(ele,color) {
  if(!(ele=xGetElementById(ele))) {return}
  else {
  if(ele.style && xDef(ele.style.borderColor)) {
          if (xStr(color)) ele.style.borderColor = color;
          color = ele.style.borderColor
  }
  else if(xDef(ele.borderColor)) {
     if (xStr(color)) ele.borderColor = color;
     color = ele.borderColor
  }
return color
}
}
function xBorderStyle(ele,val) {
  if(!(ele=xGetElementById(ele))) {return}                                                                                  
  else {
  if(e.style && xDef(e.style.borderStyle)) {
          if (xStr(val)) ele.style.borderStyle = val;                                                                   
          val = ele.style.borderStyle                                                                                        
  }
  else if(xDef(ele.borderStyle)) {                                                                                         
     if (xStr(val)) ele.borderStyle = val;                                                                             
     val = ele.borderStyle                                                                                                
  }
return val
}
}
function xBorderWidth(ele,val) {                                                                                            
  if(!(ele=xGetElementById(ele))) {return}                                                                                  
  else {                                                                                                                    
  if(ele.style && xDef(ele.style.borderWidth)) {                                                                                
          if (xStr(val)) ele.style.borderWidth = val;                                                                       
          val = ele.style.borderWidth                                                                                       
                                                                                                                            
  }                                                                                                                         
  else if(xDef(ele.borderWidth)) {     
     if (xStr(val)) ele.borderWidth = val
     val = ele.borderWidth                                                                                                  
  }                                                                                                                         
return val                                                                                                                  
}                                                                                                                           
}
function submitform(evt) {
var e = new xEvent(evt)
if (e.target != null) buttonid=e.target.id 
else buttonid=evt.id
//alert(buttonid)
if (buttonid == 'procno') {
  myform=document.SelectFile
  newvalue='Submit'
//alert(myform.name+' '+newvalue)
}
if (buttonid == 'expand') {
  if (specaction == 'Set minimum peak picking') {
     myform=document.form4
     newvalue='Pick Peaks'
  }
  else {
     myform=document.form2
     newvalue='Update Spectrum'
  }
}
if (buttonid == 'createpars') {
  myform=document.form4;
  newvalue='lppl';
//  alert(newvalue)   
}
if (buttonid == 'savecontours') {
  levelform=document.contourlevelform
  result=Number(levelform.numlev.value/2)
  myform=document.form2
  var pref=''
  if (levelform.levelsign[0].checked) {pref='+'}
  if (levelform.levelsign[1].checked) {pref='-'}
  if (result < 1 ) {
     alert('Minimum of one level required'); return}
  if (pref == '' & Math.floor(result) != result) { 
      alert('Please enter an even number of levels\n with a minimum of 2')
      return }
  myform.numlev.value=levelform.numlev.value
  if(levelform.threshold.value == '') {alert('Enter a threshold value'); return}   
  else { myform.threshold.value=pref+levelform.threshold.value}
  if (Number(levelform.incfactor.value) <= 1) {alert('factor must be > 1'); return}
  else{ myform.incfactor.value=levelform.incfactor.value}
  newvalue='Save Contours'
}
//alert('Pressed '+buttonid+' Submit-form:'+myform.name)
name='js_select'
myform.elements[name].value=newvalue
vartext='Form: '+myform.name+'\n'
for (i=0;i<myform.elements.length;i++) {
vartext=vartext+myform.elements[i].name+'='+myform.elements[i].value+'\n'
}
//if (confirm(vartext)) {
myform.submit() // }
}
function PromptAndSubmitValue(message,varname,xselection,xbutton,xform) {
//message: Message for prompt 
//varname: name of variable set
//xselection: Action to be submitted
//alert(xform.form)
//alert('Hello:'+message+varname+xbutton.id+xform+xselection)
var submitvar='js_select'
if (xbutton.form) {myform=xbutton.form}
else {myform=xGetElementById(xform)}
mysubmit=myform.elements[submitvar]
mysubmit.value=xselection
if (xDef(myform.elements[varname])) {
   element=myform.elements[varname]
   var oldvalue=element.value}
else {
   tempelement=xGetElementById(varname)
   if (tempelement != null) {
       var oldvalue=tempelement.value
                }
   else {var oldvalue = ''}
   element=AddHidden(myform,varname,oldvalue)
}  
//alert(element.form.name+': '+element.name+' = '+element.value)
var newvalue=oldvalue
input=window.prompt(message,oldvalue)
//alert('input entered')
if (xDef(input)) {
  lines=new Array()
  lines=input.split('|')
  newvalue=lines.join("\n")
//     alert(oldvalue+' changed to '+newvalue)
  element.value=newvalue
}
else {
  element.value=oldvalue
}
if (element.value != oldvalue & mysubmit.value !='') {
//  if (myform == xbutton.form)  { xbutton.type='submit' }  // might be needed if myform contained pushed button,
							    // but does not go over well in IE
  myform.submit()
}
}
function AddHidden(cform,cvarname,cvarvalue) {
//alert('AddHidden('+cform+','+cvarname+','+cvarvalue+')')
if (cform != 'all') {  //do only specified form
  if (cform.elements) {myform=cform;}
  else {myform=xGetElementById(cform);}
//el = xGetElementById(cvarname)
//alert('Using xGetElementById: '+el+' '+el.name)
// alert(myform.name+myform.elements.length)
  findex=0;
  while (findex < myform.elements.length) {
    if (myform.elements[findex].name == cvarname) {el = myform.elements[findex]; myindex=findex; findex=myform.elements.length}
    findex++
  }
  if (!el) {el = xGetElementById(cvarname)}

//  else {alert('found element '+cvarname+' in '+myform.name+':'+el.name+':'+el.type)}
  if (el && el.type == 'hidden'){ //alert('Setting existing '+el.type+' variable '+el.name+'(old value='+el.value+') to '+cvarvalue)
          el.value=cvarvalue}
  else {
//  alert('Creating new element '+cvarname+' with value '+cvarvalue)
    var el = document.createElement('input');
    el.setAttribute('type', 'hidden');
    el.setAttribute('value',cvarvalue);
    el.setAttribute('name', cvarname)
    el.setAttribute('id', cvarname)
    myform.appendChild(el)
    myindex=myform.elements.length;
  }
//alert('Value set in'+myform.name+':'+el.name+'='+el.value+' ('+myform.elements[myindex].value+')')
return el
}
else {   //change all variables
         vcount=0;
         hiddenvars=xGetElementsByAttribute('input','type','hidden');
          if (hiddenvars.length > 0) {
//            alert('Checking '+hiddenvars.length+' hidden variables')
            for (i=0;i<hiddenvars.length;i++) {   
                if (hiddenvars[i].name == cvarname) {
                   el=hiddenvars[i];
                   el.value=cvarvalue
                   vcount++
               }
            }  
          } // else {alert('no element in hiddenvars')}
//          alert('set '+cvarname+'='+cvarvalue+' '+vcount+' times')
}
}
function SetDate() {
curdate=new Date();// ds= new Array;
ds=curdate.toLocaleString() 
//dsa=new Array
//dsa=ds.split(',')
//document.memberform.date.value=ds[2]+'. '+ds[1]+', '+ds[3];
return ds
}
function padint(intgr,dig) {
str=String(intgr)
strlength=str.length
addlength=dig-strlength
newstr=str
i=0
while (i<addlength) {
  newstr='0'+newstr
  i++
  }
//alert(str+' '+strlength+' '+addlength+' '+newstr)
return newstr
}
function SetWindowWidth() {
 windowhsize=Number(xClientWidth());
 windowvsize=Number(xClientHeight())
//alert('Set Window Width')
 curcookie=xGetCookie('userid')
if (curcookie != null) {
cookievalues=curcookie.split(':')
//alert(curcookie+'\n '+cookievalues.length)
if (cookievalues.length < 5) {
 newcookie=curcookie+':'+windowhsize
// alert('appending '+windowhsize+' to cookie: '+newcookie)
}
else {
 oldvalue=cookievalues[4]
 cookievalues[4]=windowhsize
 newcookie=cookievalues.join(':')
// alert('replacing '+oldvalue+' with '+cookievalues[4]+' :'+newcookie)
}
curdate = new Date()
curdateraw=curdate.getTime()
//curdateraw=Date.parse(curdate)
expdateraw=curdateraw+150000000
expdate=new Date(expdateraw)
//alert('Curdate: '+curdate+'('+curdateraw+') Exp. Date: '+expdate+'( '+expdateraw+') New: '+newcookie)
xSetCookie('userid',newcookie,expdate)
}
AddHidden('all','windowwidth',windowhsize)
AddHidden('all','windowheight',windowvsize)
}
