var logoTimer;
var inMal = false;
var inDrag = false;
var ivTogEf;
var dsFx1;
var colP;

String.prototype.taki = function(){ //v1.0
	return this.replace(/[a-zA-Z]/g, function(c){
		return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
	});
};


Sortables.implement({
  serialize: function(){
      var serial = [];
      this.list.getChildren().each(function(el, i){
				     serial[i] = el.getProperty('id');
				   }, this);
      return serial;
    }
  });

function hideLogo() {
  var hd = new Fx.Styles('itolLogo', {duration: 1000, onComplete: function(){$('itolLogo').style.display='none';} });
  hd.start({
      'opacity':[1,0],
	'height':[90, 0]
	});
  clearInterval(logoTimer);
}

function getViews(tID,ct,ncon) {
 var rows = '<tr><th>Label</th><th>Note</th></tr>';
 for (var i=0; i < views[tID].length; i+=3) {
   if (ncon) {
     rows = rows + '<tr><td><a href="restoreView.cgi?ct=' + ct + '&amp;view=' + views[tID][i] + '">' + views[tID][i+1] + '</a></td><td>' + views[tID][i+2] + '</td></tr>';
   } else {
     rows = rows + '<tr><td><a href="restoreView.cgi?ct=' + ct + '&amp;view=' + views[tID][i] + '">' + views[tID][i+1] + '</a></td><td><a class="vClo" onclick="popDelView(\'' + tID + '\',\'' +  i + '\');"></a><a id="vn' + views[tID][i] + '" onmousedown="noteMal(this, \'' + i + '\',\'' + tID + '\');" class="noteMal">' + views[tID][i+2] + '</a></td></tr>';
   }
 }

  return overlib('<table class="viewPop">' + rows + '</table>', STICKY, MOUSEOFF, OFFSETX,0,OFFSETY,0,TIMEOUT, 3000);
}

