var ds = 1;
var spC = 0;
var colC = 0;
var nRt;
var views = new Object;


function initPrune(ids, count, col, colcount) {
  $('prune').value = ids;
  if (colcount > 0) {
    colC = colcount;
    $('collapsed').value = col;
    if ($('colspn')) {
      $('colspn').style.display='inline';
      $('colcount').innerHTML=colcount;
    }
  }
  if (count > 0) {
    spC=count;
    if ($('spCount')) { $('spCount').innerHTML=count; }
  }
}
function setAngle(ang,c) {
  if (c) {
    $('rotate').value = ang;
  } else {
    $('rotate').value = ang;
//    $('nTreeRotate').value = ang;
  }
}

function newRoot(id) {
  $('nroot').value = id;
  blink('spSub', 8,1);
}

function updateColLists(col, uncol, prune) {
  $('collapse').value = col;
  $('uncollapse').value = uncol;
  blink('spSub', 8,1);
}
function updateRevList(rev) {
  $('rev').value = rev;
  blink('spSub', 8,1);
}

function blink(el, times, onoff) {
  if (times==0) {
    if (onoff == 0 && document.getElementById(el).className.match(/blink/))
      removename (document.getElementById(el),"blink");
    if (onoff == 1 && !document.getElementById(el).className.match(/blink/))
      document.getElementById(el).className += " blink";
    return;
  }
  
  if (document.getElementById(el).className.match(/blink/))
    removename (document.getElementById(el),"blink");
  else
    document.getElementById(el).className += " blink";
  setTimeout("blink('"+el+"',"+(times-1)+", "+onoff+")", 150);   
}

function removename(el, name) {
  var i, curList, newList;
  // Remove the given class name from the className property of the element.
  newList = new Array();
  curList = el.className.split(" ");
  for (i = 0; i < curList.length; i++)
    if (curList[i] != name)
      newList.push(curList[i]);
  el.className = newList.join(" ");
}

function expForm (){
  $('mainForm').action = "export.cgi";
  $('mainForm').submit();
  return true;
}

function updForm (lnk){
  $('mainForm').action = lnk;
  $('mainForm').submit();
  return true;
}

function showRot () {
  $('rotInput').style.display = 'inline';
  blink('spSub', 3,0);
}

function hideRot () {
  $('rotInput').style.display = 'none';
  blink('spSub', 3,0);
}

function showTreeDesc() {
  var sel = $('treeName');
  var show;
  for (var i = 0; i < sel.options.length; i++) {
    var name = sel.options[i].value;
    if (!name) {
      continue;
    }
    if (i == sel.selectedIndex) {
      show = name;
    }
    document.getElementById(name).style.display='none';
  }
  var el = document.getElementById(show);
  el.style.display='block';
}
function dsVisible(id) {
  $('dsVisible').value = id;
}
function delNodes(lst) {
  $('deleted').value = lst;
  blink('spSub', 3,0);
}
function moveNodes(lst) {
  $('moved').value = lst;
  blink('spSub', 3,0);
}
function edColNodes(lst) {
  $('edCol').value = lst;
  blink('spSub', 3,0);
}

function addDS() {
 if (ds > 5) {
  return;
  }
 ds = ds + 1;
 var curDS = 'dataSet' + ds;
 $(curDS).style.display = 'block';
 if (ds == 5) {
   $('addDs').style.display = 'none';
 }
}

function saveState() {
  if ($('stateLabel').value == '' || $('stateLabel').value == 'Label needed...') {
    $('stateLabel').value = 'Label needed...';
    blink('stateLabel', 8,1);
    //   alert("You must supply a label for the saved view.");
    return;
  }
  var p = $('stateParams').value;
  if ($('prune').value) {
    p = p + '&amp;prune=' + $('prune').value;
  }
  if ($('species').value) {
    p = p + '&amp;species=' + $('species').value ;
  }
  var note = $('stateNote').value;
  if (!note) { note = 'Click to add'; }
  var pars = "params=" + encodeURIComponent(p) + "&amp;stateLabel=" + $('stateLabel').value + "&amp;stateNote=" + note;
  var ax = new XHR({method: 'get',onSuccess: sStateOK,onFailure: sStateErr}).send('saveState.cgi', pars);
}

