/**
 * This function checks the currently selected organism in the SELECT control
 * with the ID "organism-name" and hides/unhides the associated DIV section
 * with the same name. 
 * 
 * opt	The currently select option for the organism checkbox.
 */
function displayOrganismCheckboxes(opt) {
   //Find the parent element of the hidden DIV sections with the ID of
   // organism-arrays and hide them first
   var array = window.parent.document.getElementById('organism-arrays');
   if(array != null) {
   	//Get all child elements and loop through them
	   var children = array.childNodes;
	   for(var i = 0; i < children.length; i++) {
	   	//For the current node, check to see if it's a DIV and set it's 
	   	// style.display attribute to none (hide it)
	   	var node = children.item(i);
	   	if(node.tagName=="DIV") {
	   		if(node.id==opt.value) {
				   node.style.display='block';
	   		}
				else {   	
		   		//Hide all child elements of this DIV section
		   		node.style.display='none';
	   		
		   		//Also (cuz I can't think of a better way to handle this in the
		   		// JSP...) uncheck and unselect all INPUTs beneath this DIV
		   		var divchildren = node.childNodes;
		   		for(var di = 0; di < divchildren.length; di++) {
		   			//Get the next child node, see if it's an input
		   			var childnode = divchildren.item(di);
		   			if(childnode.tagName=="INPUT") {
		   				if(childnode.type=="checkbox") {
			   				childnode.checked=false;
		   				}
		   				if(childnode.type=="radio") {
		   					childnode.selected=false;
		   				}
		   			}//If this is an input
		   		}//For each child node of the DIV
				}//If not the current selected DIV
	   	}//if This is a DIV section element
	   }//For each child node
	}//If array id tag found
}

/**
 * This function populates the select box identified by ctrlId, with options
 * values from the DIV section identified by optDivId, where those options have
 * an 'organism' attribute that matches the current value in 'orgVal'. 
 * 
 * ctrlId		The id of the select control to populate
 * optDivId		The id of the DIV section that contains options
 * orgVal		The 'organism' attribute value of options to be selected
 */
function updateSelectOptions(ctrlId, optDivId, orgVal) {
	//Get the target select control and the source DIV section
   var selCtrl 	= document.getElementById(ctrlId);
   var divSection = document.getElementById(optDivId);
	
//	alert('Changing options in select dropdown '+ctrlId+', looking for '+orgVal+' in DIV section '+optDivId);
	
	//Be sure both controls were found before proceeding
   if(selCtrl != null && divSection != null) {
   	//Remove all existing elements from the target select control
      for(var index = selCtrl.length-1; index >= 0; index--) {
         selCtrl.remove(index); 
      }

		//Loop through all child nodes of the DIV section, examining all 
		// elements with OPTION tag names to see if their organism value
		// matches the specified orgVal
		var options = divSection.getElementsByTagName('JAMES');
//      alert('Processing div child nodes for organism id matches. '+options.length+' elements...');

      for(var index = 0; index < options.length; index++) {
      	//Get the next child element
         var option = options[index];
         
         //Check to see if this is an OPTION element and it's 'organism'
         // attribute matches
         if(option.tagName=="JAMES") {
         	//Get the organism value
         	var org = option.getAttribute("organism");
//         	alert('Found JAMES tag with organism id '+org+'...');
         	
         	//See if the current option has a matching organism id and
         	// display it in the list if necessary
         	if(org == orgVal) {
	         	//Match, so create a new option from this OPTION element
					var newopt = 
						new Option(option.getAttribute('text'),
									  option.getAttribute('value'), 
									  false);

	            //Add the new option to the select control
	            selCtrl.options.add(newopt);
	            
	            //If selected, set the selected value
	            if(option.getAttribute("selected") != null) {
	            	newopt.selected=true;
	            }
         	}
         }
         
         //Sort
         sortListBox(selCtrl);
      }
   }
   else {
   	alert("Control(s) not found!");
   }
}

/**
 * sort function for ordering select boxes
 */
function compareText (opt1, opt2) { 
	// not case sensitive 
	return opt1.text.toLowerCase() < opt2.text.toLowerCase() ? -1 : 
			 opt1.text.toLowerCase() > opt2.text.toLowerCase() ? 1 : 0; 
} 

/**
 * Function for sorting a listbox by object
 * 
 */