window.addEvent('domready', function(){
		  if ($('intVCont')) {
		    ivTogEf = new Fx.Slide('intVCont').hide();
		  }
		  if (!document.URL.match(/personal_page.cgi/) ) {
		    return;
		  }

		  if ($('itolLogo')) {
		    //$('itolLogo').style.display='none';
		    logoTimer = setInterval (hideLogo, 1000);	    
		  }
		  if (colP) {
		    for (var i = 0; i < colP.length; i++) {
		      var tPr = $E('.proCont', $(colP[i]));
		      if (!tPr.eff) {
			tPr.eff = new Fx.Slide(tPr).hide();
			$E('.bMin', $(colP[i])).addClass('bMax');
		      }
		    }
		  }
		  $$('.bSh').each(function(item){
		      item.removeEvents('mouseover');
		      item.removeEvents('mouseout');
		      item.addEvent('mouseover', function(ev){
			  return overlib('<b>This project is shared.</b>',WRAP);
			}.bind(this));
		      item.addEvent('mouseout', function(ev){
			  return nd();
			}.bind(this));
		    }.bind(this));
		  
		  $$('.oTab').each(function(item){
				     item.removeEvents('mouseover');
				     item.removeEvents('mouseout');
				     item.addEvent('mouseover', function(ev){
						     ev = new Event(ev);
						     var tgt = $E('.wClo', ev.target.parentNode);
						     clearInterval(tgt.Tmr);
						     tgt.style.display = 'inline';
						   }.bind(this));
				     item.addEvent('mouseout', function(ev){
						     ev = new Event(ev);
						     var tgt = $E('.wClo', ev.target.parentNode);
						     tgt.Tmr = setInterval( function(){tgt.style.display = 'none'; clearInterval(tgt.Tmr);}, 1500);
						   }.bind(this));
				   }.bind(this));

		  $$('.bMin').each(function(item){
				     item.removeEvents('mousedown');
				     item.addEvent('mousedown', function(ev){
						     ev = new Event(ev);
						     ev.stop();
						     var tPr = $E('.proCont', ev.target.parentNode.parentNode);
						     if (!tPr.eff) {
						       tPr.eff = new Fx.Slide(tPr);
						     }
						     if (ev.target.hasClass('bMax')) {
						       tPr.eff.slideIn();
						       ev.target.removeClass('bMax');
						       new Ajax('ajax/updatePos.cgi', {
							 method: 'post',
								    data: 'pr=' + ev.target.parentNode.parentNode.id + '&col=u',
								    onFailure: function(){ return overlib('<span style="background: #faa;">ERROR saving state into database</span>', WRAP, TIMEOUT, 3000);}
							 }).request();

						     } else {
						       tPr.eff.slideOut();
						       ev.target.addClass('bMax');
						       new Ajax('ajax/updatePos.cgi', {
							 method: 'post',
								    data: 'pr=' + ev.target.parentNode.parentNode.id + '&col=c',
								    onFailure: function(){ return overlib('<span style="background: #faa;">ERROR saving state into database</span>', WRAP, TIMEOUT, 3000);}
							 }).request();
						     }
						   }.bind(this));
				   }.bind(this));
		  $$('.bOpt').each(function(item){
				     item.removeEvents('mousedown');
				     item.addEvent('mousedown', function(ev){
						     ev = new Event(ev);
						     ev.stop();
						     var pID = ev.target.parentNode.parentNode.id;
						     overlib('<p style="margin:2px 0; white-space:nowrap;"><a onclick="popMTT(\'' + pID + '\');">Move to workspace...</a><br /><a onclick="sharePro(\'' + pID + '\');">Toggle project sharing</a><br /><a onclick="removePro(\'' + pID + '\');">Delete project</a></p>', STICKY,WRAP,MOUSEOFF,OFFSETY,5,OFFSETX,5,LEFT,CAPTION, 'Project options',CLOSECLICK);
						   }.bind(this));
				   }.bind(this));
		  
		  if ($('projects')) {
		    var pSort = new Sortables($('projects'), {
		      handles: $$('.pHead'),
						  onComplete: function(){
						  new Ajax('ajax/updatePos.cgi', {
						    method: 'post',
							       data: 'pOrd=' + pSort.serialize(),
							       onFailure: function(){ return overlib('<span style="background: #faa;">ERROR saving positions into database</span>', WRAP, TIMEOUT, 3000);}
						    }).request();
						}
		      }
		      );
		  }

		  headTits = $$('.pHeadTit').concat($$('.cTT'));
		  headTits.each(function(item) {
				  item.removeEvents('mousedown');
				  item.removeEvents('mouseover');
				  item.removeEvents('mouseout');
				  item.addEvent('mousedown', function(ev){
						  new Event(ev).stop();
						  inMal = true;
						  if (!item.hasFocus) {
						    item.hasFocus=true;
						    item.removeClass('malItemActive');
						    var cont = item.innerHTML;
						    item.oldContent = cont;
						    var ts = item.getStyle('font-size');
						    cont = cont.replace(/\"/g, "&#34;");
						    cont = cont.replace(/\'/g, "&#39;");
						    var tWid = item.parentNode.offsetWidth * 0.75;
						    item.innerHTML = "<input style='width:" + tWid + "px;' type='text' value=\"" + cont + "\" id='" + item.id + "_title' onkeypress='checkMalInput(event, \"" + item.id + "\");' onblur='malUpdate(\"" + item.id + "\");' />";
						    item.addClass('malItemEdit');
						    $(item.id + '_title').setStyle('font-size', ts);
						    $(item.id + '_title').focus();
						    return nd();
						  }
						}.bind(this)
						);
			 			 
				  item.addEvent('mouseover', function() {
						  if (!item.hasFocus) {
						    item.addClass('malItemActive');
						  }
						}.bind(this));
				  
				  item.addEvent('mouseout', function() {
						  if (!item.hasFocus) {
						    item.removeClass('malItemActive');
						  }
						}.bind(this));
				}.bind(this));
		  descriptions = $$('.pDesc').concat($$('.tDesc')).concat($$('.tNote'));
		  descriptions.each(function(item) {
				      item.removeEvents('mousedown');
				      item.removeEvents('mouseover');
				      item.removeEvents('mouseout');
				      item.addEvent('mousedown', function(){
						      if (!item.hasFocus) {
							item.hasFocus=true;					
							item.removeClass('malItemActive');
							var cont = item.innerHTML;
							item.oldContent = cont;
							var ts = item.getStyle('font-size');
							var tWid = item.getStyle('width');
							cont = cont.replace(/\"/g, "&#34;");
							cont = cont.replace(/\'/g, "&#39;");
							item.innerHTML = "<input style='width:" + tWid + ";' type='text' value=\"" + cont + "\" id='" + item.id + "_title' onkeypress='checkMalInput(event, \"" + item.id + "\");' onblur='malUpdate(\"" + item.id + "\");' />";
							item.addClass('malItemEdit');
							$(item.id + '_title').focus();
							return nd();
						      }
						    }.bind(this)
						    );		       
				      item.addEvent('mouseover', function() {
						      if (!item.hasFocus) {
							item.addClass('malItemActive');
						      }
						     }.bind(this));				      
				      item.addEvent('mouseout', function() {
						      if (!item.hasFocus) {
							item.removeClass('malItemActive');
						      }
						    }.bind(this));
				    }.bind(this));

		  $$('.tdH').each(function(item) {
				    item.removeEvents('mousedown');
				    item.removeEvents('mouseover');
				    item.removeEvents('mouseout');
				    item.addEvent('mouseover', function() {
						    if (inDrag) { return;}
						    overlib('<b>Click and drag the tree to another project</b>',WRAP,TIMEOUT,1000);						    
					  }.bind(this));
				      
				    item.addEvent('mouseout', function() {
						      return nd();
						    }.bind(this));

				    item.addEvent('mousedown', function(){
						    inDrag = true;
						    nd();
						    var row = item.parentNode.parentNode;
						    row.origTable = row.parentNode.id;
						    row.origPlace = row.previousSibling;
						    row.style.top = item.parentNode.getTop();
						    row.style.left = item.parentNode.getLeft();
						    new Drag.Move(row, {
						      container: $('currentTab'),
								      droppables: $$('.Ptrees')
								      });
						    row.addEvent('emptydrop', function(){
								   if (!inDrag) {return;}
								   this.setStyle('position', 'static');
								   this.injectAfter(this.origPlace);
								   this.setStyle('top', this.getTop());
								   this.setStyle('left', this.getLeft());
								 });
						  }.bind(this));
				    
				  });



		  $$('.Ptrees').each(function(drop, index){
				       drop.removeEvents('leave');
				       drop.removeEvents('over');
				       drop.removeEvents('drop');
				       drop.addEvents({
					   'over': function(el, obj){
					     if ($('tmpRow')) { return;}
					     if (this.id == el.origPlace.parentNode.parentNode.id) { return; }
					     var trow = el.clone();
					     trow.setStyle('position', 'static');
					     trow.setStyle('background-color', '#faa');
					     trow.id = 'tmpRow';
					     trow.injectInside(this.firstChild);
					   },
					     'leave': function(el, obj){
					     if ($('tmpRow')) { $('tmpRow').remove();}
					   },
					     'drop': function(el, obj){
							if (!inDrag) { return;}
					     inDrag=false;
					     if (this.id == el.origPlace.parentNode.parentNode.id) { 
								    el.setStyle('position', 'static');
								    el.injectAfter(el.origPlace);
								    el.setStyle('top', el.getTop());
								    el.setStyle('left', el.getLeft()); 
								    return; 
					     }
					     if ($('tmpRow')) {$('tmpRow').remove();}
					     var tgt = this.firstChild;
					     var upA = new Ajax('ajax/updatePos.cgi',
								{
								method: 'post',
								    data: 'tr=' + el.id + '&pr=' + this.id,
								    onComplete: function(){moveOk(el,tgt);},
								    onFailure: function(){moveErr(el);}
								  
								}
								).request();
					     
					   }
					 });
				     });

		});
window.addEvent('load', function() {
		  if ($('uploadF')) {
		    $('uploadF').target = 'upRes';
		    $('uploadF').setAttribute('target', 'upRes');
		  }
		});

function ckDSupload(res,addBRCIcon) {
  if (!res) { return;}
  dsFx1.slideOut();
  if ($('DSupRes')) { $('DSupRes').remove(); }
  var resDiv = new Element('div').setProperty('id', 'DSupRes').injectTop($('newDS'));
  var resCon = frames['upRes'].document.getElementById('res');
  if (res == 3) {
    resDiv.innerHTML = resCon.innerHTML;
  } else {
    if (res < 4) {
      var tc = frames['upRes'].document.getElementById('tcell');
      var box = new Element('span');
      box.innerHTML = resCon.innerHTML;
      if ($(tc.innerHTML).innerHTML == '-') { $(tc.innerHTML).innerHTML = '' }
      box.injectInside($(tc.innerHTML));
    }
    if (res == 1 || res == 5) {
      resDiv.remove();
      $('newDSov').style.display='none';
      $('newDS').style.display='none';
    } else {
      var log = frames['upRes'].document.getElementById('output');
      resDiv.innerHTML = log.innerHTML;
    }
  }
  if (addBRCIcon) {
    var tc = frames['upRes'].document.getElementById('tcell').innerHTML.split(/_ds/)[0];
    var icon = new Element('span');
    icon.innerHTML = "<img src='img/has_brc.gif' alt='BC' onmouseover='return overlib(\"&lt;b&gt;Colored branches&lt;/b&gt;\", WRAP);' onmouseout='return nd();' />";
    icon.injectInside($E( ".tFeat", tc));
  }
  $('upRes').src = '';
}


function moveOk (el,wh) {
               el.setStyle('position','static');
               el.injectInside(wh);
               el.setStyle('top', el.getTop());
               el.setStyle('left', el.getLeft());
}
function moveErr (el) {
	overlib('<span style="background: #faa;">ERROR saving new position</span>',WRAP, TIMEOUT, 3000);
	el.setStyle('position', 'static');
	el.injectAfter(el.origPlace);
	el.setStyle('top', el.getTop());
	el.setStyle('left', el.getLeft());

}

function malUpdate(itemId) {
  inMal = false;
  if ($(itemId).hasFocus) {
    var newText = $(itemId + '_title').value;
    if (newText == '') {
      alert('Fields cannot be empty');
      $(itemId).innerHTML = $(itemId).oldContent;
      $(itemId).hasFocus = false;
      $(itemId).removeClass('malItemEdit');
      return;
    }
    if (newText == $(itemId).oldContent) {
      $(itemId).innerHTML = newText;
      $(itemId).hasFocus = false;
      $(itemId).removeClass('malItemEdit');
      return;
    }
    var upA = new Ajax('ajax/updateData.cgi', 
		       {
		       method: 'post',
			   data: 'id=' + itemId + '&data=' + escape(newText),
				   onComplete: function(){endMal(itemId);},
				   onFailure: function(){failedUpdate(itemId);}
			   }
		       ).request();

  }
}

function endMal(itemId) {
  var newText = $(itemId + '_title').value;
  $(itemId).hasFocus = false;
  $(itemId).removeClass('malItemEdit');
  $(itemId).innerHTML = newText;
  if ($(itemId).ntIdx == 'dsl') {
	dsLabs[itemId] = newText;
  } else if ($(itemId).ntIdx) {
    var ntI = parseInt($(itemId).ntIdx) + 2;
    views[$(itemId).tree][ntI] = newText;
  }
}
function failedUpdate(itemId) {
  $(itemId).hasFocus = false;
  $(itemId).removeClass('malItemEdit');
  $(itemId).innerHTML = $(itemId).oldContent;
  overlib("<p style='margin:0; padding: 10px;background: #faa;'>ERROR: Couldn't update the database</p>", STICKY, TIMEOUT, 3000, WRAP);
}

function checkMalInput(oEvent, itemId) {
  if ((oEvent.keyCode && oEvent.keyCode==13)
      || (oEvent.which && oEvent.which==13)) {
    malUpdate(itemId);
  }
}
function popCopy(id) {
  overlib('<p style="margin:2px 0; white-space:nowrap;"><a onmouseover=\'overlib2("This function will copy this tree into a project &rsquo;<b>Imported trees</b>&rsquo; in your own iTOL account. The project will be automatically created if it does not exist.")\' onmouseout=\'return cClick2();\'  onclick="doCopyTree(\'' + id.substr(1) + '\');">Copy tree to your iTOL account</a></p>', EXCLUSIVE,STICKY,WRAP,MOUSEOFF,OFFSETY,0,OFFSETX,0,LEFT,CAPTION, 'Tree functions',CLOSECLICK); 
}

function popNT() {
  overlib('<h1 style="margin:0;padding:0;">Add a new workspace</h1><table><tr><td><b>Workspace name:</b></td><td><input type="text" size="30" id="newTnm" /></td></tr><tr><td><b>Description:</b></td><td><input type="text" size="30" id="newTde" /></td></tr><tr><td></td><td><input type="button" width="150px" value="Add workspace" onclick="addNewTab()" /><input type="button" width="150px" value="Cancel" onclick="cClick();" /></td></table>', WRAP, STICKY,VAUTO,HAUTO,OFFSETX,0,OFFSETY,0);
  $('newTnm').focus();
}
function popNP() {
  overlib('<h1 style="margin:0;padding:0;">Add a new project</h1><table><tr><td><b>Project name:</b></td><td><input type="text" size="30" id="newPnm" /></td></tr><tr><td><b>Description:</b></td><td><input type="text" size="30" id="newPde" /></td></tr><tr><td></td><td><input type="button" width="150px" value="Add project" onclick="addNewProject()" /><input type="button" width="150px" value="Cancel" onclick="cClick();" /></td></table>', WRAP, STICKY,VAUTO,HAUTO);
  $('newPnm').focus();
}

function renameTree(id) {
  var nm = $E('.trLn',$(id)).innerHTML;
  overlib2('<table><tr><td><b>New name:</b></td><td><input type="text" size="30" id="newTrnm" /></td></tr><tr><td></td><td><input type="button" width="150px" value="Rename tree" onclick="doRenTree(\'' + id + '\')" /><input type="button" width="150px" value="Cancel" onclick="cClick2();" /></td></tr></table>', CAPTION, 'Rename tree ' + nm + ' ?', WRAP, STICKY,VAUTO,HAUTO);
  $('newTrnm').focus();
}
function doRenTree(id) {
  if (!$('newTrnm').value.length > 0) { return cClick(); }
  new Ajax('ajax/renameTree.cgi', {
    method: 'post',
	       data: 'nm=' + escape($('newTrnm').value) + '&id=' + id,
	       onComplete: function(){$E('.trLn',$(id)).innerHTML = $('newTrnm').value; cClick2(); cClick();},
	       onFailure: function(){ return overlib('<span style="background: #faa;">ERROR renaming tree</span>', WRAP, TIMEOUT, 3000);}
    }).request(); 
}

function doDupTree(id) {
  if (!id.length > 0) { return cClick2(); }
  new Ajax('ajax/duplicateTree.cgi', {
    method: 'post',
	       data: 'tree=' + id,
	       onComplete: addDupTree,
	       onFailure: function(){ return overlib('<span style="background: #faa;">ERROR duplicating the tree</span>', WRAP, TIMEOUT, 3000);}
    }).request(); 
}

function doCopyTree(id) {
  if (!id.length > 0) { return cClick2(); }
  new Ajax('ajax/copySharedTree.cgi', {
    method: 'post',
	       data: 'tree=' + id,
	       onComplete: function(){ return overlib('<span style="background: #afa;">Tree sucessfully copied to your account</span>', WRAP, TIMEOUT, 3000);},
	       onFailure: function(){ return overlib('<span style="background: #faa;">ERROR copying the tree</span>', WRAP, TIMEOUT, 3000);}
    }).request(); 
}

function addDupTree(res) {
  var rDt = res.split(/\n/);
  var nRow = $('T'+rDt[0]).clone();
  nRow.id = 'T'+rDt[1];
  for (var i = 0; i < 8; i++) {
    nRow.cells[i].innerHTML = rDt[i+2];
  }
  nRow.cells[3].id = 'T' + rDt[1] + '_ds';
  nRow.injectAfter($('T'+ rDt[0]).parentNode.getLast());
  var dG = $E('.tdH', nRow);
  dG.addEvent('mouseover', function() {
		if (inDrag) { return;}
		overlib('<b>Click and drag the tree to another project</b>',WRAP,TIMEOUT,1000);						    
	      }.bind(this));
  
  dG.addEvent('mouseout', function() {
		return nd();
	      }.bind(this));
  dG.addEvent('mousedown', function(){
		  inDrag = true;
		  nd();
		  var row = dG.parentNode.parentNode;
		  row.origTable = row.parentNode.id;
		  row.origPlace = row.previousSibling;
		  row.style.top = dG.parentNode.getTop();
		  row.style.left = dG.parentNode.getLeft();
		  new Drag.Move(row, {
		    container: $('currentTab'),
				    droppables: $$('.Ptrees')
				    });
		  row.addEvent('emptydrop', function(){
				 if (!inDrag) {return;}
				 this.setStyle('position', 'static');
				 this.injectAfter(this.origPlace);
				 this.setStyle('top', this.getTop());
				 this.setStyle('left', this.getLeft());
			       });
		}.bind(this));
  
  return cClick();
}

function addNewTab() {
  if ($('newTnm').value == '') {
    alert("New workspace needs a name..."); cClick();
    return;
  }
  new Ajax('ajax/newTab.cgi', {
            method: 'post',
            data: 'nm=' + escape($('newTnm').value) + '&de=' + escape($('newTde').value),
            onComplete: mkTabBut,
            onFailure: function(){ return overlib('<span style="background: #faa;">ERROR inserting new workspace into the database</span>', WRAP, TIMEOUT, 3000);}
                          }).request();  
}
function mkTabBut(res) {
  var resA = res.split(/,/);
  tabs[tabs.length] = [ $('newTnm').value , resA[0]];
  var nTab = new Element('li');
  nTab.id = 'tb' + resA[0];
  nTab.innerHTML='<a class="oTab" href="personal_page.cgi?cT=' + resA[0] + '">' + $('newTnm').value + '</a>';
  nTab.injectBefore($E('.newTab', $('topTabs')));
  cClick();
}
function addNewProject() {
  if ($('newPnm').value == '') {
    alert("New projects need a name..."); cClick();
    return;
  }
  new Ajax('ajax/newProject.cgi', {
            method: 'post',
            data: 'ct=' + $('ct').value + '&nm=' + escape($('newPnm').value) + '&de=' + escape($('newPde').value),
            onComplete: mkProjBox,
            onFailure: function(){ return overlib('<span style="background: #faa;">ERROR inserting new project into the database</span>', WRAP, TIMEOUT, 3000);}
                          }).request();  
}
function mkProjBox(res) {
  curP = $$('.project');
  if (curP.length == 0) {
    window.location.reload(); 
    return;
  }
  var mT = $E('.proCont', curP[curP.length-1]).getStyle('margin-top');
  var newP;
  if (parseInt(mT.substr(0,mT.length-2)) < 0) {
    $E('.proCont', curP[curP.length-1]).eff.show();
    newP = curP[curP.length-1].clone();
    $E('.proCont', curP[curP.length-1]).eff.hide();
  } else {
    newP = curP[curP.length-1].clone();
  }

  newP.id = 'p' + res;
  $E("table", newP).id = 'pTr' + res;
  $ES(".tdM", newP).empty();
  $E(".pHeadTit", newP).innerHTML = $('newPnm').value;
  var des = 'No description.';
  if ($('newPde').value != '') { des = $('newPde').value;}
  $E(".pDesc", newP).innerHTML = des;
  $E('.ntUp', newP).href='upload.cgi?pID=p' + res;
  if (newP.style.display == 'none') {
    newP.style.display = 'block';}
  newP.injectAfter(curP[curP.length-1]);
  window.fireEvent('domready');
  cClick();
}
function popMTT(id) {
  var ln = '<p style="margin: 2px; font-size: 14px">';
  for (var i=0 ; i<tabs.length ; i++) {
    ln = ln + '<a onclick="mptt(\'' + id + '\',' + tabs[i][1] + ');">' + tabs[i][0] + '</a><br />';
  }
  overlib2(ln + '</p>', WRAP, STICKY, LEFT,CLOSECLICK,CAPTION, 'Select new workspace:');
}
function mptt(pr, tb) {
  new Ajax('ajax/updatePos.cgi', {
            method: 'post',
            data: 'pr=' + pr + '&tb=' + tb,
            onComplete: function(){ $(pr).remove();cClick();},
            onFailure: function(){ return overlib('<span style="background: #faa;">ERROR moving project within the database</span>', WRAP, TIMEOUT, 3000);}
                          }).request();	
}
function sharePro(id) {
  cClick();
  new Ajax('ajax/shareProject.cgi', {
            method: 'post',
            data: 'dpr=' + id,
            onComplete: toggleShared,
            onFailure: function(){ return overlib('<span style="background: #faa;">ERROR setting the shared flag in the database</span>', WRAP, TIMEOUT, 3000);}
                          }).request();
}
function toggleShared(res) {
  var t = res.split(/=/);
  var el = $E(".bSh",$("ph"+ t[0]));
  if (t[1] == 1) {
    el.setStyle("display", "block");
    //    $('p' + t[0]).setStyle("background-color", "#ffffee");
    $('p' + t[0]).addClass("sharedPro");
  } else {
    el.setStyle("display", "none");
    //    $('p' + t[0]).setStyle("background-color", "#ffffff");
    $('p' + t[0]).removeClass("sharedPro");
  } 
}

function removePro(id){
  overlib2('This will remove all trees and data associated with this project. <br /><b style="background: #faa;font-size:14px;">This operation CANNOT BE UNDONE.</b><br />Please make sure you do not delete the data you might still need.<p><input type="button" value="Remove project" onclick="doRemovePro(\'' + id + '\');" /> <input type="button" value="Cancel" onclick="return cClick();" /></p>', MODAL, STICKY,WRAP,CAPTION, 'Remove project?',OFFSETX,0,OFFSETY,0,CLOSECLICK);
}
function doRemovePro(id) {
  new Ajax('ajax/removeProject.cgi', {
            method: 'post',
            data: 'dpr=' + id,
            onComplete: function(){ $(id).remove();cClick();},
            onFailure: function(){ return overlib('<span style="background: #faa;">ERROR removing project from the database</span>', WRAP, TIMEOUT, 3000);}
                          }).request();
}
function noteMal(item,idx,tr) {
  // new Event(ev).stop();
  inMal = true;
  item.ntIdx = idx;
  item.tree = tr;
  if (!item.hasFocus) {
    item.hasFocus=true;
    //item.removeClass('malItemActive');
    var cont = item.innerHTML;
    item.oldContent = cont;
    cont = cont.replace(/\"/g, "&#34;");
    cont = cont.replace(/\'/g, "&#39;");
    if (cont == 'Click to add') cont = '';
    var tWid = item.parentNode.offsetWidth * 0.75;
    item.innerHTML = "<input style='width:" + tWid + "px;' type='text' value=\"" + cont + "\" id='" + item.id + "_title' onkeypress='checkMalInput(event, \"" + item.id + "\");' onblur='malUpdate(\"" + item.id + "\");' />";
    item.addClass('malItemEdit');
    //   $(item.id + '_title').setStyle('font-size', '10px');
    $(item.id + '_title').focus();
  }
}
function popDelView(tree,idx){
  idx = parseInt(idx);
  overlib2('<b style="background: #faa;font-size:14px;">This operation CANNOT BE UNDONE.</b><br />Please make sure you do not delete the data you might still need.<p><input type="button" value="Remove saved view" onclick="doRemoveView(\'' +  tree + '\',\'' + idx + '\');" /> <input type="button" value="Cancel" onclick="cClick2();" /></p>', MODAL,EXCLUSIVE,STICKY,WRAP,CAPTION, 'Remove saved view "' +  views[tree][idx+1] + '" ?',OFFSETX,0,OFFSETY,0,CLOSECLICK);
}

function doRemoveView(tree, idx) {
  idx = parseInt(idx);
  new Ajax('ajax/removeView.cgi', {
    method: 'get',
	       data: 'id=' + views[tree][idx],
	       onComplete: function(){ views[tree].splice(idx,3); cClick(); },
	       onFailure: function(){ return overlib('<span style="background: #faa;">ERROR removing saved view from the database</span>', WRAP, TIMEOUT, 3000);}
    }).request();
}

function popASett(ct) {
 overlib('<p style="margin:2px 0; white-space:nowrap;"><a onclick="popChPass();">Change login password</a><br /><a onclick="popChBatchKey()">Enable/disable batch upload</a><br /><a onmouseover=\'overlib2("This will check your current browser for saved tree views and uploaded trees, and import these into a new project called <b>Imported trees</b>. <p>If these trees are already present in your projects, they will be skipped.</p>");\' onmouseout=\'return nd2();\' onclick="importTrees(' + ct + ');">Import trees from current browser</a></p>', STICKY,WRAP,MOUSEOFF,OFFSETY,0,OFFSETX,0,LEFT,CAPTION, 'Account settings',CLOSECLICK);
}
function importTrees(ct) {
  new Ajax('ajax/importTrees.cgi', {
    method: 'get',
	       data: 'ct=' + ct,
	       onComplete: function(res){ 
		if (res == 1) {
		  window.location.reload(); 
		} else if (res == 2) {
		  return overlib('<b>No trees or saved views associated with this browser.</b>', WRAP, TIMEOUT, 4000);
		} else if (res == 3) {
		  return overlib('<b>Trees and saved views are already imported and included in your projects.</b>', WRAP, TIMEOUT, 4000);
		}
	  },
		onFailure: function(){ return overlib('<span style="background: #faa;">ERROR importing trees into the database</span>', WRAP, TIMEOUT, 3000);}
    }).request();
}

function popChBatchKey() {
  if (batchHash) {
	overlib2("Batch upload to your account is currently <b>enabled</b>.Use the following ID to upload: <br><div id='uplID'>" + batchHash + "</div><p  style='text-align:center'><input type='button' onclick='disableBatchUpl()' value='Disable'> <input type='button' onclick='newBatchUpl()' value='Generate new ID'><p style='text-align:center'><a href='help/batch_help.shtml'>About batch upload/download</a>", CAPTION, "Batch upload control", CLOSECLICK,WRAPMAX, 400,STICKY,VAUTO,HAUTO,OFFSETY,-1,OFFSETX,-1);
  } else {
	overlib2("Batch upload to your account is currently <b>disabled</b>. You can enable it and generate a new upload ID by clicking:<p style='text-align:center'><input type='button' onclick='newBatchUpl()' value='Generate new upload ID'><p style='text-align:center'><a href='help/batch_help.shtml'>About batch upload/download</a>", CAPTION, "Enable batch upload", CLOSECLICK,WRAPMAX, 400,STICKY,VAUTO,HAUTO,OFFSETY,-1,OFFSETX,-1);
  }
}

function disableBatchUpl() {
  new Ajax('ajax/disableBatch.cgi', {
	method: 'get',
		onComplete: function(){ batchHash = 0; cClick(); return overlib('<span style="background: #afa;">Batch upload disabled</span>', WRAP, TIMEOUT, 4000);},
		onFailure: function(){ cClick(); return overlib('<span style="background: #faa;">ERROR disabling batch upload</span>', WRAP, TIMEOUT, 3000);}
	}).request();
}

function newBatchUpl() {
  new Ajax('ajax/enableBatch.cgi', {
	method: 'get',
		data: 'k=n',
		onComplete: batchEnabled,
		onFailure: function(){ cClick2(); cClick(); return overlib('<span style="background: #faa;">ERROR generating new upload ID</span>', WRAP, TIMEOUT, 3000);}
	}).request();
}

function batchEnabled(res) {
  cClick2();
  batchHash = res;
  return overlib2("Your upload ID was changed. In the future, use the following ID to upload: <br><div id='uplID'>" + batchHash + "</div><p  style='text-align:center'><input type='button' onclick='cClick();' value='OK'>", CAPTION, "New Upload ID generated", CLOSECLICK,WRAPMAX, 400,STICKY,VAUTO,HAUTO,OFFSETY,-1,OFFSETX,-1);
}

function popChPass() {
  overlib2('<form onsubmit="doChPass()"><h1 style="margin:0;padding:0;">Change your login password:</h1><table><tr><td><b>Current password:</b></td><td><input type="password" size="30" tabindex="1" name="cp" id="curPass" /></td></tr><tr><td><b>New password:</b></td><td><input type="password" size="30" tabindex="2" name="np" id="newPass" /></td></tr><tr><td><b>New password again:</b></td><td><input name="np" onfocus="$(\'passErr\').innerHTML=\'\';" type="password" size="30" tabindex="3" name="np2" id="newPass2" /></td></tr><tr><td><span style="color:red" id="passErr"></span></td><td><input type="button" width="150px" value="Change" onclick="doChPass()" /><input type="button" width="150px" value="Cancel" onclick="cClick2();" /></td></table></form>', EXCLUSIVE, CLOSECLICK, WRAP, STICKY,VAUTO,HAUTO,OFFSETY,0);
  $('curPass').focus();
}
function doChPass() {
  if (!$('newPass').value) { $('passErr').innerHTML='Password cannot be empty.';$('newPass2').value = '';$('newPass').focus(); return;}
  if ($('newPass').value != $('newPass2').value) {
    $('newPass').value = ''; $('newPass2').value = ''; $('passErr').innerHTML='Password mismatch.'; $('newPass').focus(); return;}
   new Ajax('ajax/chPass.cgi', {
     method: 'post',
		data: 'op=' + escape($('curPass').value.taki()) + '&np=' + escape($('newPass').value.taki()),	       onComplete: function(){ overlib('<b>Password changed.</b>', WRAP, TIMEOUT, 3000); },
		onFailure: function(){ overlib('<span style="background: #faa;">ERROR changing password.</span>', WRAP, TIMEOUT, 5000);}
    }).request();

}
function popTopt(id) {
  var nm = $E('.trLn',$(id)).innerHTML;
  var dsAdd = '<br /><a onclick="popDatasetAdd(\'' + id + '\');">Add a dataset</a>';
  var clrDs = '<br/><a onclick="popClrDatasets(\'' + id + '\');">Remove all datasets</a>';
  if ($ES('.dsBox', id).length >= 10) { dsAdd = ''; }
  if ($ES('.dsBox', id).length == 0) { clrDs = ''; }
  overlib('<p style="margin:2px 0; white-space:nowrap;"><a onclick="renameTree(\'' + id + '\');">Rename tree<br /><a onmouseover=\'overlib2("Interactively edit the tree. Move or delete clades, collapse braches, re-root the tree.")\' onmouseout=\'return cClick2();\'  href="editor.cgi?circ=2&amp;tree=' + id.substr(1) + '">Edit tree</a><br /><a onmouseover=\'overlib2("This function will find the mid-point between most distant nodes and re-root the tree there. You can replace the existing tree, or create a re-rooted copy.")\' onmouseout=\'return cClick2();\'  href="midpoint_root.cgi?tree=' + id.substr(1) + '">Root mid-point</a><br /><a onmouseover=\'overlib2("Create a copy of the tree, with datasets and all additional data. The copy will appear in the current project.")\' onmouseout=\'return cClick2();\' onclick="doDupTree(\'' + id.substr(1) + '\');">Duplicate tree</a><br /><a onmouseover=\'overlib2("Allows you to edit the leaf labels. You can also upload a file and re-label the whole tree at once.")\' onmouseout=\'return cClick2();\'  href="editLabels.cgi?tree=' + id.substr(1) + '">Re-label leaves</a><br /><a onmouseover=\'overlib2("This function will automatically assign proper scientific names to all leaves and internal nodes, based on NCBI taxonomy. It will work only for trees which have NCBI taxonomy IDs as leafs.")\' onmouseout=\'return cClick2();\'  href="assign_tax.cgi?tree=' + id.substr(1) + '">Assign taxonomy</a><hr /><a onmouseover=\'overlib2("Add/remove branch colors and colored ranges for the leaves.")\' onmouseout=\'return cClick2();\'  href="color_tree.cgi?tree=' + id.substr(1) + '">Edit colors</a>'+ dsAdd + clrDs + '</p>', EXCLUSIVE,STICKY,WRAP,MOUSEOFF,OFFSETY,0,OFFSETX,0,LEFT,CAPTION, 'Tree options',CLOSECLICK);
}
function popDatasetAdd(id) { 
  cClick();
  var nm = $E('.trLn',$(id)).innerHTML;
  if ($ES('.dsBox', id).length >= 10) { alert('There cannot be more than 10 datasets per tree.');return;}
  $('DStree').value = id;
  if ($('DSupRes')) {
    $('DSupRes').remove();
  }
  if ($('newDSov')) {
    $('newDSov').remove();
  }
  $('DStreeN').innerHTML = nm;
  var ht=$(id).getTop(); 
  var ov = new Element('div').setProperty('id', 'newDSov').injectInside(document.body);
  ov.setStyle('height', window.getScrollHeight()+'px');
  $('newDS').setStyle('padding-top', ht + 'px');
  $('newDS').style.display='block';
  if (!dsFx1) {
    dsFx1=new Fx.Slide('newDScon').hide();
  }
  var dsFx=new Fx.Style('newDSov', 'opacity').hide();
  dsFx.start(0.8);
  dsFx1.slideIn();
}

function chkValidDSup() {
  if ($('data1_file').value == '') {
    alert('You must select the dataset file.');
    return false;
  }
  if ($('data1_label').value == '') {
    $('data1_label').setStyle('background', '#fcc');
    $('erL1').innerHTML = 'Dataset label is missing';
    return false;
  }
}
function popClrDatasets(id){
  var nm = $E('.trLn',$(id)).innerHTML;
  overlib2('This will remove all the datasets associated with this tree.<br /><b style="background: #faa;font-size:14px;">This operation CANNOT BE UNDONE.</b><br />Please make sure you do not delete the data you might still need.<p><input type="button" value="Remove datasets" onclick="doRemoveDatasets(\'' +  id + '\');" /> <input type="button" value="Cancel" onclick="return cClick2();" /></p>',MODAL, EXCLUSIVE, STICKY,WRAP,CAPTION,  'Remove all datasets for tree "' +  nm + '" ?',OFFSETX,0,OFFSETY,0,CLOSECLICK);
}
function doRemoveDatasets(id) {
  new Ajax('ajax/clearDatasets.cgi', {
    method: 'get',
	       data: 'id=' + id,
	       onComplete: function(){$(id + '_ds').innerHTML = "-"; cClick2(); cClick(); },
	       onFailure: function(){ return overlib('<span style="background: #faa;">ERROR removing datasets</span>', WRAP, TIMEOUT, 3000);}
    }).request();
}
function popTrm(id){
  var nm = $E('.trLn',$('T'+id)).innerHTML;
  overlib('This will remove all the data associated with this tree,<br />including datasets and saved views.<br /><b style="background: #faa;font-size:14px;">This operation CANNOT BE UNDONE.</b><br />Please make sure you do not delete the data you might still need.<p><input type="button" value="Remove tree" onclick="doRemoveTree(\'' +  id + '\');" /> <input type="button" value="Cancel" onclick="return cClick();" /></p>',MODAL, EXCLUSIVE, STICKY,WRAP,LEFT,CAPTION, 'Remove tree "' +  nm + '" ?',OFFSETX,0,OFFSETY,0,CLOSECLICK);
}
function doRemoveTree(id) {
  new Ajax('ajax/removeTree.cgi', {
    method: 'get',
	       data: 'id=' + id,
	       onComplete: function(){ $('T' + id).remove(); cClick(); },
	       onFailure: function(){ return overlib('<span style="background: #faa;">ERROR removing tree from the database</span>', WRAP, TIMEOUT, 3000);}
    }).request();
}

function popWrm(id,nm){
  overlib('This will remove all the data associated with this workspace,<br />including all projects and trees with their data.<br /><b style="background: #faa;font-size:14px;">This operation CANNOT BE UNDONE.</b><br />Please make sure you do not delete the data you might still need.<p><input type="button" value="Remove workspace" onclick="doRemoveWS(\'' +  id + '\');" /> <input type="button" value="Cancel" onclick="return cClick();" /></p>',  MODAL, EXCLUSIVE, STICKY,WRAP,LEFT,CAPTION, 'Remove workspace "' +  nm + '" ?',OFFSETX,0,OFFSETY,0,CLOSECLICK);
}

function doRemoveWS(id) {
  new Ajax('ajax/removeTab.cgi', {
    method: 'get',
	data: 'id=' + id,
	onComplete: function(){ $('tb' + id).remove(); cClick(); },
	onFailure: function(){ return overlib('<span style="background: #faa;">ERROR removing workspace from the database</span>', WRAP, TIMEOUT, 3000);}
    }).request();
}
function toggleIntView() {
  if ($('ivTog').hasClass('vMin')) {
    ivTogEf.slideOut();
    $('ivTog').removeClass('vMin');
  } else {
    ivTogEf.slideIn();
    $('ivTog').addClass('vMin');
  }
}

function popDS(id, typ,nCon) {
  var lab = dsLabs['dsl' + id];
  var dscolFunc = "onclick='pickColor(\"cl" + id + "\");'";
  if (typ == 'Color gradient' || typ == 'Heatmap') { dscolFunc = "onmouseover='overlib2(\"Original data is needed to change the color gradients and heatmaps.<br>You must re-upload the dataset.\",WRAP);' onmouseout=\"return nd2();\" "; 
}
  if (nCon) {
    overlib("<b>Label:</b> " + lab + "<br /><b>Type:</b> " + typ ,CLOSECLICK, STICKY, WRAP, OFFSETX,0,OFFSETY,0, CAPTION, "Dataset");
  } else {
    overlib("<b>Label:</b> <a class='noteMal' id='dsl" + id + "' onmousedown=\"noteMal(this,'dsl','" + id + "');\" >" + lab + "</a><br /><b>Type:</b> " + typ + "<br /><a onclick='popDSrm(\"" + id + "\",\"" + lab + "\");'>Remove?</a> <a id='cl" + id + "' " + dscolFunc + ">New color?</a><input type='hidden' name='cl" + id + "field' value='' />",CLOSECLICK, STICKY, WRAP, OFFSETX,0,OFFSETY,0, CAPTION, "Dataset");
  }
}

function popDSrm(id,lab){
  overlib2('This will remove the dataset from our database.<br /><b style="background: #faa;font-size:14px;">This operation CANNOT BE UNDONE.</b><br />Please make sure you do not delete the data you might still need.<p><input type="button" value="Remove dataset" onclick="dropDS(\'' +  id + '\');" /> <input type="button" value="Cancel" onclick="cClick2();" /></p>',MODAL, EXCLUSIVE, STICKY,WRAP,CAPTION, 'Remove dataset \'' + lab + '\' ?',OFFSETX,0,OFFSETY,0,CLOSECLICK);
}

function dropDS(id) {
  new Ajax('ajax/removeDS.cgi', {
    method: 'get',
	data: 'id=' + id,
	onComplete: function(){ $('ds' + id).remove(); cClick(); },
	onFailure: function(){ return overlib('<span style="background: #faa;">ERROR removing dataset from the database</span>', WRAP, TIMEOUT, 3000);}
    }).request();
}

function moveTree(id,dir) {
  if (dir == 2) {
    if (!$(id).nextSibling) {
      return;
    }
  } else {
    if ($(id).previousSibling.hasClass('tdMh')) {
      return;
    }
  }
  new Ajax('ajax/updatePos.cgi', {
    method: 'get',
	data: 'tr=' + id + '&amp;dir=' + dir,
	onComplete: function(){ 
	if (dir == 2) {
	  $(id).injectAfter($(id).nextSibling);
	} else {
	  $(id).injectBefore($(id).previousSibling);
	} },
	onFailure: function(){ return overlib('<b>An ERROR occured while moving the tree</b>',FGCOLOR, '#ffaaaa',TEXTSIZE, 16, WRAP, TIMEOUT, 3000);}
    }).request();
}
function popShProNfo(l) {
  overlib("You colleagues and friends can access all your shared projects<br /> by typing your iTOL login ('<span style=\"color:green;font-weight:bold\">" + l + "</span>') on the <a href='shared_projects.shtml'>SHARED PROJECTS</a> page.<p>Alternatively, you can send them the direct link to your shared accounts page:<p> <a href='shared/" + l + "'>http://itol.embl.de/shared/" + l + "</a></p><p>They will be able to view and export the trees, but not modify or delete them.</p>", WRAP, CAPTION, "How to share your shared projects",STICKY,CLOSECLICK);
}