function sStateOK(txt) {
 $('saveState').innerHTML = txt;
}

function sStateErr() {
  $('saveState').innerHTML = "<p style=\"background: #f66;font-weight: bold; font-size: 14px\">ERROR saving state</p>";
}

function removeView(id) {
  var rmax = new Ajax( 'ajax/removeView.cgi' ,{method: 'get',data: 'id=' + id , update: id}).request();
}

function logMe(msg) {
  //alert(msg);
  //    console.log(msg);
  //  opera.postError(msg);
}
function chkViewSub(oEvent) {
  if ((oEvent.keyCode && oEvent.keyCode==13)
      || (oEvent.which && oEvent.which==13)) {
    if ($('stateLabel').value == 'Label:') { 
      alert("Please type a label for the saved view.");
    } else if ($('stateLabel').value != '') {
      saveState();
    }
  }
}
    
function flObj (swf,ht) {
  if (swf.indexOf('cgi?par=') == -1) {
  if ($('prune').value) {
    swf = swf + '&amp;prune=' + $('prune').value;
  }
  if ($('species').value) {
    swf = swf + '&amp;species=' + $('species').value ;
  }
  }
  //  $('controls').setStyle('height', $('conTable').getStyle('height'));
  $('fOb').innerHTML = '<embed type="application/x-shockwave-flash" src="'+ swf + '" id="mainTree" name="mainTree" bgcolor="#FFFFFF" quality="high" menu="false" scale="scale" wmode="transparent"  salign="lt" height="'+ ht +'" width="100%">';
}

function flObj_t2 (swf, ht) {
  if (swf.indexOf('cgi?par=') == -1) {
    if ($('prune').value) {
      swf = swf + '&amp;prune=' + $('prune').value;
    }
    if ($('species').value) {
      swf = swf + '&amp;species=' + $('species').value ;
    }
  }
  $('fOb').innerHTML =
    '<object type="application/x-shockwave-flash" id="mainTree" data="' + swf + '" width="100%" height="' + ht + '"><param name="movie" value="' + swf + '" /><param name="QUALITY" value="HIGH" /> <param  name="WMODE" value="transparent" /><param  name="menu" value="false" /><param  name="salign" value="lt" />Our trees are displayed using Flash, and your browser does not have a proper plugin installed. You can download and install the plugin from <a href="http://www.adobe.com/shockwave/download/?P1_Prod_Version=ShockwaveFlash">Adobe\'s web page</a></object>';
}

function noBrlCheck() {
  if ($('noBrl').checked == false) {
    if ($('delBoot') && $('delBoot').checked == true) {
      $('delBoot').checked = false;
      overlib("You cannot remove branches based on bootstrap values, and use branch lengths.", STICKY, WRAP, TIMEOUT, 5000);
    }
  }
  blink('spSub', 8,1);
}
function delBootCheck() {
  if ($('delBoot').checked == true) {
    if ($('noBrl') && $('noBrl').checked == false) {
      $('noBrl').checked = true;
      overlib("Branch lengths will be ignored on the next tree update.", STICKY, WRAP, TIMEOUT, 5000);
    }
  }
  blink('spSub', 8,1);
}

