
  function windowOpenWithSize(theurl, thewd, theht) {
    if(!(theht)) {
      theht = 528;
    }
    if(!(thewd)) {
      thewd = 410;
    }
    var newwin  = window.open(theurl,"labelsize","dependent=no, resizable=yes,toolbar=no,menubar=yes,scrollbars=yes,width="+thewd+",height="+theht);
//     alert(theurl);
    if(newwin!=null)
      newwin.focus();
  }
  
  function toTop() {
        self.scrollTo(0, 0)
}
function toBot() {
        self.scrollTo(0, window.screen.height)
}
function toSpot(xparam, yparam) {
        self.scrollTo(xparam, yparam)
}
function fold(elementId, more, moreName, hideName) {
    var elementToFold = document.getElementById(elementId);
    var moreLink = document.getElementById(more);
    if (navigator.userAgent.indexOf("Netscape6") != -1)	{
        if (elementToFold.style.visibility=="visible") {
            elementToFold.style.visibility="hidden";
            moreLink.firstChild.nodeValue=moreName;
        }	else {
            elementToFold.style.visibility="visible";
            moreLink.firstChild.nodeValue=hideName;
        }
    } else {
        if (elementToFold.style.display=="") {
            elementToFold.style.display="none";
            moreLink.firstChild.nodeValue=moreName;
        } else {
            elementToFold.style.display="";
            moreLink.firstChild.nodeValue=hideName;
        }
    }
}

  function errorMsg()
{
  alert("Netscape 6 or Mozilla is needed to install a sherlock plugin");
}
function addEngine(name,ext,cat,type){
  if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function")){
    //cat="Web";
    //cat=prompt('In what category should this engine be installed?','Web')
    window.sidebar.addSearchEngine(
      "http://www.ebi.ac.uk/chebi/plugins/firefox/"+name+".src",
      "http://www.ebi.ac.uk/chebi/plugins/firefox/"+name+".jpg",
      name,
      cat );
  } else {
    errorMsg();
  }
}

function toggleVisibility(panelId)
{
    var panel = document.getElementById(panelId);
    var currentVisibility = panel.style.visibility;

    if (currentVisibility == 'hidden')
    {
        panel.style.visibility = 'visible';
    }
    else
    {
        panel.style.visibility = 'hidden';
    }
}

  // fake selects a field and then you can copy it to the clipboard
   var chebiPreviousHighlightedField = null;
   function chebiSelectAll(fieldToSelect, fieldToHighlight) {
  var selectedF = document.getElementById(fieldToSelect);
  var highlightedF = document.getElementById(fieldToHighlight);
  // select the actual field
  selectedF.select();
      // highlight the field if need be
  if ( chebiPreviousHighlightedField!=null && highlightedF == chebiPreviousHighlightedField){
      chebiPreviousHighlightedField = null;
      highlightedF.style.backgroundColor = "#ffffff";
  } else {
      if (chebiPreviousHighlightedField!=null)
         chebiPreviousHighlightedField.style.backgroundColor = "#ffffff";
      chebiPreviousHighlightedField = highlightedF;
      highlightedF.style.backgroundColor = "#eeeeee";
   }
}
   
   
// ========================
// ADVANCED SEARCH 
// 
// developer: adekker
//========================
 
function removePreviousPlusButton(block, counter) {

	counter--;
	if (counter > -1)
		document.getElementById(block + "PlusButton" + counter).style.display="none";
}
	

// Remove this row if it's not the last one! also add previous plus button.
function removeThisRow(block, counter) {

	var blockId = block + counter;
	var node = document.getElementById(blockId);

	var parentBlock = block.substr(0, block.length - 1) + "ies";
	var parentNode = document.getElementById(parentBlock);
	var divNodes = parentNode.getElementsByTagName("div");
	var divNodesQuantity = divNodes.length;

	// Not the last one!
	if (divNodesQuantity == 1) {
		addAnotherRow(block, counter);
	}

	// Get the last row
	var lastRow = 0;
	var beforeLastRow = 0;
	for (i = 0; i < divNodesQuantity; i++) {
		var id = divNodes[i].getAttributeNode("id").value;
		var row = id.substr(block.length);

		if (row > lastRow) {
			beforeLastRow = lastRow;
			lastRow = row;
		}
	}

	// Delete the row!
	document.getElementById(parentBlock).removeChild(node);

	// If it's the only row, add a plus button to the next row, or...
	// If it's the last row, add a plus button to the previous row
	if (divNodesQuantity == 1)
		document.getElementById(block + "PlusButton" + (counter + 1)).style.display = "inline";
	else if (counter == lastRow) {
		document.getElementById(block + "PlusButton" + (beforeLastRow)).style.display = "inline";
	}
}

