// Reset all the input and selection fields in the specified form.
function resetForm(formName) {
    // Get the form
    var myForm = document.getElementById(formName);
    // Loop through its elements.
    for (var i = 0; i < myForm.elements.length; i++) {
        var myField = myForm.elements[i];
        var myType = myField.type.toLowerCase();
        // Reset this element in the appropriate fashion for its type.
        switch (myType) {
        case "text" :
        case "textarea" :
            myField.value = "";
            break;
        case "radio" :
        case "checkbox" :
            myField.checked = false;
            break;
        case "select-one" :
            myField.selectedIndex = 0;
            break;
        case "select-multiple" :
            myField.selectedIndex = -1;
            break;
        }
    }
}

// Show the header section appropriate to the page width.
// Wide pages get a complicated banner, narrow ones a title.
function fixSizing() {
    var myTopBar = document.getElementById("nmpdrTopBar");
    var myTitle = document.getElementById("nmpdrTitle");
    var mySearcher = document.getElementById("searcher");
    var newSize = document.body.clientWidth;
    if (newSize < 850) {
        myTopBar.className = "invisible";
        myTitle.className = "visible";
        mySearcher.className = "narrowSearcher";
    } else {
        myTopBar.className = "visible";
        myTitle.className = "invisible";
        mySearcher.className = "wideSearcher";
    }
}

// Return the url suffix for the specified topic in the specified web.
function urlSuffix(text, web, topic) {
    var retVal = "/";
    var dotLoc = text.indexOf(".");
    if (dotLoc >= 0) {
        retVal += text.substring(0, dotLoc) + "/" + text.substring(dotLoc+1);
    } else if (text != '') {
        retVal += web + "/" + text;
    } else {
        retVal += web + "/" + topic;
    }
    return retVal;
}

// Submit the search form in the mode indicated by the
// radio button.
function submitSearchForm() {
    var qBox = document.getElementById("WSbox");
    clearDefaultandCSS(qBox);
    var jumpForm = document.getElementById("jumpForm");
    fixAction();
    jumpForm.submit();
}

// Fix the action on the jump form according to the selected search type.
function fixAction() {
    var jumpForm = document.getElementById("jumpForm");
    var radioButton = document.getElementById("WSdataRadio");
    if (radioButton.checked) {
        jumpForm.action = document.getElementById("WSdataScript").value;
    } else {
        jumpForm.action = document.getElementById("WSpageScript").value;
    }

}

// Make a text field ready for input
function clearDefaultandCSS(el) {
    if (!el.defaultValue) {
        el.defaultValue = el.value;
    }
    if (el.defaultValue == el.value) {
        el.value = "";
    }
    // If Dynamic Style is supported, clear the style
    removeClass(el, "patternFormFieldDefaultColor");
}

// Convert a text field for display
function setDefaultText(el) {
    if (el.value == "" && el.defaultValue) el.value = el.defaultValue;
    addClass(el, "patternFormFieldDefaultColor");
}

// Remove the given class from an element, if it is there
function removeClass(element, classname) {
    var classes = getClassList(element);
    if (!classes) return;
    var index = indexOf(classname,classes);
    if (index >= 0) {
        classes.splice(index,1);
        setClassList(element, classes);
    }
}

// Return TRUE if the given class is found in an element.
function hasClass(element, classname) {
    var classes = getClassList(element);
    var retVal = false;
    if (classes) {
        var index = indexOf(classname, classes);
        retVal = (index >= 0);
    }
    return retVal;
}

// Add the given class to the element, unless it is already there
function addClass(element, classname) {
    var classes = getClassList(element);
    if (!classes) return;
    if (indexOf(classname, classes) < 0) {
        classes[classes.length] = classname;
        setClassList(element,classes);
    }
}

// Replace the given class with a different class on the element.
// The new class is added even if the old class is not present.
function replaceClass(element, oldclass, newclass) {
    removeClass(element, oldclass);
    addClass(element, newclass);
}

// Get an array of the classes on the object.
function getClassList(element) {
    if (element.className && element.className != "") {
        return element.className.split(' ');
    }
    return [];
}

// Set the classes on an element from an array of class names
// Cache the list in the 'classes' attribute on the element
function setClassList(element, classlist) {
    element.className = classlist.join(' ');
}