function getFontSize() {
  var pars = '';
  if ($('treeName')) { pars += "treeName=" + $('treeName').value + "&" ;}
  if ($('tree')) { pars += "tree=" + $('tree').value + "&" ;}
  if ($('delBootVal')) { pars += "delBootVal=" + $('delBootVal').value + "&" ;}
  if ($('species')) { pars += "species=" + $('species').value + "&" ;}
  if ($('prune')) { pars += "prune=" + $('prune').value + "&" ;}
  if ($('collapse')) { pars += "collapse=" + $('collapse').value + "&" ;}
  if ($('mode')) { pars += "mode=" + $('mode').value + "&" ;}
  if ($('collab')) { pars += "collab=" + $('collab').value + "&" ;}
  if ($('spread')) { pars += "spread=" + $('spread').value + "&" ;}
  if ($('invertCirc')) { pars += "invertCirc" + $('invertCirc').value + "&" ;}
  if ($('scaleFac')) { pars += "scaleFac" + $('scaleFac').value + "&" ;}
  overlib("<span style='font-size: 16px'>Calculating font size...</span>", WRAP, STICKY);
  new Ajax( 'ajax/getFontSize.cgi' ,{method: 'post',data: pars, onComplete: updFontSize, onFailure: function(){ return overlib('<span style="background: #faa;">Error calculating font size</span>', WRAP, TIMEOUT, 3000);}}).request();
}
function updFontSize(res) {
  $('fontSize').value = res;
  overlib("<span style='font-size: 16px'>Optimal font size for the current tree view is " + res + "</span>", WRAP, STICKY, TIMEOUT, 5000);
  $('fsFunc').style.display = 'none';
}

function checkDs(what) {
  if (what == 'other') {
    $('none').checked = false;
  } else if (what == 'none') {
    for (var i = 0; i <= 10; i++) {
      if ($('other' + i)) {
	$('other' + i).checked = false;
      }
    }
  }

//   if (what == 'ring') {
//     for (var i = 0; i <= 10; i++) {
//       if ($('other' + i)) {
// 	$('other' + i).checked = false;
//       }
//     }
//     $('none').checked = false;    
//   } else if (what == 'other') {
//     for (var i = 0; i <= 10; i++) {
//       if ($('ring' + i)) {
// 	$('ring' + i).checked = false;
//       }
//     }
//     $('none').checked = false;
//   } else if (what == 'pie') {
//     $('none').checked = false;
//   } else if (what == 'none') {
//     for (var i = 0; i <= 10; i++) {
//       if ($('ring' + i)) {
// 	$('ring' + i).checked = false;
//       }
//       if ($('pie' + i)) {
// 	$('pie' + i).checked = false;
//       }
//       if ($('other' + i)) {
// 	$('other' + i).checked = false;
//       }
//     }
//   }
}

function dsTypOpt(id) {
  if ($('data' + id + 'type').selectedIndex == 2) {
    $('pieCh' + id).style.display = '';
    $('pieTr' + id).style.display = '';
    $('barSize' + id).style.display = '';
    $('malign' + id).style.display = '';
  } else {
    $('pieCh' + id).style.display = 'none';
    $('pieTr' + id).style.display = 'none';
    $('barSize' + id).style.display = 'none';
    $('malign' + id).style.display = 'none';
  }
  if ($('data' + id + 'type').selectedIndex == 1 || $('data' + id + 'type').selectedIndex == 5) {
    $('barSize' + id).style.display = '';
  }
  if ($('data' + id + 'type').selectedIndex == 3 || $('data' + id + 'type').selectedIndex == 4) {
    $('stripWid' + id).style.display = '';
    $('stripShift' + id).style.display = '';
  } else {
    $('stripWid' + id).style.display = 'none';
    $('stripShift' + id).style.display = 'none';
  }
  if ($('data' + id + 'type').selectedIndex == 4) {
    $('stripColTyp' + id).style.display = '';
  } else {
    $('stripColTyp' + id).style.display = 'none';
  }
  if ($('data' + id + 'type').selectedIndex == 6) {
    $('protSize' + id).style.display = '';
  } else {
    $('protSize' + id).style.display = 'none';
  }
  if ($('data' + id + 'type').selectedIndex == 7) {
    $$('.hmap' + id).each(function(item){item.style.display = ''; })
  } else {
    $$('.hmap' + id).each(function(item){item.style.display = 'none'; })
  }
  if ($('data' + id + 'type').selectedIndex == 8) {
    $$('.boxplotN' + id).each(function(item){item.style.display = ''; })
      if ($('data' + id + '_boxRawY').checked) {             
        boxplotRawExp(id, 1);
      } else {            
        boxplotRawExp(id, 0);
      }
  } else {
    $$('.boxplotN' + id).each(function(item){item.style.display = 'none'; })
    $$('.boxplotR' + id).each(function(item){item.style.display = 'none'; })
  }

  if ($('newDS')) {
    $('newDScon').getParent().setStyle('height', $('newDScon').getStyle('height'));
  }
}