// Add another row of the same block! also remove plus button.
function addAnotherRow(block, counter) {

	var blockId = block+counter;
	var modelNode = document.getElementById(blockId);
	var newNode = modelNode.cloneNode(true);
	var children = newNode.childNodes;
	var newCounter = counter+1;	

	//var msg = blockId+"\n";
	newNode.setAttribute('id',blockId.replace(counter,newCounter));
	
	for(i=0;i<children.length;i++) {
		if (children[i].nodeType == 1) {
			//msg += children[i].nodeName + "\n"; 
          
          nameValue = children[i].getAttribute("name");
          typeValue = children[i].getAttribute("type");
          idValue = children[i].getAttribute("id");
          onclickValue = children[i].getAttribute("onclick");
          onkeyupValue = children[i].getAttribute("onkeyup");
          onblurValue = children[i].getAttribute("onblur");
          onmouseoutValue = children[i].getAttribute("onmouseout");
                      
          if (nameValue != null)
              children[i].setAttribute("name", nameValue.replace(counter,newCounter));
          
          if (idValue != null)
              children[i].setAttribute("id", idValue.replace(counter,newCounter));

          if (onclickValue != null)
              children[i].setAttribute("onclick", onclickValue.replace(counter,newCounter));
          
          if (onkeyupValue != null) 
              children[i].setAttribute("onkeyup", onkeyupValue.replace(counter,newCounter));
          
          if (onblurValue != null) 
              children[i].setAttribute("onblur", onblurValue.replace(counter,newCounter));
          
          if (onmouseoutValue != null) 
              children[i].setAttribute("onmouseout", onmouseoutValue.replace(counter,newCounter));

          if (children[i].nodeName == "INPUT" && idValue != null && typeValue != null && typeValue == "text")  
              children[i].value = "";
          
          if (children[i].nodeName == "SPAN" && idValue == "incomingOntologyQueryLabelField" + counter) 
              children[i].innerHTML = "";   
          
		}
	}
	//alert(msg);
	
	// Get the parent block!
	parentBlock = block.substr(0, block.length-1) + "ies";
	document.getElementById(parentBlock).appendChild(newNode);

	// Fix the buttons!
	document.getElementById(block+"PlusButton"+counter).style.display = "none";
	document.getElementById(block+"PlusButton"+newCounter).style.display = "inline";
}

// ========================
// ADVANCED SEARCH 
// AJAX part
// 
// developer: adekker
//========================
var lastValue;
function quickDWRSearch(value, block, counter) {
	
//	var value = field.value;
//    var id = field.id;
	var menu = block + "DWRMenu" + counter;
	
    if (value.length > 2 && value != lastValue) {
    
        lastValue = value;
        value = value+'*';
    
	    QuickSearchDWR.search(value, 50, {
	    	callback:function(resultList) { parseResult(resultList, block, counter); }	    
	    });
    
    } else {
        document.getElementById(menu).style.display = "none";
    }
}

function quickDWROntologyNameSearch(value, block, counter) {

    if (value == '')
        return;

    QuickSearchDWR.search(value, 1, {
        callback:function(resultList) { parseOntologyNameResult(resultList, block, counter); }
    });
}

function parseOntologyNameResult(results, block, counter) {
    var label = results[0].chebiName;

    var labelField = block + "LabelField" + counter;
    document.getElementById(labelField).value = label;
}

var ajaxAdvSearchResults;
function parseResult(results, block, counter) {
	
	ajaxAdvSearchResults = results;
    var page = 1;
	
	drawPage(block, counter, page);
    
}