// Determine the first index of a string in an array.
// Return -1 if the string is not found.
function indexOf(inElement, inArray) {
    if (!inArray || inArray.length == undefined) return -1;
    var i, ilen = inArray.length;
    for (i=0; i<ilen; ++i) {
        if (inArray[i] == inElement) return i;
    }
    return -1;
}

// Select all items in a menu.
function selectAll(fieldName) {
    var field = document.getElementById(fieldName);
    for (var i = 0; i < field.length; i++) {
        field[i].selected = true;
    }
}

// Deselect all items in a menu.
function clearAll(fieldName) {
    var field = document.getElementById(fieldName);
    for (var i = 0; i < field.length; i++) {
        field[i].selected = false;
    }
}

// Find the items in a menu that have a specified string in the text.
// This method returns an array. The array value is TRUE for each
// field that matches the string and FALSE otherwise.
function findTyped(field, srchFieldName) {
    var srchValue = document.getElementById(srchFieldName).value.toLowerCase();
    var retVal = new Array();
    for (var i = 0; i < field.length; i++) {
        if (srchValue == "") {
            retVal[i] = true;
        } else {
            var myText = field[i].text.toLowerCase();
            var searchLoc = myText.indexOf(srchValue);
            retVal[i] = (searchLoc >= 0);
        }
    }
    return retVal;
}

// Display only the items in a menu that have a specified string
// in the text.
function showTyped(fieldName, srchFieldName) {
    var field = document.getElementById(fieldName);
    var found = findTyped(field, srchFieldName);
    for (var i in found) {
        if (found[i]) {
            removeClass(field[i], 'Hidden');
        } else {
            addClass(field[i], 'Hidden');
        }
    }
}

// Select the items in a menu that have a specified string
// in the text. This also removes the 'hidden' class
// from all elements and clears the search field.
function selectShowing(fieldName, srchFieldName) {
    var field = document.getElementById(fieldName);
    var found = findTyped(field, srchFieldName);
    for (var i in found) {
        removeClass(field[i], 'Hidden');
        if (found[i]) {
            field[i].selected = true;
        }
    }
    var searchField = document.getElementById(srchFieldName);
    searchField.value = "";
}


// Select or de-select the first N items in a menu.
function selectSome(fieldName, n, flag) {
    var field = document.getElementById(fieldName);
    for (i = 0; i < n; i++) {
        field[i].selected = flag;
    }
    for (i = n; i < field.length; i++) {
        field[i].selected = ! flag;
    }
}

// Specify value for a field if it's empty.
function setIfEmpty(field, val) {
    if (field.value == "") {
        field.value = val;
    }
}

// Deselect in field 2 all the items selected in field 1,
// and do a showSelected on whichever fields change. The
// fields in this case are menus, and the size and target
// parameters are as they as for showSelected. Both menus
// must contain the same items in the same order.
function crossUnSelect(field1, target1, field2, target2, size) {
    var count = 0;
    for (i = 0; i < field1.length; i++) {
        if (field1[i].selected && field2[i].selected) {
            field2[i].selected = false;
            count++;
        }
    }
    showSelected(field1, target1, size);
    if (count > 0) {
        showSelected(field2, target2, size);
    }
}


// Display the selected items from a menu in a paragraph
// element. The target should be the ID of a <div> element
// that can be used to display the result.
function showSelected(fieldName, targetName, urlName, size) {
    // We'll build two lists: "texts" will have names and IDs, and "values" will have IDs only.
    var texts = "";
    var values = "";
    // Track the number of genomes and the display length of each string in here.
    var count = 0;
    var textSize = 0;
    var valueSize = 0;
    // The delimiter goes in front of each label, and the suffix after. The delimiter
    // changes but the suffix is always the same.
    var delim = "";
    var suffix = "</a>";
    // Get the URL prefix for the seed viewer links.
    var urlPrefix = document.getElementById(urlName).value;
    // Get the select control.
    var field = document.getElementById(fieldName);
    // Loop through the list, looking for selected items.
    for (i = 0; i < field.length; i++) {
        // Process this field if it's selected.
        if (field[i].selected) {
            // Extract the name and ID.
            var thisText = field[i].text;
            var thisValue = field[i].value;
            // Record the additional length.
            textSize += thisText.length;
            valueSize += thisValue.length;
            // Each organism ID will be hyperlinked to its seed viewer page.
            var linker = "<a href=\"" + urlPrefix + thisValue + "\" target=\"_blank\">";
            var linkValue = linker + thisValue + suffix;
            thisText = thisText.replace(thisValue, linkValue);
            texts += delim + thisText + suffix;
            values += delim + linkValue + suffix;
            delim = ", ";
            count++;
        }
    }
    if (count == 0) {
        texts = "Nothing selected.";
    } else {
        if (valueSize > size) {
            texts = count.toString() + " genomes selected";
        } else if (textSize > size) {
            texts = values;
        }
    }
    var targetField = document.getElementById(targetName);
    targetField.innerHTML = texts;
}