function boxplotRawExp(id,i) {
  if (i) {
    $$('.boxplotR' + id).each(function(item){item.style.display = ''; })
      } else {
    $$('.boxplotR' + id).each(function(item){item.style.display = 'none'; })
      }
  if ($('newDS')) {
    $('newDScon').getParent().setStyle('height', $('newDScon').getStyle('height'));
  }
}

function advCon() {
 $('advCcon').style.display = 'block';
 $('basCcon').style.display = 'none';
 $('basicC').className = 'unselC';
 $('advC').className = 'selC';
 $('advL').style.fontWeight = 'bold';
 $('basL').style.fontWeight = 'normal';
}

function basicCon() {
 $('advCcon').style.display = 'none';
 $('basCcon').style.display = 'block';
 $('basicC').className = 'selC';
 $('advC').className = 'unselC';
 $('advL').style.fontWeight = 'normal';
 $('basL').style.fontWeight = 'bold';
}

function chkUpForm () { 
  if ($('treetext').value == 'Paste your tree here...' || $('treetext').value == '') {
    if ($('usertree').value == '') {
      alert("You must provide a tree!");
      $('usertree').focus;
      return false;
    }
  }
  for (var i = 0; i <= 10; i++) {
    if ($('data' + i + '_file').value && $('data' + i + '_label').value == '') {
      $('data' + i + '_label').setStyle('background', '#f66');
      $('erL' + i).innerHTML = 'Label is missing for dataset ' + i;
      dsTab.activate('Dataset ' + i);
      new Fx.Scroll('data' + i + '_label');
      return false;
    }
  }
  return true;
}
function popLogin () {
  overlib('<form action=\'itol_login.cgi\' method=\'post\'><table><tr><td>Login:</td><td><input type=\'text\' name=\'login\' id=\'login\' size=\'10\' /></td></tr><tr><td>Password:</td><td><input type=\'password\' name=\'pwd\' id=\'pwd\' size=\'10\' /></td></tr><tr><td colspan=\'2\'><input type=\'checkbox\' name=\'permlogin\' value=\'1\' /> Keep this browser logged in</td></tr></table><p><input type=\'submit\' value=\'Login\' /><input type=\'reset\' value=\'Reset\' /></p><p><a href="itol_account.cgi">No account yet?</a><br /><a href="lost_password.cgi">Forgot your password?</a></form>', STICKY, CLOSECLICK, CAPTION, 'iTOL Login:');
  $('login').focus();
}

function fillLoginBox() {
  $('loginBox').innerHTML = "<form action='itol_login.cgi' method='post'><h3 style=\'margin:0;padding:0 3px;color:#333;\'>iTOL account login</h3><table style=\'margin:0; padding:0; border-collapse: collapse\'><tr><td>Login:</td><td>Password:</td></tr><tr><td><input type=\'text\' name=\'login\' id=\'login\' style=\'width:90px\' /></td><td><input type=\'password\' name=\'pwd\' id=\'pwd\' style=\'width:90px\' /></td></tr><tr><td><input type=\'checkbox\' name=\'permlogin\' value=\'1\' />Remain logged-in?</td><td><input type=\'submit\' value=\'Login\' style=\'width:90px\' /></td></tr></table></form>";
}