function drawPage(block, counter, page) {
	
	var results = ajaxAdvSearchResults;
	var maxPerPage = 10;
	var init = (page - 1) * maxPerPage;
	var max = page * maxPerPage;
	if (max > results.length) max = results.length;
	
	var content = "<ul>";
	for (i=init;i<max;i++) {
		if (results[i].definition != null)
			var title = results[i].definition;
		content += "<li><a " + (title?"title='"+title+"'":"") + " href=\"javascript: insertValue('"+block+"', '"+counter+"', '"+results[i].chebiId+"', '"+results[i].chebiName+"')\">"+results[i].chebiName.substr(0,50)+"</a></li>";
	}
	
	if (results.length > maxPerPage*page)
		content += "<li><a href=\"javascript: drawPage('"+block+"','"+counter+"',"+(++page)+")\">Next Page >></a></li>";
	content += "</ul>";
	
	var menu = block + "DWRMenu" + counter;
    var menuNode = document.getElementById(menu);
	menuNode.innerHTML = content; 
	menuNode.style.display = "block";	
}

function insertValue(block, counter, value, label) {

	var textField = block + "TextField" + counter;
	var menu = block + "DWRMenu" + counter;
	var labelField = block + "LabelField" + counter;
	
	document.getElementById(textField).value = value;
    document.getElementById(labelField).value = label;
//	document.getElementById(labelField).innerHTML = label;
//	document.getElementById(labelField).title = label;
	document.getElementById(menu).style.display = "none";

	// incomingOntology expected. Add an "if" in case you need it.
	var relationship = block + "Relationship" + counter;
	var relationNode = document.getElementById(relationship);
	if (relationNode.selectedIndex == 0)
		relationNode.selectedIndex = 1;
}

var damnMenuToBeHidden;
var alive;
function dismissDWRMenu(block, counter) {
	var menu = block + "DWRMenu" + counter;
    damnMenuToBeHidden = menu;
    alive = false;
    setTimeout("hideDamnMenu()", 2000);
}

function keepAlive(val) {
	alive = val;
}
function hideDamnMenu() {
    if (damnMenuToBeHidden != null && !alive)
        document.getElementById(damnMenuToBeHidden).style.display = "none";
}

//========================
//ADVANCED SEARCH 
// Submit/Search/Reset part
//
//developer: adekker
//========================

function checkForStructures() {
    var str = document.getElementById('advancedSearchFT_structure');
    var edt = document.getElementById('Editor');
    
    str.value = edt.getMolFile();
}

function checkStructureChanges(searchMethod) {

    if (searchMethod == null)
        searchMethod = 'substructure';
    
	if (searchMethod == 'substructure') { //substructure
		document.getElementById("strictlyStereoDiv").style.visibility = "visible";
		document.getElementById("similarityLevel").style.visibility = "hidden";
	} else if (searchMethod == 'similarity') { //similarity
		document.getElementById("strictlyStereoDiv").style.visibility = "hidden";
		document.getElementById("similarityLevel").style.visibility = "visible";
	} else { //exact
		document.getElementById("strictlyStereoDiv").style.visibility = "hidden";
		document.getElementById("similarityLevel").style.visibility = "hidden";
	}
	
}

function submitSearch(form) {
	checkForStructures();
    form.submit();

}

function resetSearch(form) {

    if (document.getElementById('Editor') != null) document.getElementById('Editor').clear();

    resetBlock("textQueries");
    resetBlock("incomingOntologyQueries");
    resetBlock("formulaQueries");
    resetBlock("molecularWeightQueries");
    resetBlock("chargeQueries");
    resetBlock("datasourceQueries");
    
    return false;
}

function resetBlock(parentBlock) {

	var parentNode = document.getElementById(parentBlock);
	var divNodes = parentNode.getElementsByTagName("div");

	// Get rows
    while (divNodes.length > 1) {
        document.getElementById(parentBlock).removeChild(divNodes[0]);
    }
    
    // Now there is only one! 
    var id = divNodes[0].getAttribute("id");
	var block = parentBlock.substr(0, parentBlock.length - 3) + "y";
	var counter = id.substring(block.length, id.length);

	removeThisRow(block, parseInt(counter));
}


//========================
//QUICK SEARCH BOX 
//
//developer: adekker
//========================

//Remove the white spaces from begin and end.
function trim(str) {
	return str.replace(/^\s+|\s+$/g, '') ;
}

function quicksearchfocus(field) {
	field.value = "";
}

function quicksearchblur(field) {
	if (trim(field.value) == "")
		field.value = "Search ChEBI here!";
}