function sortListBox(pListBox) { 
	var compareFunction = compareText; 
	var options = new Array (pListBox.options.length); 
	for (var i = 0; i < options.length; i++) 
		options[i] = 
			new Option ( 
				pListBox.options[i].text, 
				pListBox.options[i].value, 
				pListBox.options[i].defaultSelected, 
				pListBox.options[i].selected 
			); 
	options.sort(compareFunction); 
	pListBox.options.length = 0; 
	for (var i = 0; i < options.length; i++) 
		pListBox.options[i] = options[i]; 
} 


/**
 * Given the id value and show boolean, show or hide the following DIV section 
 * by setting it's style.display value to 'block' or 'none'.
 * 
 * id		The id of the DIV section to modify
 * show	boolean, show or hide the DIV section (true = show)
 */
function divVisibility(id, show) {
	//Get a list of all document DIV elements 
	var divArray = document.getElementsByTagName("DIV");
	for(var i = 0; i < divArray.length; i++) {
		//Get the next DIV
		var div = divArray.item(i);
		
		//Check the id against our argument
		if(div.id==id) {
			//Show or hide?
			div.style.display=(show)?'block':'none';
		}
	}
}

/**
 * This function checks to be sure that the select box 'sbox' has options, and
 * changes the enabled/disabled state of 'submit' accordingly.
 *  
 * submit	The button to disable if no options are selected
 * sbox		The select object id to check
 */
function updateSubmit(submit, sbox) {
	//Get the select control and submit button
	var selctrl = document.getElementById(sbox);
	var button = document.getElementById(submit);
	
	//Check the value of the select box
	if(selctrl != null && selctrl.value == "") {
		button.disabled = true;
	}
	else {
		button.disabled = false;
	}
}

/**
 * Displayes the PleaseWait.jsp in the iframe window specified
 * 
 * iframeId		The id of the window to update
 */
function iframePleaseWait(iframeId) {
	//Set please wait page
	document.getElementById(iframeId).src="PleaseWait.jsp";
}


/**
 * 
 */
function setExpressionURL(iframeId, orgid, gene, array, showdegen, shownmd, showdomain, footer) {
	//Get the IFRAME
	var iframe = document.getElementById(iframeId);
	if(iframe!=null) {
		//Build the URL
		var url = "ExpressionImage.jsp?orgid="+orgid+"&symbol="+gene+
			"&array="+array;

		//See if we should show degen probes
		if(showdegen=='on') {
			url = url+"&includeDegen=on";
		}
		
		if(shownmd=='on') {
			url = url+"&includeNMD=on";
		}

		if(showdomain=='on') {
			url = url+"&includeDomain=on";
		}
		
		if(footer != null) {
			url = url+"&imageFooter="+footer;
		}

		//Set the iframe source URL
		iframe.src=url;
	}
}

/**
 * Resizes the specified iframe object to fit contents.
 * 
 */
function resizeImageIFrame(iframeId) {
	//Get the IFRAME
	//alert("Resizing image iframe");
	var target = document.getElementById(iframeId);
	if(target!=null) {
		//Declare height and width
		var height = 0;
		var width = 0;
		
		//Check for elements
		if(target.Document && target.Document.body.scrollHeight) {
			//IE syntax
			height = target.Document.body.scrollHeight;
			width = target.Document.body.scrollWidth;
			target.style.height = height;
			
			//alert("IE frame offsetHeight="+height+", scrollWidth="+width);

			//IE needs a push out the first time to cover labels and 
			// expression pane width. Keep track of this in an attribute
			if(target.getAttribute('widthadjusted') != 'true') {
				width += 300;
				target.setAttribute('widthadjusted', 'true');
			}
			target.style.width = width;
		}
//		else if(target.contentDocument && target.contentDocument.body.offsetHeight) {
		else if(target.contentWindow && target.contentWindow.document.body.scrollWidth) {
			//Firefox syntax
			var bdy = target.contentWindow.document.body
			var h = bdy.offsetHeight;
			var w = bdy.scrollWidth;

			var o = target.contentWindow.document.getElementById("imagecontainer");
			if(o) w = o.offsetWidth;
		
			//alert("Firefox frame offsetHeight="+h+", scrollWidth="+w);

			target.height = h + 'px';
			target.width = (w+50) + 'px';
			// target.width = '1000px';
		}
	}
}

/**
 *
 */
function adjustDivHeight(objid, sz) {
	var obj = document.getElementById(objid);
	if(obj) {
		//alert("resizing div to "+sz+" pixels");
	 	obj.style.height = (sz) + "px";
	}
}