function showKEGG (id) {
  document.location.href = 'http://pathways.embl.de/map_for_node.cgi?nodeID=' + id;
}

function popCurStat() {
  var msg = '<table><tr><td>Leafs in the tree:</td><td><b>' + spC + '</b></td></tr>';
  msg = msg + '<tr><td>Collapsed branches:</td><td><b>' + colC + '</b></td></tr>';
  if (nRt) {
    msg = msg + '<tr><td>Rerooted on node:</td><td><b>' + nRt + '</b></td></tr>';
  } else {
    msg = msg + '<tr><td>Not rerooted</td><td></td></tr>';
  }
  overlib(msg + '</table>', WRAP,STICKY,CAPTION,'Current tree view:',OFFSETX,5,OFFSETY,5,CLOSETEXT, '');
  
}

function utfdecode (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
}

function colModeSwitch() {
  if (cc>1 || cr>1) {
    var res = confirm('Any changes you made will be lost on mode change.\nProceed?');
    if (res != 0) {
      $('mSwitch').value = 1;
      $('mainForm').action = 'color_tree.cgi';
      $('mainForm').submit();
    }
  } else {
    $('mSwitch').value = 1;
    $('mainForm').action = 'color_tree.cgi';
    $('mainForm').submit();
  }
}

function updatePruneList(ids) {
  //  ids = utfdecode(ids);
  $('prune').value = ids;
  blink('spSub', 8,1);
}
function updateColoredList(ids) {
  $('colored').value = escape(ids);
  var nRn = ids.split("+");

  if (nRn.length <= 1) {
    $('cladeData').innerHTML ='-';
    return;
  }

  colors = new Object;
  cc = nRn.length-1;
  for (var i = 0;i<nRn.length-1;i++) {
    var dt = nRn[i].split("sE-p4");
    if (colors["#" + dt[0].substr(2)]) {
      colors["#" + dt[0].substr(2)]++;
    } else {
      colors["#" + dt[0].substr(2)] = 1;
    }
    cc++;
  }
  drawColorsBox();
}
function updateRangesList(ids) {
  $('rangeDt').value = escape(ids);
  var nRn = ids.split("+");
  if (nRn.length <= 1) {
    $('rangeData').innerHTML ='-';
    return;
  }
  ranges = new Object;
  cr=nRn.length-1;
  for (var i = 0;i<nRn.length-1;i++) {
    var dt = nRn[i].split("sE-p4");
    ranges["#" + dt[0].substr(2)] = dt[1];
  }
  drawRangesBox();
}

function drawRangesBox() {
  var rIn = '';
  var c = 1;
  for (var r in ranges) {
    var lab = ranges[r].split("-PlUs-").join("+");
    rIn = rIn + '<span style="font-size:8px;border:1px solid black;color:' + r + ';background:' + r + ';">RN</span> ' + lab + ' ';
    if (c++ % 5 == 0) { rIn = rIn + '<br />'; }
  }
  if (rIn) { $('rangeData').innerHTML = rIn;}
}