var __isFireFox = navigator.userAgent.match(/gecko/i);  
//returns the absolute position of some element within document  
function GetElementAbsolutePos(element) {  
    var res = new Object();  
    res.x = 0; res.y = 0;  
    if (element !== null) {  
        res.x = element.offsetLeft;   
        res.y = element.offsetTop;   
        var offsetParent = element.offsetParent;  
        var parentNode = element.parentNode;  
        while (offsetParent !== null) {  
            res.x += offsetParent.offsetLeft;  
            res.y += offsetParent.offsetTop;  
            if (offsetParent != document.body && offsetParent != document.documentElement) {  
                res.x -= offsetParent.scrollLeft;  
                res.y -= offsetParent.scrollTop;  
            }
            //next lines are necessary to support FireFox problem with offsetParent  
            if (__isFireFox) {  
                while (offsetParent != parentNode && parentNode !== null) {  
                    res.x -= parentNode.scrollLeft;  
                    res.y -= parentNode.scrollTop;  
                    parentNode = parentNode.parentNode;  
                }      
            }  
            parentNode = offsetParent.parentNode;  
            offsetParent = offsetParent.offsetParent;  
        }  
    }  
    return res;  
}

var hovering = null;

// Show a tooltip. This is a pretty limited-use thing for the search controls,
// necessitated by a mysterious failure of the old technology.
function doTooltip(object, text) {
    doTooltip2(object, text, object.clientWidth, object.clientHeight);
}

// Same as above, but with explicit x and y offsets, for mapped diagrams.
function doTooltip2(object, text, x2, y2) {
    if (hovering == null) {
        hovering = document.createElement("div");
        hovering.id = "popup_tooltip_div";
        hovering.className = "invisible";
        document.body.appendChild(hovering);
        hovering.onclick = undoTooltip;
        hovering.style.position = 'absolute';
    }
    hovering.innerHTML = text;
    var objectPos = GetElementAbsolutePos(object);
    var leftPos = objectPos.x + x2;
    var topPos = objectPos.y + y2;
    hovering.style.left = leftPos.toString() + "px";
    hovering.style.top = topPos.toString() + "px";
    hovering.className = "visible";
    object.onmouseout = undoTooltip;
}

function undoTooltip() {
    hovering.className = "invisible";
}

// Create a new window with a page in it.
function doPagePopup(divThing, url) {
    window.open(url);
}

// Create a new page with a tip and a link in it.
function doHintPopup(divThing, url, tip) {
    var tipURL = tip + '?cover=hint;width=' + window.outerWidth.toString() +
                 ';height=' + window.outerHeight.toString() + ";more=" +
                 url;
    window.open(tipURL, 'Hint',
                'width=300,height=300,status=yes,resizable=yes,scrollbars=yes');
}

// Front page tab simulation.

//here you place the ids of every element you want.
var ids=new Array('a0','a1','a2','a3','a4','a5','a6','a7','a8');

function switchid(id){	
	hideallids();
	showdiv(id);
}

function hideallids(){
	//loop through the array and hide each element by id
	for (var i=0;i<ids.length;i++){
		hidediv(ids[i]);
	}		  
}

function hidediv(id) {
	//safe function to hide an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'none';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'none';
		}
		else { // IE 4
			document.all.id.style.display = 'none';
		}
	}
}

function showdiv(id) {
	//safe function to show an element with a specified id
		  
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'block';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'block';
		}
		else { // IE 4
			document.all.id.style.display = 'block';
		}
	}
}