/**
 *
 */
 function adjustDivWidth(objid, sz) {
	var obj = document.getElementById(objid);
	if(obj) {
		//alert("resizing div to "+sz+" pixels");
	 	obj.style.width = (sz) + "px";
	}
 }
 
/**
 * Sets the URL for the help pane in the window header. Each JSP should call this
 * function after the header is loaded to populate the help area of the page
 * with the contents of the provided URL.
 */
function setHelpURL(url) {
	//Find the document DIV for help
	var d = document.getElementById('helppanecontents');
	if(d != null) {
		d.src = url
	}
}

/**
 * Toggles the visibility of the div with the specified ID
 * 
 */
function toggleDivVisible(id) {
	var d = document.getElementById(id);
	if(d != null) {
		if(d.style.display=='none') {
			d.style.display='block';
		}
		else {
			d.style.display='none';
		}
	}
}

/**
 * Sets the page name in the header
 * 
 */
function setPageName(n) {
	//Find the document element to set text for
	var e = document.getElementById('doctitle');
	if(e != null) {
		e.innerHTML = n;
	}	
}

/**
 * Finds all input controls with ids with the specified prefix, and checks the
 * value length, cancelling submission if any are invalid.
 * 
 */
function checkSequenceLength(prefix, min, type) {
	//Declare vars
	var valid = true;
	var i = 0;
	
	//Get the first control
	var ctrl = window.parent.document.getElementById(prefix+i);
	do {
		
		if(ctrl.value.length > 0 && ctrl.value.length < min) {
			//This control's content is invalid
			ctrl.className="invalid";
			valid = false;
		}
		
		//Increment and get next control
		i++;
		ctrl = window.parent.document.getElementById(prefix+i);
	} while(ctrl != null);

	//Alert the user that submission was cancelled
	if(valid == false) {
		var msg = window.parent.document.getElementById('sequencemessage');
		if(msg != null) {
			msg.innerHTML='ERROR! Sequences must be at least '+min+' '+type+' in length!';
		}
		else {
			//Can't find error box? just alert box it
			alert('Minimum sequence length is '+min+' '+type+'. Please enter valid sequences.');
		}
	}	
	//Return state
	return valid;
}

/**
 * This function checks to be sure the input contains the minimum amount of
 * characters as specified by the argument. Valid states are chars == 0 and 
 * chars >= minchars. The class is toggled between none ("") and invalid.
 * 
 */
function checkMinChars(ctrl, minchars) {
	if(ctrl.value.length > 0 && ctrl.value.length < minchars) {
		ctrl.className="invalid";
	}
	else {
		ctrl.className="";
	}
}

/**
 * This function ensures that the specified field contains the minimum number
 * of characters specified. If the minimum is not met, then the focus is not 
 * allowed to leave the input control. A length of 0 is allowed, as well as
 * anything equal to or over minchars.
 * 
 */
function requireMinChars(ctrl, minchars) {
	if(ctrl.value.length > 0 && ctrl.value.length < minchars) {
		//Change the class to 'invalid' which should indicate, visually, that 
		// this field value is, um, invalid
		ctrl.className="invalid";
		
		//Return false for form submit
		return false;
	}
	else {
		//Valid, set no classname (inherited) and return true
		ctrl.className="";
		return true;
	}
}

/**
 * Focuses the specified text box object if the class is "invalid"
 * 
 */
function focusTextboxOnInvalid(ctrl) {
}





/**
 * This function displays the div section who's id matches the value of the
 * option provided, within the enclosing tag with the id provided. All other
 * DIVs within the divContainerId tag are hidden. This is used to hide
 * probeset images except the one matching the option selected.
 * 
 * divContainerId		The ID of the tag that contains the divs to hide/show
 * opt					A select box option who's value is the id of the div
 * 						to show.
 */
/*
function displayProbesetImage(divContainerId, opt) {
	//Get the element with the id specified
	var container = document.getElementById(divContainerId);
	if(container != null) {
   	//Get all child elements and loop through them
	   var children = container.childNodes;
	   for(var i = 0; i < children.length; i++) {
	   	//For the current node, check to see if it's a DIV and set it's 
	   	// style.display attribute to none (hide it)
	   	var node = children.item(i);
	   	if(node.tagName=="DIV") {
	   		if(node.id==opt.value) {
				   node.style.display='block';
	   		}
				else {   	
		   		//Hide all child elements of this DIV section
		   		node.style.display='none';
				}//If not the current selected DIV
	   	}//if This is a DIV section element
	   }//For each child node
	}//If array id tag found
}
*/