function drawColorsBox() {
  var cIn = '';
  var c = 1;
  for (var r in colors) {
    var t = '1 clade';
    if (colors[r] > 1) { t = colors[r] + ' clades'; }
    cIn = cIn + '<span style="font-size:8px;border:1px solid black;color:' + r + ';background:' + r + ';">CN</span> ' + t + ' ';
    if (c++ % 5 == 0) { cIn = cIn + '<br />'; }
  }
  if (cIn) { $('cladeData').innerHTML = cIn;}
}
function initColor() {
  drawRangesBox();
  drawColorsBox();
}
function expFormatChange() {
  if ($('expFormat').selectedIndex == 0) {
    $ES('.txt', $('export')).setStyle('display', 'none');
    $ES('.bmp', $('export')).setStyle('display', '');
    if ($('datasets')) {
      $('datasets').setStyle('display', 'block');
    }
  } else if ($('expFormat').selectedIndex < 5) {
    $ES('.txt', $('export')).setStyle('display', 'none');
    $ES('.bmp', $('export')).setStyle('display', 'none');
    $ES('.vec', $('export')).setStyle('display', '');
    if ($('datasets')) {
      $('datasets').setStyle('display', 'block');
    }
  } else {
    $ES('.bmp', $('export')).setStyle('display', 'none');
    $ES('.vec', $('export')).setStyle('display', 'none');
    if ($('datasets')) {
      $('datasets').setStyle('display', 'none');
    }
    if ($('expFormat').selectedIndex == 5) {
      $ES('.txt', $('export')).setStyle('display', '');
    }
  }
}
function modeChPop() {
  var pop;
  var coord = $('tmode').getCoordinates();
  var x2 = coord.right + 100;
  var unr = " ";

  if ($('tmode').innerHTML == 'Circular') {
    pop = "<span style='background: #afa;'>Circular mode</span><br><a href='#' onclick=\"modeSwitch('n');\" onmouseover='overlib2(\"<img src=img/nmode.jpg>\",WRAP,STICKY,FIXX,"+x2+",FIXY," + coord.top + ")' onmouseout='cClick2()'>Normal mode</a>" + unr;
    
  } else if ($('tmode').innerHTML == 'Normal') {
    pop = "<a href='#' onclick=\"modeSwitch('c');\" onmouseover='overlib2(\"<img src=img/cmode.jpg>\",WRAP,STICKY,FIXX,"+x2+",FIXY," + coord.top + ")' onmouseout='cClick2()'>Circular mode</a><br><span style='background: #afa;'>Normal mode</span>" + unr;
  } else if ($('tmode').innerHTML == 'Unrooted') {
    pop = "<a href='#' onclick=\"modeSwitch('c');\" onmouseover='overlib2(\"<img src=img/cmode.jpg>\",WRAP,STICKY,FIXX,"+x2+",FIXY," + coord.top + ")' onmouseout='cClick2()'>Circular mode</a><br><a href='#' onclick=\"modeSwitch('n');\" onmouseover='overlib2(\"<img src=img/nmode.jpg>\",WRAP,STICKY,FIXX,"+x2+",FIXY," + coord.top + ")' onmouseout='cClick2()'>Normal mode</a><br><span style='background: #afa;'>Unrooted mode</span>";
  }

    overlib(pop, WRAP,STICKY,OFFSETX,10,FIXX,coord.right,FIXY,coord.top,MOUSEOFF,WIDTH,150);
}

function modeSwitch(nm) {
  if (nm == 'c') {
    showRot();
    $('tmode').innerHTML = 'Circular';
    $('mode').value = 'circular';
  } else if (nm == 'n') {
    hideRot();
    $('tmode').innerHTML = 'Normal';
    $('mode').value = 'normal';
  } else if (nm == 'u') {
    hideRot();
    $('tmode').innerHTML = 'Unrooted';
    $('mode').value = 'unrooted';
  }
  blink('spSub', 8,1);   
  cClick2();cClick();
}
function rnBoxTog() {
  if ($('rnHidden').checked == true) {
	$('rangeVisBlock').style.display = 'none';
  } else {
	$('rangeVisBlock').style.display = 'inline';
  }
}
function toggleAdvUpload() {
  if ($('advUpBut').innerHTML == '(show)') {
    $('advUpBut').innerHTML ='(hide)';
    $ES('.advUpRow', '.treeEx').setStyle('display', 'table-row');
  } else {
    $('advUpBut').innerHTML ='(show)';
    $ES('.advUpRow', '.treeEx').setStyle('display', 'none');
  }
}
function setRnVis(w) {
  $('rnVisible').value = w;
}
