//this function handles all rounded corner function call with various div elements
var textSize=new Array();
var itemIden=new Array();
var curtitle="";
var i=0;

function roundedCorners()
{
		DD_roundies.addRule('#nav,#qsearch,#related_window,#related_window_opportunity,#related_window_relevancy','10px',true);
		DD_roundies.addRule('h1,#login_header,#login_header_guest,#overlaytitlecontainer,#related_window_top_bar','10px 10px 0 0', true);
		DD_roundies.addRule('h3,.rec_list,.results_pagination','10px', true);
		DD_roundies.addRule('.results_header,.results_navigation,.results_navigation_rec','10px', true);
		DD_roundies.addRule('h3#all_corners,.browse_header','10px', true);
		DD_roundies.addRule('h1#all_corners','10px', true);
		DD_roundies.addRule('.button,.cont_next_button,.cont_next_button_prf,.cont_next_res_button,.cont_nxt_but','8px', true); 
		DD_roundies.addRule('ul#ser a','10px 10px 0 0', true);
		DD_roundies.addRule('.button_level4,.button_disabled a:link,..button_disabled a:visited,.refine_btn ','6px', true);
		DD_roundies.addRule('#selected_profiles_action,#related_window_bottom_bar','0 0 10px 10px', true);
		DD_roundies.addRule('#nav_profile a:hover','0px 10px 10px 0px', true);
		DD_roundies.addRule('#nav_home a:hover','10px 0px 0px 10px', true);
		DD_roundies.addRule('h3,#homepage_box,#homepage_box_award,#homepage_box_rec,.page_title_head','10px 10px 0 0', true);
	
}
// this function handles all functions that need to be loaded "onLoad"
function init(domain){
	
	IconOver();
	inputHelp();
	checkTextSize();	
	toolTip();
	externalLinks(domain);
	
	var obj = window.document.getElementById('save_email_html');
	if(obj){
		obj.checked = true;
	}
	var email_html = window.document.getElementById('email_html');
	if(email_html){
		email_html.checked = true;
	}
	
	

}
function IconOver(){
	if (!document.getElementById) {
		return;
	}
	var imgOrigSrc = '';
	var imgPreload = new Array();
	var images = document.getElementsByTagName('img');
	for (var i = 0; i < images.length; i++) {
		if (images[i].getAttribute('rsrc')) {
			if (images[i].getAttribute('active') == 'true'){
				//originalSrc = images[i].getAttribute('src');
				//images[i].setAttribute('osrc',originalSrc);
				
				var activeSrc = images[i].getAttribute('asrc');
				images[i].setAttribute('src',activeSrc);
				
				images[i].parentNode.onmouseover = function() {}
				images[i].parentNode.onmouseout = function() {}
			}
			else {
				imgPreload[i] = new Image();
				imgPreload[i].src = images[i].getAttribute('rsrc');
				
				var originalSrc = images[i].getAttribute('osrc');
				if (!originalSrc){
					originalSrc = images[i].getAttribute('src');
					images[i].setAttribute('osrc',originalSrc);
				}
				var currentSrc = images[i].getAttribute('src');
				if (originalSrc !=  currentSrc){
					images[i].setAttribute('src',originalSrc);
				}
						
				images[i].parentNode.onmouseover = function() {
					imgOrigSrc = this.firstChild.getAttribute('osrc');
					this.firstChild.setAttribute('src',this.firstChild.getAttribute('rsrc'));
				}
				images[i].parentNode.onmouseout = function() {
					this.firstChild.setAttribute('src',imgOrigSrc);
				}
			}
		}
	}
}

function inputHelp(){
	var inputElements = document.getElementsByTagName('input');

	for (i=0; i < inputElements.length; i++) {
		var helpvalue = inputElements[i].getAttribute('helpvalue');
		if (helpvalue){
			if(inputElements[i].value == ''){
				inputElements[i].value = helpvalue;
			}
			inputElements[i].onfocus = function(){
				if(this.value == this.getAttribute('helpvalue')){
					this.value=''; 
					this.className = 'input_text input_sel';
				}
			}
			inputElements[i].onblur = function(){
				if(this.value == ''){
					this.value = this.getAttribute('helpvalue'); 
					this.className = 'input_text input_des';
				}
			}
		}
	}
}


function checkTextSize(){
	
	var newSize = readCookie('goTextSize');
	
	if (newSize){		
		SetFontSize(newSize);
	}
	else{
		SetFontSize('0.7em');
	}
		
}

function externalLinks(domain) {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		var href = anchor.getAttribute("href");
		var firstChar;
		if (href) {
			firstChar = href.charAt(0);
		}
		if (href && !anchor.target &&
			!(firstChar == '#' || firstChar == '/') &&
			href.indexOf("elsevier.com") < 0 &&
			href.indexOf(domain) < 0)
		{
			anchor.target = "_goexternal";
		}
	}
}

// --------------------------------------------
// Common utilities
// --------------------------------------------

/** Show the indicated div. */
function showDiv(divId) {
	if(divId=='save_set_alert')
	{
		document.getElementById('save_email_html').checked=true;
	}
	var div = document.getElementById(divId);
	if (div) {
		div.style.display="block";
	}
}

/** Hide the indicated div. */
function hideDiv(divId) {
	
	var div = document.getElementById(divId);
	if (div) {
		div.style.display="none";
	}
}
function resDiv(divId) {
	var div = document.getElementById(divId);
	if (div) {
		div.style.display="";
	}
}
/* Set the maximum width of an element.
 * @param id
 * @param width
 */
function setElementWidth(id, width) {
	var element = document.getElementById(id);
	if (element) {
		element.style.maxWidth=width;
	}
}

// expand and contracts a single element
function toggleExpCon(element,targetID){
	var status = element.getAttribute('status');
	var icon = element.firstChild;

	if (status == 'expand'){
		target = document.getElementById(targetID);
		target.style.display = 'none';
		icon.setAttribute('src','/static/images/grant/icon_expand.gif');
		icon.setAttribute('alt','Expand this section');
		icon.setAttribute('title','Expand this section');
		element.setAttribute('status','contract');
	}
	else if (status == 'contract'){
		target = document.getElementById(targetID);
		target.style.display = 'block';
		icon.setAttribute('src','/static/images/grant/icon_contract.gif');
		icon.setAttribute('alt','Contract this section');
		icon.setAttribute('title','Contract this section');
		element.setAttribute('status','expand');
	}
}

function toolTip(){
	if (!document.getElementById) {
		return;
	}
	var links = document.getElementsByTagName('a');
	for (var i = 0; i < links.length; i++) {
		if (links[i].getAttribute('tooltip')) {
			links[i].className = 'tooltip';
			
			links[i].onmouseover = function() {
				showTooltipTimeout(this,'tooltip');
			}
			links[i].onmouseout = function() {
				resetTooltipTimeout('tooltip');
			}
		}
	}
}

var TooltipOver = false;

function showTooltipTimeout(object,tooltipId){
	var objectId = object.getAttribute('id');
	TooltipOver = true;
	
	setTimeout('showTooltip(\''+objectId+'\',\''+tooltipId+'\')',250);
}

function showTooltip(objectId,tooltipId){
	
	
	if (TooltipOver){
		var tooltipElement = document.getElementById(tooltipId);
		tooltipElement.style.display = "block";
		
		var objectElement = document.getElementById(objectId);
		var text = objectElement.getAttribute('tooltip');
		tooltipElement.innerHTML = text;
		
		var pos = findPos(objectElement);
		var dim = findDim(objectElement);
		
		tooltipElement.style.top = pos.y - dim.h + 'px';
		tooltipElement.style.left = pos.x + dim.w + 'px';
		
		
	}
}

function resetTooltipTimeout(tooltipId){
	TooltipOver = false;
	setTimeout('resetTooltip(\''+tooltipId+'\')',500);
}

function resetTooltip(tooltipId){
	tooltipElement = document.getElementById(tooltipId);
	tooltipElement.style.display = "none";
	if(iframeObj && iev < 7) {
		iframeObj.style.display = 'none';
	}
}

function showOverlayById(divid,w,h,showClose){
	if(divid == "send_opportunity" || divid == "award" || divid == "send_opportunity_open" || divid == "send_opportunity_closed"){ // validation for limiting the number of results that can be emailed
		// Get the list of selected items
		var elements;
		if(divid == "send_opportunity_closed"){
			elements = document.getElementsByName('doc_select_closed');
		}else{		
			elements = document.getElementsByName('doc_select');
		}
		var ids;
		if (elements && elements.length > 0) {
			// Append the items onto the id list.
			for ( var i = 0; i < elements.length; i++) {
				if (elements[i].checked) {
					if (ids) {
						ids = ids + ';' + elements[i].value;
					} else {
						ids = elements[i].value;
					}
				}
			}
		}
		
		if(divid != "send_opportunity_open" && divid != "send_opportunity_closed"){
			// Check for additional selected items from another page
			var seldiv = document.getElementById('sel_items');
			if (seldiv && seldiv.innerHTML && seldiv.innerHTML.length > 0) {
				ids = ids + ';' + seldiv.innerHTML;
			}
		}
		
		if (ids) {
			ids = deduplicateList(ids, ';');
		}
		if (ids == null){
			alert("You need to select some items before choosing this action.");
			return false;
		}
		// check if user has not exceeded the maximum no of results that can be selected
		var idTokens = ids.split(';');
		var noOfIds = idTokens.length;
		var maxSelectCount = document.getElementById('emailSelectedMaxSelectCount').value;
		var result = true;
		
		//check if the user has selected all results
		if ( divid != "send_opportunity_closed" && document.getElementById('allSelectedinAllPages').value == "true" ) {
			var hitCount = document.getElementById("totalresultscount").value; 
			var deSelectedResultsString = document.getElementById("deselectedResults").value;
			var deSelectedResultsTokens = deSelectedResultsString.split(';'); 
			var selectedResultsCount = hitCount - (deSelectedResultsTokens.length);
			if ( selectedResultsCount > maxSelectCount ) {
				//if the number of results exceed the configured limit, alert the user
				result = confirm("You can email a maximum of "+ maxSelectCount+" items.Select OK to "
						+"proceed to email the first "+ maxSelectCount +" documents or Cancel if you do not want to continue.");
				if (result == false) {
					clearSelection();
					return false;
				}
			}
		}else if (divid == "send_opportunity_closed" && document.getElementById('allSelectedinAllPagesClosed').value == "true") {
			
				var hitCount = document.getElementById("totalresultscountClosed").value; 
				var deSelectedResultsString = document.getElementById("deselectedResultsClosed").value;
				var deSelectedResultsTokens = deSelectedResultsString.split(';'); 
				var selectedResultsCount = hitCount - (deSelectedResultsTokens.length);
				
				if ( selectedResultsCount > maxSelectCount ) {
					//if the number of results exceed the configured limit, alert the user
					result = confirm("You can print a maximum of "+ maxSelectCount+" items. Select OK to "
							+"proceed to print the first "+ maxSelectCount +" documents or Cancel if you do not want to continue.");
					if (result == false) {
						clearSelectionClosed();
						return false;
					}
				}
			
		}
		else if ( noOfIds > maxSelectCount ) {
			// user has manually selected more results than the configured limit
			result = confirm("You can email a maximum of "+ maxSelectCount+" items.Select OK to"
					+"proceed to email the first "+ maxSelectCount +" documents or Cancel if you do not want to continue.");
			if (result == false) {
				if(divid == "send_opportunity_closed"){clearSelectionClosed();}
				else{clearSelection();}
				return false;
			}
		}
		
	}
	
	
	var div = document.getElementById(divid);
	
	var resultsNavigationDropDownListElement = document.getElementById("resultsNavigationDropDownList");
	if(resultsNavigationDropDownListElement){
		resultsNavigationDropDownListElement.style.visibility="hidden";	
	}
	
	// The div has to be visible in order to get a calculated height from it.
	showDiv(divid);
	var divHeight = div.offsetHeight;
	hideDiv(divid);
	showOverlay(div.innerHTML,document.getElementById(divid+'_title').innerHTML,w,divHeight,showClose);
	
	// Try to set the height of the div based on what's being displayed in it.
	element = document.getElementById('overlay');
	element.style.height = '';
}

function showOverlay(html,title,w,h,showClose){
	var element = document.getElementById('overlay');
	var elementInner = document.getElementById('overlayinner');
	elementInner.innerHTML=html;

	var elementTitle = document.getElementById('overlaytitle');
	elementTitle.firstChild.innerHTML=title;
	showDiv('overlay');
	var titleHeight = elementTitle.offsetHeight;
	hideDiv('overlay');
	
	var w = parseInt(w);
	var h = parseInt(h) + titleHeight;
	
	element.style.width = w + 'px';
	element.style.height = h + 'px';
	
	var screensize = browserScreensize();
	var screenWidth = screensize.w;
	var screenHeight = screensize.h;
	
	var leftOffset = (screenWidth - w) / 2;
	var topOffset = (screenHeight - h) / 2;
	
	// Add in the offset based on use of the scrollbar.
	var ScrollTop = document.body.scrollTop;
	if (ScrollTop == 0)
	{
	    if (window.pageYOffset) {
	        ScrollTop = window.pageYOffset;
	    } else if (document.body.parentElement) {
	    	var topParent = document.body.parentElement;
	    	while (topParent.parentElement) {
	    		topParent = topParent.parentElement;
	    	}
	        ScrollTop = topParent.scrollTop;
	    }
	}
	if (ScrollTop && typeof ScrollTop == "number") {
		topOffset = topOffset + ScrollTop;
	}

	element.style.left = leftOffset + 'px';
	element.style.top = topOffset + 'px';
	
	if (!showClose){
		document.getElementById('closeOverlay').style.display = 'none';
	}
	else {
		document.getElementById('closeOverlay').style.display = 'block';
	}
	
	element.style.display = 'block';
}

function hideOverlay(){
	var resultsNavigationDropDownListElement = document.getElementById("resultsNavigationDropDownList");
	if(resultsNavigationDropDownListElement){
		resultsNavigationDropDownListElement.style.visibility="visible";
		}
	var element = document.getElementById('overlay');
	element.style.display = 'none';
	return false
}

function browserScreensize(){
	var browser = BrowserDetect.browser;
	var version = BrowserDetect.version;
	var winW;
	var winH;
	if (browser == 'Explorer'){
		if (version >= '5'){
			winW = document.documentElement.clientWidth-20;
			winH = document.documentElement.clientHeight-20;
		}
	}
	else if (browser == 'Firefox'){
		winW = window.innerWidth-16;
		winH = window.innerHeight-16;
	}
	else {
		winW = window.innerWidth-16;
		winH = window.innerHeight-16;
	}
	
	return {w:winW, h:winH};
}

function colorTimeout(elementID,steps,startColor,endColor,isec) {
	var element = document.getElementById(elementID);
	if (element){
		var startColorArr = new Array();
		startColorArr['r'] = h2d(startColor.substr(0,2));
		startColorArr['g'] = h2d(startColor.substr(2,2));
		startColorArr['b'] = h2d(startColor.substr(4,2));
		
		var endColorArr = new Array();
		endColorArr['r'] = h2d(endColor.substr(0,2));
		endColorArr['g'] = h2d(endColor.substr(2,2));
		endColorArr['b'] = h2d(endColor.substr(4,2));
		
		var tempColorArr = new Array();
		tempColorArr['r'] = Math.round(startColorArr['r'] + ((endColorArr['r'] - startColorArr['r']) / steps));
		tempColorArr['g'] = Math.round(startColorArr['g'] + ((endColorArr['g'] - startColorArr['g']) / steps));
		tempColorArr['b'] = Math.round(startColorArr['b'] + ((endColorArr['b'] - startColorArr['b']) / steps));
		
		var newColor = d2h(tempColorArr['r'])+ d2h(tempColorArr['g']) + d2h(tempColorArr['b']);
		var newColorHTML = "#" + newColor;
		element.style.backgroundColor = newColorHTML;
		
		//inverseColor = d2h(255-tempColorArr['r'])+ d2h(255-tempColorArr['g']) + d2h(255-tempColorArr['b']);
		var textColorArr = new Array();
		textColorArr['r'] = Math.round((5 * steps));
		textColorArr['g'] = Math.round((5 * steps));
		textColorArr['b'] = Math.round((5 * steps));
		
		var invColor = d2h(textColorArr['r'])+ d2h(textColorArr['g']) + d2h(textColorArr['b']);
		var invColorHTML = "#" + invColor;
		element.style.color = invColorHTML;
		
		steps--;
		if (steps >= 1) {
			setTimeout('colorTimeout(\''+elementID+'\','+steps+',\''+newColor+'\',\''+endColor+'\','+isec+')',isec);
		}
		else {
			element.style.color = '';
		}
	}
}

function d2h(d) {
	var hex = d.toString(16);
	if (d <= 15){
		hex = '0' + hex;
	}
	return hex;
}

function h2d(h) {
	var dec = parseInt(h,16);
	return dec;
}

// shows and hides a one or multiple elements
function showHide(show,hide,method){
	if (show != ''){
		var showArr = show.split(",");
		for (var i = 0; i < showArr.length; i++) {
			var showElement = document.getElementById(showArr[i]);
			if (method == 'visibility'){
				showElement.style.visibility = 'visible';
			}
			else if (method == 'display'){
				showElement.style.display = 'block';
			}
		}
	}
	
	if (hide != ''){
		var hideArr = hide.split(",");
		for (var i = 0; i < hideArr.length; i++) {
			var hideElement = document.getElementById(hideArr[i]);
			if (method == 'visibility'){
				hideElement.style.visibility = 'hidden';
			}
			else if (method == 'display'){
				hideElement.style.display = 'none';
			}
		}
	}
}

function checkChange(elementID){
	var element = document.getElementById(elementID);
	if (element.getAttribute('value') != element.firstChild.value){
		return true;
	}
	return true;
}

function checkMailPass(){
	 if ((checkChange('input_email') == false) && ((checkValue('password1') == false) && (checkValue('password2') == false) )){
		 showHide('','change_email_notice','display');
	 }
}

function checkValue(elementID){
	var element = document.getElementById(elementID);
	if (element.value != ''){
		return true;
	}
	else {
		return false;
	}
}

/*
 * Build a Grant Optimizer URL (without the host and context root).
 * @param path The path to the page.  Required.
 * @param event The event to execute on that page.  Can be null.
 * @param querystring The querystring to append to the URL.  Can be null.
 * @param nameArray Array of parameter names to be added to the querystring.
 *        Can be null.  If supplied the length should match the length of the
 *        valueArray.
 * @param valueArray Array of parameter values to be added to the querystring.
 *        Can be null.  If supplied the length should match the length of the
 *        nameArray.
 * @return The url as a string.
 */ 
function buildURL(path, event, querystring, nameArray, valueArray)
{
	var url = path;
	var addedQS = false;

	// Check to see if there is an event and add it.
	if (event && event != undefined) {
		url = url+'?'+event+'=';
		addedQS = true;
	}
	
	// Check to see if there is a querystring and add it.	
	if (querystring && querystring != undefined) {
		if (!addedQS) {
			url = url+'?';
		} else {
			url = url+'&';
		}
		url = url+querystring;
		addedQS = true;
	}
	
	// Check to same querystring parameters came in as name/value pairs and
	// if so add them.
	if (nameArray && nameArray != undefined) {
		var addAmp = true;
		if (!addedQS) {
			url = url+'?';
			addAmp = false;
		}
		for(var i=0; i<nameArray.length; i++) {
			if (addAmp) {
				url = url+'&';
			}
			url = url+nameArray[i]+'='+valueArray[i]
			addAmp = true;
		}
		addedQS = true;
	}
	return url;
}
function ClipBoard() {
	var holdtext = document.getElementById('holdtext');
	var copytext = document.getElementById('copytext');	
	holdtext.innerText = copytext.innerText;		
	var Copied = holdtext.createTextRange();		
	Copied.execCommand("RemoveFormat");
	Copied.execCommand("Copy");	
	return false;
} 
/*
 * Given a url, the name of a parameter on that url, and a value to put
 * into that parameter, modify the indicated parameter on the url.
 * @param linkId
 * @param param
 * @param value
 */
function modifyLinkParameter(linkId, param, value)
{
	var link = document.getElementById(linkId);
	var url = link.href;
	
	if (url.indexOf('?') < 0) {
		// The url has no query string.  Just put on the parameter.
		url = url+'?'+param+'='+value;
	} else {
		// Check to see if the parameter exists already on the URL.
		var loc = url.indexOf('?'+param+'=');
		if (loc < 0) {
			loc = url.indexOf('&'+param+'=');
		}
		
		if (loc > 0)
		{
			// The parameter is already on the URL, replace the value.
			loc = url.indexOf('=',loc);
			var endLoc = url.indexOf('&',loc);
			if (endLoc > 0) {
				// This parameter is in the middle somewhere.
				url = url.substring(0,loc+1)+value+url.substring(endLoc);
			} else {
				// This is the last parameter.
				url = url.substring(0,loc+1)+value;
			}
		} else {
			// The parameter isn't on the URL, append it.
			url = url+'&'+param+'='+value;
		}
	}
	
	link.href = url;
}

/*
 * Set a cookie.
 * @param name The name of the cookie
 * @param value The value to set into the cookie
 * @param days The number of days the cookie should be valid for.  null
 * if the cookie should be valid only for this browser session.
 */
function createCookie(name, value, days)
{
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+escape(value)+expires+"; path=/";
}

/*
 * Get the value for a cookie.
 * @param c_name The name of the cookie
 */
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
	}
	return null;
}

/*
 * Erase the indicated cookie value.
 */
function eraseCookie(name)
{
	createCookie(name, "", -1);
}

function SetFontSize(newSize){
	
	bodyElement = document.getElementById('body');
	bodyElement.style.fontSize = newSize;
	
	imageSmallElement = document.getElementById('fontSmall');
	imageMediumElement = document.getElementById('fontMedium');
	imageLargeElement = document.getElementById('fontLarge');		
	if (newSize == '0.7em'){
		imageSmallElement.setAttribute('active','true');
		imageMediumElement.setAttribute('active','false');
		imageLargeElement.setAttribute('active','false');
	}
	else if (newSize == '0.77em'){
		imageSmallElement.setAttribute('active','false');
		imageMediumElement.setAttribute('active','true');
		imageLargeElement.setAttribute('active','false');
	}
	else if (newSize == '0.83em'){
		imageSmallElement.setAttribute('active','false');
		imageMediumElement.setAttribute('active','false');
		imageLargeElement.setAttribute('active','true');
	}
	IconOver();	
	newSizeOld = readCookie('goTextSize');
	if (newSize != newSizeOld){
		createCookie('goTextSize',newSize,365);
	}
	return false;
}


function encode_utf8( s )
{
  return escape( s );
}

function decode_utf8( s )
{
  return unescape( s );
}

function inputHelp(){
	var inputElements = document.getElementsByTagName('input');
	
	for (i=0; i < inputElements.length; i++) {
		helpvalue = inputElements[i].getAttribute('helpvalue');
		if (helpvalue){
			inputElements[i].style.color = '#707070';
			inputElements[i].value = helpvalue;
			inputElements[i].onfocus = function(){
				if(this.value == this.getAttribute('helpvalue')){
					this.value=''; 
					this.style.color = '#000000';
				}
			}
			inputElements[i].onblur = function(){
				if(this.value == ''){
					this.value = this.getAttribute('helpvalue'); 
					this.style.color = '#707070';
				}
			}
		}
	}
}

function setCursor(element){
	element.style.cursor = 'pointer';
}

function infoboxFader(fadeElementID,waittime,infoTXT){
	fadeElement = document.getElementById(fadeElementID);
	if (fadeElement){
		fadeElement.innerHTML = infoTXT;
		fadeElement.style.display = 'block';
		fadeElement.style.height = 'auto';
		
		steps = 10;
		step = 10;
		isec = 50;
		
		if (doResize){
			totalHeight = fadeElement.offsetHeight;
			fadeElement.style.height = totalHeight + 'px';
			divided = Math.round(totalHeight / steps-1);
			fadeElement.style.overflow = 'hidden';
		}
		else {
			totalHeight = 0;
			divided = 0;
		}
		
		setTimeout('alphaFader(\''+fadeElementID+'\','+steps+','+step+','+isec+','+totalHeight+','+divided+')',waittime);
	}
}

function alphaFader(elementid,steps,step,isec,totalHeight,divided) {
	element = document.getElementById(elementid);
	
	if (doResize){
		newHeight = totalHeight-divided;
		element.style.height = newHeight + 'px';
	}
	else {
		newHeight = 0;
		divided = 0;
	}
	
	if (step == 0) {
		element.style.display = 'none';
	} 
	else {
		if (step < 10){
			setOpacity(element,step);
		}
		setTimeout('alphaFader(\''+elementid+'\','+steps+','+(step-1)+','+isec+','+newHeight+','+divided+')',isec);
	}
}

function setOpacity(element,value) {
	element.style.opacity = value/10;
	element.style.filter = 'alpha(opacity=' + value*10 + ')';
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return {x:curleft, y:curtop};
}

function findDim(obj) {
	var curw = curh = 0;

	curw = obj.offsetWidth;
	curh = obj.offsetHeight;

	return {w:curw, h:curh};
}

function parentExists() {
	if (window.opener){
		return true;
	}
	else {
		return false;
	}
}

// --------------------------------------
// AJAX calls for saving a search
// --------------------------------------

/*
 * Gather the data from the page to build the request to save a search.
 */
function buildSaveSearch(content, searchtext, limtext, extext, hits)

{
	
	var title = document.getElementById('save_name').value;
	var alert=false;
	var frequency;
	var email;
	var format;
	if (document.getElementById('save_alert_yes').checked) {
		alert=true;
		frequency = document.getElementById('save_frequency').value;
		var emailSelect = document.getElementById('save_email');
		var email = emailSelect.value;
		if (document.getElementById('save_email_html').checked) {
			format = "H";
		} else {
			format = "T";
		}
	}
	
	saveSearch(
		title, content, searchtext, limtext, extext, hits,
		alert, frequency, email, format);
}

/*
 * Make call to save the search.
 */
var totalHitSearch;
function saveSearch(
	title, content, searchtext, limtext, extext, hits,
	alert, frequency, email, format)
{
	totalHitSearch = hits;
	 // Build the parameters string
	var parms;
	parms =
		'title='+encode_utf8(title)+
		'&content='+content+
		'&searchtext='+encode_utf8(searchtext)+
		'&limtext='+encode_utf8(limtext)+
		'&extext='+encode_utf8(extext)+
		'&hits='+hits;
	if (alert) {
		// If we're alerting on this, add that data to the string.
		parms = parms+
		  	'&frequency='+frequency+
		  	'&email='+encode_utf8(email)+
		  	'&format='+format;
	}
	
	var myAjax = new Ajax.Request(
		'/my/search/save',
		{ method: 'post',
		  parameters: parms,
		  onComplete: doneSavingSearch
		}
	);
}

/*
 * Method that gets called after a search has been saved.
 */
function doneSavingSearch(originalRequest)
{
	var responseText = originalRequest.responseText;
	
	if (responseText.indexOf("<status>error</status>")>0) {
		alert('Unable to save search: '+
			responseText.substring(
				responseText.indexOf("<message>")+9,
				responseText.indexOf("</message>")));
	} else {
		if(totalHitSearch == 0){
			alert('No results found. Your search has been saved.');
		}else{
			alert('Your search has been saved.');
		}
	}
}
//--------------------------------------
//AJAX calls for Editing the saved search
//--------------------------------------

/*
* Gather the data from the page to build the request to save a search.
*/
function buildEditSearch(id)
{
	var title = document.getElementById('save_name_'+id).value;	
	editSearch(id,title);
}

/*
* Make call to Edit the Saved Search.
*/
function editSearch(id,title)
{
	// Build the parameters string
	var parms;
	parms =
		'id='+id+
		'&title='+title;
	
	var myAjax = new Ajax.Request(
		'/my/search/edit',
		{ method: 'post',
		  parameters: parms,
		  onComplete: doneEditingSavedSearch
		}
	);
}
/*
* Method that gets called after Editing a Saved Search.
*/
function doneEditingSavedSearch(originalRequest)
{
	var responseText = originalRequest.responseText;
	
	if (responseText.indexOf("<status>error</status>")>0) {
		alert('Unable to set alert: '+
			responseText.substring(
				responseText.indexOf("<message>")+9,
				responseText.indexOf("</message>")));
	} else {
		window.location.reload();
	}
}
// --------------------------------------
// AJAX calls for setting an alert on a saved search
// --------------------------------------

/*
 * Gather the data from the page to build the request to save a search.
 */
function buildSetAlert(id)
{
	var frequency = document.getElementById('alert_frequency_'+id).value;
	var email = document.getElementById('alert_email_'+id).value;
	var format;
	if (document.getElementById('alert_format_html_'+id).checked) {
		format = "H";
	} else {
		format = "T";
	}
	
	setAlert(id, frequency, email, format);
}

/*
 * Make call to set the alert.
 */
function setAlert(id, frequency, email, format)
{
	// Build the parameters string
	var parms;
	parms =
		'id='+id+
	  	'&frequency='+frequency+
	  	'&email='+encode_utf8(email)+
	  	'&format='+format;
	
	var myAjax = new Ajax.Request(
		'/my/alert/save',
		{ method: 'post',
		  parameters: parms,
		  onComplete: doneSettingAlert
		}
	);
}

/*
 * Method that gets called after an alert has been set.
 */
function doneSettingAlert(originalRequest)
{
	var responseText = originalRequest.responseText;
	
	if (responseText.indexOf("<status>error</status>")>0) {
		alert('Unable to set alert: '+
			responseText.substring(
				responseText.indexOf("<message>")+9,
				responseText.indexOf("</message>")));
	} else {
		window.location.reload();
	}
}

// --------------------------------------
// AJAX calls for setting an alert on a document
// --------------------------------------

/*
 * Gather the data from the page to build the request to save a search.
 */
function buildSetContentAlert(id, content)
{
	var frequency = document.getElementById('alert_frequency_'+id).value;
	var email = document.getElementById('alert_email_'+id).value;
	var format;
	if (document.getElementById('alert_format_html_'+id).checked) {
		format = "H";
	} else {
		format = "T";
	}
	var alertContent;
	if (document.getElementById('save_alerttype_sol').checked) {
		alertContent = "S";
	} else {
		alertContent = "A";
	}
	
	setContentAlert(id, content, alertContent, frequency, email, format);
}

/*
 * Make call to set the alert.
 */
function setContentAlert(id, content, alertContent, frequency, email, format)
{
	// Build the parameters string
	var parms;
	parms =
		'id='+id+
		'&content='+content+
		'&alertContent='+alertContent+
	  	'&frequency='+frequency+
	  	'&email='+encode_utf8(email)+
	  	'&format='+format;
	
	var myAjax = new Ajax.Request(
		'/my/content/alert/save',
		{ method: 'post',
		  parameters: parms,
		  onComplete: doneSettingContentAlert
		}
	);
}

/*
 * Method that gets called after an alert has been set.
 */
function doneSettingContentAlert(originalRequest)
{
	var responseText = originalRequest.responseText;
	
	if (responseText.indexOf("<status>error</status>")>0) {
		alert('Unable to set alert: '+
			responseText.substring(
				responseText.indexOf("<message>")+9,
				responseText.indexOf("</message>")));
	} else {
		window.location.reload();
	}
}

// --------------------------------------
// AJAX calls for saving a document
// --------------------------------------

/*
 * Gather the data from the page to build the request to save a document.
 */
function buildSaveDocument(id, content)
{
	var title = document.getElementById('save_name').value;
	var createAlert=false;
	var frequency;
	var alertContent;
	var email;
	var format;
	
	var saveAlertCheck = document.getElementById('save_alert_yes');
	if (saveAlertCheck && saveAlertCheck.checked) {
		createAlert=true;
		frequency = document.getElementById('save_frequency').value;
		var emailSelect = document.getElementById('save_email');
		var email = emailSelect.value;
		if (document.getElementById('save_alerttype_sol').checked) {
			alertContent = "S";
		} else {
			alertContent = "A";
		}
		if (document.getElementById('save_email_html').checked) {
			format = "H";
		} else {
			format = "T";
		}
	}
	
	saveDocument(
		id, content, title, createAlert, frequency, alertContent, email, format);
}

/*
 * Make call to save the document.
 */
function saveDocument(
	id, content, title,
	createAlert, frequency, alertContent, email, format)
{
	// Do something about characters that cause problems
	var loc = -1;
	while ((loc = title.indexOf("\u2019")) >= 0) {
		if (loc == 0) {
			title = "'"+title.substring(1);
		} else if (loc == (title.length-1)) {
			title = title.substring(0,loc)+"'";
		} else {
			title = title.substring(0,loc)+"'"+title.substring(loc+1);
		}
	}
	
	// Build the parameters string
	var parms;
	parms =
		'id='+id+
		'&title='+encode_utf8(title)+
		'&content='+content;
		
	if (createAlert) {
		// If we're alerting on this, add that data to the string.
		parms = parms+
		  	'&frequency='+frequency+
		  	'&alertContent='+alertContent+
		  	'&email='+encode_utf8(email)+
		  	'&format='+format;
	}
	
	var myAjax = new Ajax.Request(
		'/my/document/save',
		{ method: 'post',
		  parameters: parms,
		  onComplete: doneSavingDocument
		}
	);
}

/*
 * Method that gets called after a document has been saved.
 */
function doneSavingDocument(originalRequest)
{
	var responseText = originalRequest.responseText;
	
	if (responseText.indexOf("<status>error</status>")>0) {
		alert('Unable to save favorite: '+
			responseText.substring(
				responseText.indexOf("<message>")+9,
				responseText.indexOf("</message>")));
	} else {
		alert('Your favorite has been saved.');
	}
}

// ************************************************************
// Generic methods for working with lists of items.
// ************************************************************

/*
 * Select all items found using the indicated name.
 * @param name The name of the items to look for.
 */
function selectAllItems(name)
{
	var elements = document.getElementsByName(name);
	if (elements && elements.length > 0) {
		for(var i=0; i<elements.length; i++) {
			elements[i].checked = true;
		}
	}
}

/*
 * Deselect all items found using the indicated name.
 * @param name The name of the items to look for.
 */
function deselectAllItems(name)
{
	var elements = document.getElementsByName(name);
	if (elements && elements.length > 0) {
		for(var i=0; i<elements.length; i++) {
			elements[i].checked = false;
		}
	}
}
 
/*
 * Build an URL to process all items selected in the list.  An alert
 * message is displayed if there are no items selected.
 * @param path The path to send the request to.
 * @param parm The parameter to use for the selected items.  The value for
 * the paramter is taken from teh value of the selected items.
 * @param backpath The page to return to in the event of an error.
 * @param name The name of the items to look for.
 * @return true if there were items selected, false if there were not.
 */
function processSelectedItems(path, parm, backpath, name)
{
	var url = path+"?";
	
	// Get the list of selected items
	var foundOne = false;
	var elements = document.getElementsByName(name);
	if (elements && elements.length > 0) {
		// Append the items onto the url.
		for(var i=0; i<elements.length; i++) {
			if (elements[i].checked) {
				url = url+"&"+parm+"="+elements[i].value;
				foundOne = true;
			}
		}

		if (!foundOne) {
			// There weren't any selected items.
			alert("You need to select some items before choosing this action.");
			
		}else if(confirm('Are you sure you want to delete this selection?')){
			window.location = url;
			
		}
	}
	return false;
}

// --------------------------------------
// AJAX calls for setting a recommendations alert
// --------------------------------------

/*
 * Gather the data from the page to build the request to save an alert
 * on new recommendations.
 */
var totalhitrec;
function buildRecommendationAlert(totalhit)
{	
	totalhitrec = totalhit;
	var frequency = document.getElementById('save_frequency').value;
	var emailSelect = document.getElementById('save_email');
	var email = emailSelect.value;
	var format;
	if (document.getElementById('save_email_html').checked) {
		format = "H";
	} else {
		format = "T";
	}
	
	setRecommendationAlert(frequency, email, format);
	
}

/*
 * Make call to set the recommendation alert.
 */
function setRecommendationAlert(frequency, email, format)
{
	// Build the parameters string
	var parms;
	parms =
	  	'frequency='+frequency+
	  	'&email='+encode_utf8(email)+
	  	'&format='+format;
	
	var myAjax = new Ajax.Request(
		'/my/recommendations/alert/save',
		{ method: 'post',
		  parameters: parms,
		  onComplete: doneSettingRecommendationAlert
		}
	);
}

/*
 * Method that gets called after an alert has been set.
 */
function doneSettingRecommendationAlert(originalRequest)
{
	var responseText = originalRequest.responseText;
	
	if (responseText.indexOf("<status>error</status>")>0) {
		alert('Unable to set alert: '+
			responseText.substring(
				responseText.indexOf("<message>")+9,
				responseText.indexOf("</message>")));
	} else {
		
		if(totalhitrec == 0){
			alert('No recommendations found. Your search alert has been saved.');
		}else{
			alert('Your alert on new recommendations has been created.');
		}
		window.location.reload();
	}
}

// --------------------------------------
// AJAX calls for editing a recommendations alert
// --------------------------------------

/*
 * Gather the data from the page to build the request to edit an alert
 * on recommendations.
 */
function changeRecommendationAlert()
{
	var frequency = document.getElementById('save_frequency').value;
	var emailSelect = document.getElementById('save_email');
	var email = emailSelect.value;
	var format;
	if (document.getElementById('save_email_html').checked) {
		format = "H";
	} else {
		format = "T";
	}
	
	editRecommendationAlert(frequency, email, format);
}

/*
 * Make call to edit the recommendation alert.
 */
function editRecommendationAlert(frequency, email, format)
{
	// Build the parameters string
	var parms;
	parms =
	  	'frequency='+frequency+
	  	'&email='+encode_utf8(email)+
	  	'&format='+format;
	
	var myAjax = new Ajax.Request(
		'/my/recommendations/alert/save',
		{ method: 'post',
		  parameters: parms,
		  onComplete: doneEditingRecommendationAlert
		}
	);
}

/*
 * Method that gets called after an alert has been edited.
 */
function doneEditingRecommendationAlert(originalRequest)
{
	var responseText = originalRequest.responseText;
	
	if (responseText.indexOf("<status>error</status>")>0) {
		alert('Unable to edit alert: '+
			responseText.substring(
				responseText.indexOf("<message>")+9,
				responseText.indexOf("</message>")));
	} else {
		alert('Your alert on new recommendations has been modified.');
	}
}

// --------------------------------------
// AJAX calls for deleting a recommendations alert
// --------------------------------------

/*
 * Gather the data from the page to build the request to delete an alert
 * on recommendations.
 */
function deleteRecommendationAlert()
{
	answer = confirm("Are you sure you want to delete your recommendation alert?")
	if(answer != 0){
		var myAjax = new Ajax.Request(
			'/my/recommendations/alert/delete',
			{ method: 'post',
			  onComplete: doneDeletingRecommendationAlert
			}
		);
	}
}

/*
 * Method that gets called after an alert has been deleted.
 */
function doneDeletingRecommendationAlert(originalRequest)
{
	var responseText = originalRequest.responseText;
	
	if (responseText.indexOf("<status>error</status>")>0) {
		alert('Unable to delete alert: '+
			responseText.substring(
				responseText.indexOf("<message>")+9,
				responseText.indexOf("</message>")));
	} else {
		alert('You have successfully deleted your recommendation alert.');
		window.location.reload();
	}
}

// --------------------------------------
// AJAX calls for saving multiple selected documents
// --------------------------------------

/*
 * Gather the data from the page to build the request to save multiple documents.
 */
function saveSelectedContent(content, checkboxId)
{
	return saveSelectedContentById(content, checkboxId);
}

/*
 * Gather the data from the page to build the request to save multiple documents.
 */
function saveSelectedContentById(content, checkboxId)
{
	var ids;
	// Get the list of selected items
	if (checkboxId != "doc_select_closed") {
		ids = document.getElementById('selectedResults').value;
	} else {
		ids = document.getElementById('selectedResultsClosed').value;
	}
	
	if (ids) {
		ids = deduplicateList(ids, ';');
	}else{
		// There weren't any selected items.
		alert("You need to select some items before choosing this action.");
		return false;
	}
	
	// check if user has not exceeded the maximum no of results that can be selected
	var idTokens = ids.split(';');
	var noOfIds = idTokens.length;
	var maxSelectCount = document.getElementById('addSelectedToFavouritesMaxSelectCount').value;
	var result = true;
	var resultsSelectionLimited=false;
	//check if the user has selected all results
	if ( checkboxId != "doc_select_closed" && document.getElementById('allSelectedinAllPages').value == "true" ) {
		var hitCount = document.getElementById("totalresultscount").value; 
		var deSelectedResultsString = document.getElementById("deselectedResults").value;
		var deSelectedResultsTokens = deSelectedResultsString.split(';'); 
		var selectedResultsCount = hitCount - (deSelectedResultsTokens.length);
		
		if ( selectedResultsCount > maxSelectCount ) {
			//if the number of results exceed the configured limit, alert the user
			result = confirm("You can add a maximum of "+ maxSelectCount+" items.Select OK to "
					+"proceed to print the first "+ maxSelectCount +" documents or Cancel if you do not want to continue.");
			if (result == true) {
				 resultsSelectionLimited = true;
			}
			else
			{
				clearSelection();
				return false;
			}
		}
	}
	else if ( checkboxId == "doc_select_closed" && document.getElementById('allSelectedinAllPagesClosed') != null ) {
		if ( document.getElementById('allSelectedinAllPagesClosed').value == "true" ) {
			var hitCount = document.getElementById("totalresultscountClosed").value; 
			var deSelectedResultsString = document.getElementById("deselectedResultsClosed").value;
			var deSelectedResultsTokens = deSelectedResultsString.split(';'); 
			var selectedResultsCount = hitCount - (deSelectedResultsTokens.length);
			
			if ( selectedResultsCount > maxSelectCount ) {
				//if the number of results exceed the configured limit, alert the user
				result = confirm("You can add a maximum of "+ maxSelectCount+" items. Select OK to "
						+"proceed to print the first "+ maxSelectCount +" documents or Cancel if you do not want to continue.");
				if (result == true) {
					 resultsSelectionLimited = true;
				}
				else
				{
					clearSelectionClosed();
					return false;
				}
			}
		}
	}
	else if ( noOfIds > maxSelectCount ) {
		result = confirm("You can add a maximum of "+ maxSelectCount+" items.Select OK to"
				+"proceed to print the first "+ maxSelectCount +" documents or Cancel if you do not want to continue.");
		if (result == true) {
			ids = "";
			for (i = 0; i < maxSelectCount; i++ ) {
				ids = ids + idTokens[i] + ';'; 
			}
		}else{
			
			clearSelection();
			return false;
		}	
			
	}
	
	
	// Build the parameters string
	var parms;
	parms =
		'content='+content+
		'&id='+ids;
	
	
	if (resultsSelectionLimited) { 
		/* send to the action bean a flag indicating that the user was forced
		 	select limited set of results */
		parms = parms+'&resultsSelectionLimited='+resultsSelectionLimited;
	}
	var desel;
	var allsel;
	if(checkboxId == "doc_select_closed"){
		desel=document.getElementById("deselectedResultsClosed").value;
		allsel=document.getElementById('allSelectedinAllPagesClosed').value;
		
	}else{
		desel=document.getElementById("deselectedResults").value;
		allsel=document.getElementById('allSelectedinAllPages').value;
		
	}	
	parms = parms+'&'+"deselectedResults"+'='+desel;
	parms = parms+'&'+"allSelectedinAllPages"+'='+allsel;
	
	
	var myAjax = new Ajax.Request(
		'/my/document/save/multiple',
		{ method: 'post',
		  parameters: parms,
		  onComplete: doneSavingSelectedDocuments
		}
	);
	
}

/*
 * Method that gets called after a document has been saved.
 */
function doneSavingSelectedDocuments(originalRequest)
{
	var responseText = originalRequest.responseText;
	
	if (responseText.indexOf("<status>error</status>")>0) {
		alert('Unable to save favorites: '+
			responseText.substring(
				responseText.indexOf("<message>")+9,
				responseText.indexOf("</message>")));
	} else {
		alert('Your favorites have been saved.');
	}
}

// --------------------------------------
// Function used for printing multiple docs
// --------------------------------------

/*
 * Gather the selections and open a window showing the details for all of
 * the selections.
 */
function printSelectedContent(content,checkboxId,auid)
{
	return printSelectedContentById(content, checkboxId,auid);
}

/*
 * Gather the selections and open a window showing the details for all of
 * the selections.
 */
function printSelectedContentById(content, checkboxId,auid)
{
	// Get the list of selected items
	var ids;
	
	if (checkboxId != "doc_select_closed") {
		ids = document.getElementById('selectedResults').value;
	} else {
		ids = document.getElementById('selectedResultsClosed').value;
	}	
	
	if (ids) {
		ids = deduplicateList(ids, ';');
	}else{
		// There weren't any selected items.
		alert("You need to select some items before choosing this action.");
		return false;
	}
	
	// check if user has not exceeded the maximum no of results that can be selected
	var idTokens = ids.split(';');
	var noOfIds = idTokens.length;
	var maxSelectCount = document.getElementById('printSelectedMaxSelectCount').value;
	var result = true;
	var resultsSelectionLimited=false;	
	
	//check if the user has selected all results
	if ( checkboxId != "doc_select_closed" && document.getElementById('allSelectedinAllPages').value == "true" ) {
		var hitCount = document.getElementById("totalresultscount").value; 
		var deSelectedResultsString = document.getElementById("deselectedResults").value;
		var deSelectedResultsTokens = deSelectedResultsString.split(';'); 
		var selectedResultsCount = hitCount - (deSelectedResultsTokens.length);
		
		if ( selectedResultsCount > maxSelectCount ) {
			//if the number of results exceed the configured limit, alert the user
			result = confirm("You can print a maximum of "+ maxSelectCount+" items.Select OK to "
					+"proceed to print the first "+ maxSelectCount +" documents or Cancel if you do not want to continue.");
			if (result == true) {
				 resultsSelectionLimited = true;
			}
			else
			{
				clearSelection();
				return false;
			}
		}
	}
	else if ( checkboxId == "doc_select_closed" && document.getElementById('allSelectedinAllPagesClosed') != null ) {
		if ( document.getElementById('allSelectedinAllPagesClosed').value == "true" ) {
			var hitCount = document.getElementById("totalresultscountClosed").value; 
			var deSelectedResultsString = document.getElementById("deselectedResultsClosed").value;
			var deSelectedResultsTokens = deSelectedResultsString.split(';'); 
			var selectedResultsCount = hitCount - (deSelectedResultsTokens.length);
			
			if ( selectedResultsCount > maxSelectCount ) {
				//if the number of results exceed the configured limit, alert the user
				result = confirm("You can print a maximum of "+ maxSelectCount+" items. Select OK to "
						+"proceed to print the first "+ maxSelectCount +" documents or Cancel if you do not want to continue.");
				if (result == true) {
					 resultsSelectionLimited = true;
				}
				else
				{
					clearSelectionClosed();
					return false;
				}
			}
		}
	}
	else if ( noOfIds > maxSelectCount ) {
		result = confirm("You can print a maximum of "+ maxSelectCount+" items.Select OK to"
				+"proceed to print the first "+ maxSelectCount +" documents or Cancel if you do not want to continue.");
		if (result == true) {
			ids = "";
			for (var i = 0; i < maxSelectCount; i++ ) {
				ids = ids + idTokens[i] + ';'; 
			}
		}else{
			if(checkboxId == "doc_select_closed"){clearSelectionClosed();}
			else{clearSelection();}			
			return false;
		}	
			
	}
	var parms = 'id='+ids;
	if (resultsSelectionLimited) { 
		/* send to the action bean a flag indicating that the user was forced
		 	select limited set of results */
		parms = parms+'&resultsSelectionLimited='+resultsSelectionLimited;
	}
	var desel;
	var allsel;
	if(checkboxId == "doc_select_closed"){
		desel=document.getElementById("deselectedResultsClosed").value;
		allsel=document.getElementById('allSelectedinAllPagesClosed').value;
		
	}else{
		desel=document.getElementById("deselectedResults").value;
		allsel=document.getElementById('allSelectedinAllPages').value;
		
	}	
	parms = parms+'&'+"deselectedResults"+'='+desel;
	parms = parms+'&'+"allSelectedinAllPages"+'='+allsel;
	
	if (ids && (content == 'S' || content == 'SC')) {		
		if (auid) {
			parms = parms+'&auid='+auid+'&content='+content;
		}
		window.location = buildURL('/print/opportunity', null, parms, null, null);
	} else if (ids && content == 'A') {
		window.location = buildURL('/print/award', null, parms, null, null);
	}
	return false;
}

function printDetails(content){
	
	if(content == "S"){
		showDiv('opportunity_funding_body');hideDiv('opportunity_funding_body_show');showDiv('opportunity_funding_body_hide');
		showDiv('opportunity_description');hideDiv('opportunity_description_show');showDiv('opportunity_description_hide');
		showDiv('opportunity_deadline');hideDiv('opportunity_deadline_show');showDiv('opportunity_deadline_hide');
		showDiv('opportunity_dochistory');hideDiv('opportunity_dochistory_show');showDiv('opportunity_dochistory_hide');
	}else if(content == "A"){
		showDiv('award_description');hideDiv('award_description_show');showDiv('award_description_hide');
		showDiv('awardee_details');hideDiv('awardee_details_show');showDiv('awardee_details_hide');
		showDiv('award_sponsor_body');hideDiv('award_sponsor_body_show');showDiv('award_sponsor_body_hide');
		showDiv('add_awarded_grant');hideDiv('add_awarded_grant_show');showDiv('add_awarded_grant_hide');
	}else if(content == "F"){
		showDiv('fundingbody_organization');hideDiv('fundingbody_organization_show');showDiv('fundingbody_organization_hide');
		showDiv('fundingbody_description');hideDiv('fundingbody_description_show');showDiv('fundingbody_description_hide');
		showDiv('fundingbody_contact');hideDiv('fundingbody_contact_show');showDiv('fundingbody_contact_hide');		
	}else if(content == "P"){
		showDiv('fundingbody_organization');hideDiv('fundingbody_organization_show');showDiv('fundingbody_organization_hide');
		showDiv('program_description');hideDiv('program_description_show');showDiv('program_description_hide');
		showDiv('fundingbody_contact');hideDiv('fundingbody_contact_show');showDiv('fundingbody_contact_hide');		
	}
	window.print();
	return false;
}

/*
 * Gather the selections and email a list with the contents of the selections.
 */
function emailSelectedContent(content, checkboxId, searchText) {
	
	// gather the data from the page
	var recipientEmail = document.getElementById('email').value;
	var senderEmail = document.getElementById('youremail').value;
	var format;
	var message = document.getElementById('message').value;
	var subject = document.getElementById('subject').value;
	if (document.getElementById('email_html').checked) {
		format = "H";
	} else {
		format = "T";
	}
	
	return emailSelectedContentById(content, checkboxId,
			recipientEmail, senderEmail, message, subject, format, searchText);
}
//----------------------------------------
//Function used for emailing multiple docs
//----------------------------------------

/*
 * Gather the selections and email a list with the contents of the selections.
 */
function emailSelectedContentById(content, checkboxId, recipientEmail,
		senderEmail, message, subject, format, searchText) {
	
	var ids;
	// Get the list of selected items
	if (checkboxId != "doc_select_closed") {
		ids = document.getElementById('selectedResults').value;
	} else {
		ids = document.getElementById('selectedResultsClosed').value;
	}
	
	if (ids) {
		ids = deduplicateList(ids, ';');
	}else{
		// There weren't any selected items.
		alert("You need to select some items before choosing this action.");
		return false;
	}
	// check if user has not exceeded the maximum no of results that can be selected
	var idTokens = ids.split(';');
	var noOfIds = idTokens.length;
	var maxSelectCount = document.getElementById('emailSelectedMaxSelectCount').value;
	var result = true;
	var resultsSelectionLimited = false;
	

        //check if the user has selected all results
		if ( checkboxId != "doc_select_closed" && document.getElementById('allSelectedinAllPages').value == "true" ) {
              var hitCount = document.getElementById("totalresultscount").value; 
              var deSelectedResultsString = document.getElementById("deselectedResults").value;
              var deSelectedResultsTokens = deSelectedResultsString.split(';'); 
              var selectedResultsCount = hitCount - (deSelectedResultsTokens.length);
              
              if ( selectedResultsCount > maxSelectCount ) {
            	  	resultsSelectionLimited = true;
                    ids = "";
                    for (i = 0; i < maxSelectCount; i++ ) {
                          ids = ids + idTokens[i] + ';'; 
                    }
              }
        }
		else if ( checkboxId == "doc_select_closed" && document.getElementById('allSelectedinAllPagesClosed').value == "true" ) {
			
				var hitCount = document.getElementById("totalresultscountClosed").value; 
				var deSelectedResultsString = document.getElementById("deselectedResultsClosed").value;
				var deSelectedResultsTokens = deSelectedResultsString.split(';'); 
				var selectedResultsCount = hitCount - (deSelectedResultsTokens.length);
				
				if ( selectedResultsCount > maxSelectCount ) {
					resultsSelectionLimited = true;
                    ids = "";
                    for (i = 0; i < maxSelectCount; i++ ) {
                          ids = ids + idTokens[i] + ';'; 
                    }
              }
		}
		
        else if ( noOfIds > maxSelectCount ) {
                    ids = "";
                    for (i = 0; i < maxSelectCount; i++ ) {
                          ids = ids + idTokens[i] + ';'; 
                    }
                    if(checkboxId == "doc_select_closed"){
                    	 clearSelectionClosed();
                    }else{
                    	 clearSelection();
                    }
                   
        }
	
	var parms = '&recipientEmail=' + encode_utf8(recipientEmail)
			+ '&senderEmail=' + encode_utf8(senderEmail) + '&message='
			+ encode_utf8(message) + '&subject=' + encode_utf8(subject)
			+ '&format=' + format + '&searchText=' + encode_utf8(searchText);	
	
	if (resultsSelectionLimited) { 
		/* send to the action bean a flag indicating that the user was forced
		 	select limited set of results */
		parms = parms+'&resultsSelectionLimited='+resultsSelectionLimited;
	}
	var desel;
	var allsel;
	if(checkboxId == "doc_select_closed"){
		desel=document.getElementById("deselectedResultsClosed").value;
		allsel=document.getElementById('allSelectedinAllPagesClosed').value;
		
	}else{
		desel=document.getElementById("deselectedResults").value;
		allsel=document.getElementById('allSelectedinAllPages').value;
		
	}	
	parms = parms+'&'+"deselectedResults"+'='+desel;
	parms = parms+'&'+"allSelectedinAllPages"+'='+allsel;
	

	if (ids && (content == 'S' || content == 'SO' || content == 'SC' || content == 'R' || content == 'RP')) {		
		parms = parms + '&content=' + content + '&id=' + ids;
		var myAjax = new Ajax.Request('/email/opportunity/searchresults', {
			method :'post',
			parameters :parms,
			onComplete :doneSendingResults
		})
	} else if (ids && content == 'A') {
		parms = parms + '&id=' + ids;
		var myAjax = new Ajax.Request('/email/award/searchresults', {
			method :'post',
			parameters :parms,
			onComplete :doneSendingResults
		})
	} 
	
		
	
	return false;
}
/*
 * Method that gets called after a results has been sent .
 */
function doneSendingResults(originalRequest) {
	var responseText = originalRequest.responseText;

	if (responseText.indexOf("<status>error</status>") > 0) {
		alert('Unable to send email: ' + responseText.substring(responseText
				.indexOf("<message>") + 9, responseText.indexOf("</message>")));
	} else {
		alert('Your mail has been sent.');
	}
}
// --------------------------------------
// Function used for exporting multiple docs
// --------------------------------------

/*
 * Gather the selections and output a csv file with the contents of
 * the selections.
 */
function exportSelectedContent(content,checkboxId, auid)
{
	return exportSelectedContentById(content, checkboxId, auid);
}

/*
 * Gather the selections and output a csv file with the contents of
 * the selections.
 */
function exportSelectedContentById(content, checkboxId,auid)
{
	var ids;
	// Get the list of selected items
	if (checkboxId != "doc_select_closed") {
		ids = document.getElementById('selectedResults').value;
	} else {
		ids = document.getElementById('selectedResultsClosed').value;
	}
	
	if (ids) {
		ids = deduplicateList(ids,';');
	}else{
		alert("You need to select some items before choosing this action.");
		return false;
	}
	
	// check if user has not exceeded the maximum no of results that can be selected
	var idTokens = ids.split(';');
	var noOfIds = idTokens.length;
	var maxSelectCount = document.getElementById('exportToExcelMaxSelectCount').value;
	var result = true;
	var resultsSelectionLimited=false;
	//check if the user has selected all results
	if ( checkboxId != "doc_select_closed" && document.getElementById('allSelectedinAllPages').value == "true" ) {
		var hitCount = document.getElementById("totalresultscount").value; 
		var deSelectedResultsString = document.getElementById("deselectedResults").value;
		var deSelectedResultsTokens = deSelectedResultsString.split(';'); 
		var selectedResultsCount = hitCount - (deSelectedResultsTokens.length);
		
		if ( selectedResultsCount > maxSelectCount ) {
			//if the number of results exceed the configured limit, alert the user
			result = confirm("You can export a maximum of "+ maxSelectCount+" items.Select OK to "
					+"proceed to print the first "+ maxSelectCount +" documents or Cancel if you do not want to continue.");
			if (result == true) {
				 resultsSelectionLimited = true;
			}
			else
			{
				clearSelection();
				return false;
			}
		}
	}
	else if ( checkboxId == "doc_select_closed" && document.getElementById('allSelectedinAllPagesClosed').value == "true" ) {
		
			var hitCount = document.getElementById("totalresultscountClosed").value; 
			var deSelectedResultsString = document.getElementById("deselectedResultsClosed").value;
			var deSelectedResultsTokens = deSelectedResultsString.split(';'); 
			var selectedResultsCount = hitCount - (deSelectedResultsTokens.length);
			
			if ( selectedResultsCount > maxSelectCount ) {
				//if the number of results exceed the configured limit, alert the user
				result = confirm("You can export a maximum of "+ maxSelectCount+" items. Select OK to "
						+"proceed to print the first "+ maxSelectCount +" documents or Cancel if you do not want to continue.");
				if (result == true) {
					 resultsSelectionLimited = true;
				}
				else
				{
					clearSelectionClosed();
					return false;
				}
			}
		
	}
	else if ( noOfIds > maxSelectCount ) {
		result = confirm("You can export a maximum of "+ maxSelectCount+" items.Select OK to"
				+"proceed to print the first "+ maxSelectCount +" documents or Cancel if you do not want to continue.");
		if (result == true) {
			ids = "";
			for (i = 0; i < maxSelectCount; i++ ) {
				ids = ids + idTokens[i] + ';'; 
			}
		}else{
			if(checkboxId == "doc_select"){
				clearSelection();
			}else{
				clearSelectionClosed();
			}
			return false;
		}	
			
	}
	
	var parms = 'id='+ids;
	if (resultsSelectionLimited) { 
		/* send to the action bean a flag indicating that the user was forced
		 	select limited set of results */
		parms = parms+'&resultsSelectionLimited='+resultsSelectionLimited;
	}
	var desel;
	var allsel;
	if(checkboxId == "doc_select_closed"){
		desel=document.getElementById("deselectedResultsClosed").value;
		allsel=document.getElementById('allSelectedinAllPagesClosed').value;
		
	}else{
		desel=document.getElementById("deselectedResults").value;
		allsel=document.getElementById('allSelectedinAllPages').value;
		
	}	
	parms = parms+'&'+"deselectedResults"+'='+desel;
	parms = parms+'&'+"allSelectedinAllPages"+'='+allsel;
	
	if (ids && (content == 'S' || content == 'SC')) {		
		if (auid) {
			parms = parms+'&auid='+auid+'&content='+content;
		}		
		parms = parms+'&file=opportunities.csv';
		window.location=buildURL('/export/opportunity', null, parms, null, null);
	} else if (ids && content == 'A') {	
		
		parms = parms+'&file=awards.csv';
		window.location=buildURL('/export/award', null, parms, null, null);
	}
	return false;
}

// --------------------------------------
// Function used for comparing multiple docs
// --------------------------------------

/*
 * Gather the selections and take the user to a window showing the details
 * for all of the selections.
 */
function compareSelectedContent(content, checkboxId, auid)
{
	return compareSelectedContentById(content, checkboxId, auid);
}

/*
 * Gather the selections and take the user to a window showing the details
 * for all of the selections.
 */
function compareSelectedContentById(content, checkboxId, auid)
{
	// Get the list of selected items
	//var elements = document.getElementsByName(checkboxId);
	var ids;
	var idcount = 0;
	if (checkboxId != "doc_select_closed") {
		ids = document.getElementById('selectedResults').value;
	} else {
		ids = document.getElementById('selectedResultsClosed').value;
	}
	var elements = ids.split(';');
	idcount = ids.split(';').length - 1;
	// We can only compare two ids.
	if (idcount == 1){
		result = confirm("You can compare 2 items. Select OK to proceed to compare the first 2 items or Cancel if you do not want to continue.");
		if (result == true) {
			var elements = document.getElementsByName(checkboxId);
			ids = elements[0].value + ';' + elements[1].value;
			}
		else
		{
			if (checkboxId == "doc_select_closed") {
				clearSelectionClosed();
			}else{
				clearSelection();
			}	
			
			return false;
		}
	}
	else if (idcount > 0 && idcount != 2) {
		result = confirm("You can compare 2 items. Select OK to proceed to compare the first 2 items or Cancel if you do not want to continue.");
		if (result == true) {
			ids =  elements[0] + ';' + elements[1]; 
		}
		else
		{
			if (checkboxId == "doc_select_closed") {
				clearSelectionClosed();
			}else{
				clearSelection();
			}
			return false;
	    }
	} else if (	idcount == 0 ){
		alert("select 2 opportunities results to compare.");
		return false;
	}
	
	if (ids && content == 'S') {
		var parms = 'id='+ids;
		if (auid) {
			parms = parms+'&auid='+auid;
		}
		window.location = buildURL('/compare/opportunity', null, parms, null, null);
	} else {
		// There weren't any selected items.
		alert("select 2 opportunities results to compare.");
		return false;
	}
}

// --------------------------------------
// Function used for making a string containing all selected items
// --------------------------------------

/*
 * Gather the selections.
 */
function getAllSelectedItems(previousSelections)
{
	// Get the list of selected items
	var elements = document.getElementsByName('doc_select');
	var ids = previousSelections;
	if (elements && elements.length > 0) {
		// Append the items onto the id list.
		for(var i=0; i<elements.length; i++) {
			if (elements[i].checked) {
				if (ids && ids.length>0) {
					ids = ids+';'+elements[i].value;
				} else {
					ids = elements[i].value;
				}
			}
		}
	}
	ids = deduplicateList(ids, ';');
	
	return ids;
}

/*
 * Given a list and a delimiter for the list, remove any duplicate items in
 * the list.  Also remove any item called "undefined" from the list.
 */
function deduplicateList(ids, delim)
{
	var idList;
	var splitList = ids.split(delim);
	for(var i=0; i<splitList.length; i++) {
		if (idList) {
			if (idList.indexOf(splitList[i]) < 0 && !(splitList[i] == 'undefined')) {
				idList = idList+';'+splitList[i];
			}
		} else if (!(splitList[i] == 'undefined')) {
			idList = splitList[i];
		}
	}
	
	return idList;
}

// ----------------------------------------------------------------------
// Functions for handling clustering.
// ----------------------------------------------------------------------

var clusteringShowing = 3;
var clusteringDimensions;

/*
 * This funciton has to be called during rendering of the page.  It sets
 * the names of the clustering divs so that more can be shown as needed.
 */
function configureDimensionNames(dimensions) {
	clusteringDimensions = dimensions;
	showClustering();
}

/*
 * When the user clicks the "more" link, this function will be called to
 * cause more clustering categories to be shown.
 */
function showMoreClustering(i) {
	if (clusteringShowing == 3) {
		clusteringShowing = 10;
	} else {
		clusteringShowing = clusteringShowing*2;
	}
	showColumnClustering(i);
}

/*
 * When the user clicks the "less" link, this function will be called to
 * cause fewer clustering categories to be shown.
 */
function showLessClustering(i) {
	if (clusteringShowing == 10) {
		clusteringShowing = 3;
	} else {
		clusteringShowing = clusteringShowing/2;
	}
	showColumnClustering(i);
}

/*
 * Set the appropriate divs to be visible or not for each available
 * clustering dimension based on the number of items being shown.
 */
function showClustering() {
	// Iterate through the dimensions.
	for(var i=0; i<clusteringDimensions.length; i++) {
		// The dimension name to use ...
		var dimName = clusteringDimensions[i];

		// Flag used to indicate whether or not the more link should be
		// displayed.		
		var nomore = false;
		var noless = false;

		// Iterate through the categories and set them to visible or hidden.		
		for(var j=0; j<160; j++) {
			var clusteringItem = document.getElementById(dimName+j);
			if (clusteringItem && j < clusteringShowing) {
				clusteringItem.style.display="block";
			} else if (clusteringItem) {
				clusteringItem.style.display="none";
			} else if (j < clusteringShowing) {
				if (j < 3) {
					noless = true;
				}
				nomore = true;
				break;
			}
		}
		// Check to make sure there's at least one more category before
		// displaying the more link.
		if (nomore == false) {
			if (!document.getElementById(dimName+clusteringShowing)) {
				nomore = true;
			}
		}
		
		// Set the more link to visible or hidden depending on whether there
		// are more categories to be shown.
		if (nomore) {
			hideDiv(dimName+"More");
		} else {
			showDiv(dimName+"More");
		}
		// Set the less link to visible or hidden depending on whether we're
		// showing more than 3 or not.
		if (clusteringShowing > 3 && !noless) {
			showDiv(dimName+"Less");
		} else {
			hideDiv(dimName+"Less");
		}
		
		// If both more and less are showing, then also show the separator
		// between them, otherwise don't.
		if (nomore || clusteringShowing == 3 || noless) {
			hideDiv(dimName+"Sep");
		} else {
			showDiv(dimName+"Sep");
		}
		
		// Go on to the next dimension.
	}
}

/*
 * Set the appropriate div to be visible or not for a particular
 * clustering dimension based on the number of items being shown.
 */
function showColumnClustering(i) {
		var dimName = clusteringDimensions[i];
		// Flag used to indicate whether or not the more link should be
		// displayed.		
		var nomore = false;
		var noless = false;

		// Iterate through the categories and set them to visible or hidden.		
		for(var j=0; j<160; j++) {
			var clusteringItem = document.getElementById(dimName+j);
			if (clusteringItem && j < clusteringShowing) {
				clusteringItem.style.display="block";
			} else if (clusteringItem) {
				clusteringItem.style.display="none";
			} else if (j < clusteringShowing) {
				if (j < 3) {
					noless = true;
				}
				nomore = true;
				break;
			}
		}
		// Check to make sure there's at least one more category before
		// displaying the more link.
		if (nomore == false) {
			if (!document.getElementById(dimName+clusteringShowing)) {
				nomore = true;
			}
		}
		
		// Set the more link to visible or hidden depending on whether there
		// are more categories to be shown.
		if (nomore) {
			hideDiv(dimName+"More");
		} else {
			showDiv(dimName+"More");
		}
		// Set the less link to visible or hidden depending on whether we're
		// showing more than 3 or not.
		if (clusteringShowing > 3 && !noless) {
			showDiv(dimName+"Less");
		} else {
			hideDiv(dimName+"Less");
		}
		
		// If both more and less are showing, then also show the separator
		// between them, otherwise don't.
		if (nomore || clusteringShowing == 3 || noless) {
			hideDiv(dimName+"Sep");
		} else {
			showDiv(dimName+"Sep");
		}
}

// -------------------------------------------------------------------------
// Functions for handling AJAX request to get the reesearch rank.
// -------------------------------------------------------------------------

function getResearchRank(elementId,oppid,auid) {
	element = document.getElementById(elementId);
	element.innerHTML='<img src="/static/images/grant/rel_throbber.gif" width="100" height="9" alt="Calculating research rank" title="Calculating research rank">';
	processXML('/opportunity/researchrank?id=' + oppid + '&auid=' + auid,'showResearchRank(xmlhttp.responseText,\'' + elementId + '\')');
	return true;
}

function showResearchRank(htmltext,elementId) {
	if (htmltext){
		percentage = parseInt(htmltext);
		
		// Check error codes
		if (percentage == 91) {
			outputHTML = "user not found";
		} else if (percentage == 92) {
			outputHTML = "opportunity not found";
		} else if (percentage == 93) {
			outputHTML = "recommendation not found";
		}
		else
		{
			// Not an error
			neg = 100-percentage;
			if (percentage == 100){
				outputHTML = '<img src="/static/images/grant/rel_gr.gif" height="9" width="' + percentage + '" alt="' + percentage + '%"> ' + percentage + '%';
			} else {
				outputHTML = '<img src="/static/images/grant/rel_gr.gif" height="9" width="' + percentage + '" alt="' + percentage + '%"><img src="/static/images/grant/rel_rd.gif" height="9" width="' + neg + '" alt="' + neg + '%"> ' + percentage + '%';
			}
		}
	} else {
		outputHTML = 'not available';
	}
	element = document.getElementById(elementId);
	element.innerHTML=outputHTML;
}

// ----------------------------------------------------------------------------
// JS functions related to displaying the mouseover with the list of pis
// in awards results lists.
// ----------------------------------------------------------------------------

var piDisplayOverlayMouseState = false;
var piDisplayOverlayTimeout = false;

function showAwardInvestigatorsTimeout(grantId,elementId,w,h){
	piDisplayOverlayMouseState = true;
	elementOverlay = document.getElementById('overlay');
	elementInner = document.getElementById('overlayinner');
	document.getElementById('closeOverlay').style.display = 'none';
	
	elementInner.innerHTML = '<div class="get_investigator"><img src="/static/images/grant/rel_throbber.gif" width="100" height="9" alt="Retrieving investigators" title="Retrieving investigators"></div>';
	processXML('/award/getpilist?id=' + grantId,'setAwardInvestigators(xmlhttp.responseText)');
	
	w = parseInt(w);
	h = parseInt(h);
	elementOverlay.style.width = w + 'px';
	elementOverlay.style.height = h + 'px';
	
	element = document.getElementById(elementId);
	pos = findPos(element);
	elementOverlay.style.left = pos.x + 'px';
	elementOverlay.style.top = (pos.y+20) + 'px';
	
	elementOverlay.style.display = 'block';

}

function setAwardInvestigators(html) {
	element= document.getElementById('overlayinner');
	element.innerHTML = html;
	document.getElementById('overlaytitle').innerHTML='<h4>Investigators</h4>';
}

function showInvestigators(grantid,elementId,w,h) {
	setTimeout('showInvestigatorsTimeout(\''+grantid+'\',\''+elementId+'\','+w+','+h+')',250);
}

function setInvestigators(html) {
	element= document.getElementById('overlayinner');
	element.innerHTML = html;
	document.getElementById('overlaytitle').innerHTML='<h4>Investigators</h4>';
	toolTip();
	piDisplayOverlayMouseState = false;
	piDisplayOverlayTimeout = setTimeout('hideOverlayTimeout()',6000);
	return true;
}

function showInvestigatorsTimeout(grantId,elementId,w,h){
	piDisplayOverlayMouseState = true;
	elementOverlay = document.getElementById('overlay');
	elementInner = document.getElementById('overlayinner');
	document.getElementById('closeOverlay').style.display = 'none';
	
	elementInner.innerHTML = '<div class="get_investigator"><img src="/static/images/grant/rel_throbber.gif" width="100" height="9" alt="Retrieving investigators" title="Retrieving investigators"></div>';
	processXML('/award/getpilist?id=' + grantId,'setInvestigators(xmlhttp.responseText)');
	
	w = parseInt(w);
	h = parseInt(h);
	elementOverlay.style.width = w + 'px';
	elementOverlay.style.height = h + 'px';
	
	element = document.getElementById(elementId);
	pos = findPos(element);
	elementOverlay.style.left = pos.x + 'px';
	elementOverlay.style.top = (pos.y+20) + 'px';
	
	elementOverlay.style.display = 'block';
	
	elementOverlay.onmouseout = function() {
		piDisplayOverlayMouseState = false;
		piDisplayOverlayTimeout = setTimeout('hideOverlayTimeout()',6000);
	}
	
	elementOverlay.onmouseover = function() {
		piDisplayOverlayMouseState = true;
		clearTimeout(piDisplayOverlayTimeout);
	}

	piDisplayOverlayMouseState = false;
	piDisplayOverlayTimeout = setTimeout('hideOverlayTimeout()',6000);
}

function hideOverlayTimeout(){
	if (!piDisplayOverlayMouseState){
		hideOverlay();
	}
}

//----------------------------------------------------------------------
//Functions to add, display and delete the selected element 
//----------------------------------------------------------------------

var selectedElement = new Array();

/*
 * This function is called when Enter Key is pressed
 * after selecting the subject area from the drop-down.
 */

function addItemOnEnterKeyPress(event)
{
	if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)){
		addItem('subjectArea','displaySubjectArea','selectedSubjectArea','subject area');hideDiv('subjectarea_add');return false;
	}else return true;
}

/*
 * This function is called when one or more element is to be
 * added to the selectedElement array.
 * @param selectedElementID - ID of the select element
 * @param displayElementId - ID of the div element where the selected element is to be
 * 					displayed.
 * @param hiddenElementId - ID of the hidden field element where the selected element 
 * 					is to be set to be retrieved in action bean
 * @param msg 	- Tells what is been selected(e.g subject area)
 * 
 */

function addItem(selectedElementID, displayElementId, hiddenElementId, msg)
{   
	var id=document.getElementById(selectedElementID);    
	if(id.value == "SelectOne"){
		return;
	}else if(id.value == "All"){
    	addAll(id, msg);
    }else{
    	addSelected(id.value, msg);
    }
    displaySelected(displayElementId,hiddenElementId);
}

/*
 * This function is called when all the elements in select 
 * option is to be added to the selectedElement array.
 */
function addAll(id, msg){		
	
	var length = id.length;
	var selectedElementLength = selectedElement.length;
	var item;
	if(selectedElementLength == 0){
		for(var i=2;i<length;i++){
			item = id.options[i].value;
			selectedElement.push(item);
		}
	}else {
		alert("You have already selected that "+msg+".");
	}
}
/*
 * This function is called when a selected element is to be
 * added to the selectedElement array.
 */
function addSelected(value, msg){	
	var length = selectedElement.length;
	var flag = new Boolean("true");	
	if(length == 0){
		selectedElement.push(value);
		flag = false;
	}else {
		for(var i=0;i<length;i++){			
			if(selectedElement[i] == value){
				alert("You have already selected that "+msg+".");
				flag = false;
				return;
			}
		}
	}	
	if(flag){
		selectedElement.push(value);
	}
}

/*
 * This function is called to display the selectedElement 
 * in a particular div id
 */
function displaySelected(displayElementId, hiddenElementId){	
    var closebuttontag;
    var length = selectedElement.length;   
    var tmpSelectedElement; 
    document.getElementById(displayElementId).innerHTML = "";
    for(var i=0;i<length;i++){
    	if(selectedElement[i] != "null" && selectedElement[i]!= "undefined"){
    	tmpSelectedElement+=";"+selectedElement[i];
    	closebuttontag=
    		'<img src="/static/images/grant/icon_delete.gif" style="vertical-align:super" id="'+selectedElement[i]+'" onclick="deleteSelected(this.id,'+'\''+displayElementId+'\','+'\''+hiddenElementId+'\''+')" width="9" height="9" alt="Delete" onmouseover="this.src=\'/static/images/grant/icon_delete_mo.gif\'" onmouseout="this.src=\'/static/images/grant/icon_delete.gif\'">';
    	document.getElementById(displayElementId).innerHTML+=selectedElement[i]+closebuttontag+", ";
    	}
    }    
    document.getElementById(hiddenElementId).value = tmpSelectedElement;
}
/*
 * This function is called to delete a particular 
 * element
 */
function deleteSelected(deleteItemId, displayElementId, hiddenElementId)
{	
	removeSelected(deleteItemId, displayElementId, hiddenElementId);
    document.getElementById(deleteItemId).style.display="none";    
}
/*
 * This function is called to delete a particular element.
 */
function removeSelected(item, displayElementId, hiddenElementId){
	
	var newSelectedElement= new Array();
	var length = selectedElement.length;
	for(var i=0;i<length;i++){
		if(selectedElement[i] != item){
			newSelectedElement.push(selectedElement[i]);
		}
	}
	selectedElement = newSelectedElement;
	displaySelected(displayElementId, hiddenElementId);
}

function showSelectedSubjectArea(selectedSubjectArea, displayElementId, hiddenElementId){
	if(selectedSubjectArea.length != 0){		
		var tmpSelectedElement = selectedSubjectArea.split(";");
		selectedElement = new Array();
		for(var i= 1; i<tmpSelectedElement.length; i++){		
			selectedElement.push(tmpSelectedElement[i]);
		}
		displaySelected(displayElementId,hiddenElementId);		
	}
	return false;
}

/*
 * Build an URL to delete selected awarded grants.  An alert
 * message is displayed if no awarded grant is selected.
 * @param path The path to send the request to.
 * @param parm The parameter to use for the selected items.  The value for
 * the parameter is taken from the value of the selected items.
 * @param backpath The page to return to in the event of an error.
 * @param name The name of the items to look for.
 * @return true if there were items selected, false if there were not.
 */
function deleteAwardedGrants(path, parm, backpath, name)
{
	var url = path+"?";
	var count = 0;
	
	// Get the list of selected items
	var foundOne = false;
	var elements = document.getElementsByName(name);
	if (elements && elements.length > 0) {
		// Append the items onto the url.
		for(var i=0; i<elements.length; i++) {
			if (elements[i].checked) {
				url = url+"&"+parm+"="+elements[i].value;
				foundOne = true;
				count+=1;
			}
		}
		
		if (!foundOne) {
			// There weren't any selected items.
			alert("No awarded grants were selected.To delete awarded grants from your profile, select one or more awarded grants and click Delete.");
			
		}else if(count <= 1) {
			if(confirm('Are you sure you want to delete this awarded grant from your profile?')){
				window.location = url;
			}		
		}else if(count > 1){
			if(confirm('Are you sure you want to delete these awarded grants from your profile?')){
				window.location = url;
			}
		}
	}
	return false;
}

//----------------------------------------------------------------------------
//JS functions related to results selection
//----------------------------------------------------------------------------

/*
 * this function is used to retrieve the specified number
 * of results when the number of results per page is changed by the user
 */
function navigateResults(numberOfResults,eventType,limit,exclude,term){
	var formReference = "results_"+document.getElementById("sortcolumn").value;
	document.getElementById("resultsPerPage").value =numberOfResults ;
	document.getElementById("event").value =eventType ;
	document.getElementById("retainSortOrder").value =true;
	document.getElementById("navigation").value =true;
	document.getElementById('limtext').value=limit;
	document.getElementById('extext').value=exclude;
	document.getElementById('searchTerm').value=term;
	document.getElementById(formReference).appendChild(document.getElementById('resultsPerPage'));
	document.getElementById(formReference).appendChild(document.getElementById('event'));
	document.getElementById(formReference).appendChild(document.getElementById('retainSortOrder'));
	document.getElementById(formReference).appendChild(document.getElementById('navigation'));
	document.getElementById(formReference).appendChild(document.getElementById('limtext'));
	document.getElementById(formReference).appendChild(document.getElementById('extext'));
	document.getElementById(formReference).appendChild(document.getElementById('searchTerm'));
	document.getElementById(formReference).appendChild(document.getElementById('selectedResults'));
	document.getElementById(formReference).appendChild(document.getElementById('deselectedResults'));
	document.getElementById(formReference).appendChild(document.getElementById('allSelectedinAllPages'));
	if (document.getElementById('selectedResultsClosed') != null) {
		document.getElementById(formReference).appendChild(document.getElementById('selectedResultsClosed'));
	}
	if (document.getElementById('deselectedResultsClosed') != null) {
		document.getElementById(formReference).appendChild(document.getElementById('deselectedResultsClosed'));
	}
	if (document.getElementById('allSelectedinAllPagesClosed') != null) {
		document.getElementById(formReference).appendChild(document.getElementById('allSelectedinAllPagesClosed'));
	}
	document.getElementById(formReference).submit();
}


/*
 * this function is used to retrieve the next set of results when the
 * the user chooses to navigate to previous / next page
 */

function navigate(offsetValue,eventType,limit,exclude,term){	
	var formReference = "results_"+document.getElementById("sortcolumn").value;
	document.getElementById("event").value =eventType ;
	document.getElementById("offset").value =offsetValue ;
	document.getElementById("retainSortOrder").value =true;
	document.getElementById("navigation").value =true;
	document.getElementById('limtext').value=limit;
	document.getElementById('extext').value=exclude;
	document.getElementById('searchTerm').value=term;
	document.getElementById(formReference).appendChild(document.getElementById('offset'));
	document.getElementById(formReference).appendChild(document.getElementById('resultsPerPage'));
	document.getElementById(formReference).appendChild(document.getElementById('event'));
	document.getElementById(formReference).appendChild(document.getElementById('retainSortOrder'));
	document.getElementById(formReference).appendChild(document.getElementById('navigation'));
	document.getElementById(formReference).appendChild(document.getElementById('limtext'));
	document.getElementById(formReference).appendChild(document.getElementById('extext'));
	document.getElementById(formReference).appendChild(document.getElementById('searchTerm'));
	document.getElementById(formReference).appendChild(document.getElementById('selectedResults'));
	document.getElementById(formReference).appendChild(document.getElementById('deselectedResults'));
	document.getElementById(formReference).appendChild(document.getElementById('allSelectedinAllPages'));
	if (document.getElementById('selectedResultsClosed') != null) {
		document.getElementById(formReference).appendChild(document.getElementById('selectedResultsClosed'));
	}
	if (document.getElementById('deselectedResultsClosed') != null) {
		document.getElementById(formReference).appendChild(document.getElementById('deselectedResultsClosed'));
	}
	if (document.getElementById('allSelectedinAllPagesClosed') != null) {
		document.getElementById(formReference).appendChild(document.getElementById('allSelectedinAllPagesClosed'));
	}
	document.getElementById(formReference).submit();
}

/*
 * this function is used handles a mouse click on the check
 * box corresponding to a search result.
 */

function handleSelection(resultId){
	var isAllResults = document.getElementById("allSelectedinAllPages").value; 
	var isAllSelectedOnPage = document.getElementById("isAllSelectedOnPage").value;
	var elementId = "doc_select_" + resultId;
	var status = document.getElementById(elementId).checked;
	if(isAllResults == "false"){
		if(status){
			addResultIdTocheckedList(resultId);
		}else{
			removeResultIdFromcheckedList(resultId);	
		}
	}
	else{
		if(status){
			removeResultIdFromUncheckedList(resultId);
		}else{
			addResultIdToUncheckedList(resultId);	
		}
	}
	monitorSelectedResults();	
}

function submitForm(sortname,eventType,limit,exclude,term){
	var formReference = "results_"+sortname;
	if (limit) {
		document.getElementById('limtext').value=limit;
		document.getElementById(formReference).appendChild(document.getElementById('limtext'));
	}
	if (exclude) {
		document.getElementById('extext').value=exclude;
		document.getElementById(formReference).appendChild(document.getElementById('extext'));
	}
	if (eventType) {
		document.getElementById('event').value =eventType ;
		document.getElementById(formReference).appendChild(document.getElementById('event'));
	}
	if (term) {
		document.getElementById('searchTerm').value =term ;
		document.getElementById(formReference).appendChild(document.getElementById('searchTerm'));
	}
	document.getElementById(formReference).appendChild(document.getElementById('offset'));
	document.getElementById(formReference).appendChild(document.getElementById('resultsPerPage'));
	document.getElementById(formReference).appendChild(document.getElementById('selectedResults'));
	document.getElementById(formReference).appendChild(document.getElementById('deselectedResults'));
	document.getElementById(formReference).appendChild(document.getElementById('allSelectedinAllPages'));
	if (document.getElementById('selectedResultsClosed') != null) {
		document.getElementById(formReference).appendChild(document.getElementById('selectedResultsClosed'));
	}
	if (document.getElementById('deselectedResultsClosed') != null) {
		document.getElementById(formReference).appendChild(document.getElementById('deselectedResultsClosed'));
	}
	if (document.getElementById('allSelectedinAllPagesClosed') != null) {
		document.getElementById(formReference).appendChild(document.getElementById('allSelectedinAllPagesClosed'));
	}
	document.getElementById(formReference).submit();
}

function addResultIdTocheckedList(resultId){
	document.getElementById("selectedResults").value = document.getElementById("selectedResults").value + resultId + ";";
}

function removeResultIdFromcheckedList(resultId){
	var list = document.getElementById("selectedResults").value;
	resultId = resultId + ";";
	list = list.replace(resultId,"");
	document.getElementById("selectedResults").value = list;
}

/*
*count the number of selected results.
*/

function countSelected(){
	var searchResults = document.getElementById("results_on_page").getElementsByTagName("input");
	var count =0;
	for(var i=0; i<searchResults.length; i++){
		if(searchResults[i].type=="checkbox"){
			if(searchResults[i].checked==true){
			count++;
			}
		}
	}
	return count;
}

function addResultIdToUncheckedList(resultId){
	document.getElementById("deselectedResults").value = document.getElementById("deselectedResults").value + resultId + ";";
}

function removeResultIdFromUncheckedList(resultId){
	var list = document.getElementById("deselectedResults").value;
	resultId = resultId + ";";
	list = list.replace(resultId,"");
	document.getElementById("deselectedResults").value = list;
}

function getdeselectedResultsCount(){
	if(document.getElementById("deselectedResults")){
		var list = document.getElementById("deselectedResults").value;
		var deselectedTokens = list.split(';');
		return (deselectedTokens.length - 1);
	}else{
		return 0;
	}
}

function displayResultsSelectionMessage(){
	var deselectedCount = getdeselectedResultsCount();
	var totalSelectedResultsCount = document.getElementById("totalresultscount").value - deselectedCount;
	if ( deselectedCount == 0 ){
		document.getElementById("selectAllResultsMessage").innerHTML = 'All <b> '+document.getElementById("totalresultscount").value+' </b>results are selected. <a href=\"#\" class="results_link refine_more" onclick="clearSelection();return false;">Clear Selection.</a>'; 
	} else {
		document.getElementById("selectAllResultsMessage").innerHTML = '<b> '+totalSelectedResultsCount+'</b> of the total<b> '+document.getElementById("totalresultscount").value+' </b> results are selected. <a href=\"#\" class="results_link refine_more" onclick="clearSelection();return false;">Clear Selection.</a>'; 
	}
}
	
function selectAllResultsOnPage(){
	var isAllResults = document.getElementById("allSelectedinAllPages").value; 
	var isAllSelectedOnPage = document.getElementById("isAllSelectedOnPage").value;
	var searchResults = document.getElementById("results_on_page").getElementsByTagName("input");
	var selectAllResultsOnPageLink; 
	if(document.all){
		selectAllResultsOnPageLink = document.getElementById("selectAllResultsOnPageLink").innerText;
	} else{
		selectAllResultsOnPageLink = document.getElementById("selectAllResultsOnPageLink").textContent;
	}
	if(isAllResults == "false"){ 
	if(selectAllResultsOnPageLink =="Deselect All"){
		
			for(var i=0; i<searchResults.length; i++){
				if(searchResults[i].type=="checkbox"){
					searchResults[i].checked=false;
					var id = searchResults[i].value;
					removeResultIdFromcheckedList(id);
					}
			}			
		document.getElementById("isAllSelectedOnPage").value = false;
		var inhtml = "<img src='/static/images/grant/icon_sel_col_down.gif' rsrc='/static/images/grant/icon_sel_col_down_mo.gif' alt='Select All' width='9' height='9'>Select All";
		var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.gif' rsrc='/static/images/grant/icon_sel_col_up_mo.gif' alt='Select All' width='9' height='9'>Select All";
		document.getElementById("selectAllResultsOnPageLink").innerHTML = inhtml;
		document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlBottom;
		document.getElementById('selectAllResultsMessage').innerHTML="";
	}

	else if(selectAllResultsOnPageLink =="Select All"){
		
		for(var i=0; i<searchResults.length; i++){
			if(searchResults[i].type=="checkbox"){
				if(searchResults[i].checked != true){
				searchResults[i].checked=true;
				var id = searchResults[i].value;
				addResultIdTocheckedList(id);
				}
		}
		}
		var list = document.getElementById("selectedResults").value;
		document.getElementById("isAllSelectedOnPage").value = true;
		var inhtml = "<img src='/static/images/grant/icon_sel_col_down.gif' rsrc='/static/images/grant/icon_sel_col_down_mo.gif' alt='Deselect All' width='9' height='9'>Deselect All";
		var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.gif' rsrc='/static/images/grant/icon_sel_col_up_mo.gif' alt='Deselect All' width='9' height='9'>Deselect All";
		document.getElementById("selectAllResultsOnPageLink").innerHTML = inhtml;
		document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlBottom;
			if( (countSelected() == document.getElementById("resultsPerPage").value) &&(countSelected() < document.getElementById("totalresultscount").value) ){			
			document.getElementById("selectAllResultsMessage").innerHTML='All<b> '+countSelected()+'</b> results on this page are selected. <a href=\"#\" class="results_link refine_more" onclick=\"selectAll();return false;\">Select all <b>'+document.getElementById("totalresultscount").value+'</b> results.</a>';
			}else if (countSelected() == document.getElementById("totalresultscount").value){
				document.getElementById("selectAllResultsMessage").innerHTML='All <b> '+document.getElementById("totalresultscount").value+' </b>results are selected. <a href=\"#\" class="results_link refine_more" onclick="clearSelection();return false;">Clear Selection.</a>';
		}else{
				document.getElementById("selectAllResultsMessage").innerHTML="";
			}
		}
	}else{ //user has selected all results in all pages
		if(selectAllResultsOnPageLink =="Deselect All"){

			for(var i=0; i<searchResults.length; i++){
				if(searchResults[i].type=="checkbox"){
					searchResults[i].checked=false;
					var id = searchResults[i].value;
					addResultIdToUncheckedList(id);
				}
			}			
			document.getElementById("isAllSelectedOnPage").value = false;
			var inhtml = "<img src='/static/images/grant/icon_sel_col_down.gif' rsrc='/static/images/grant/icon_sel_col_down_mo.gif' alt='Select All' width='9' height='9'>Select All";
			var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.gif' rsrc='/static/images/grant/icon_sel_col_up_mo.gif' alt='Select All' width='9' height='9'>Select All";
			document.getElementById("selectAllResultsOnPageLink").innerHTML = inhtml;
			document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlBottom;
		}
		else if(selectAllResultsOnPageLink =="Select All"){

			for(var i=0; i<searchResults.length; i++){
				if(searchResults[i].type=="checkbox"){
					if(searchResults[i].checked != true){
						searchResults[i].checked=true;
						var id = searchResults[i].value;
						removeResultIdFromUncheckedList(id);
					}
				}
			}
			var list = document.getElementById("selectedResults").value;
			document.getElementById("isAllSelectedOnPage").value = true;
			var inhtml = "<img src='/static/images/grant/icon_sel_col_down.gif' rsrc='/static/images/grant/icon_sel_col_down_mo.gif' alt='Deselect All' width='9' height='9'>Deselect All";
			var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.gif' rsrc='/static/images/grant/icon_sel_col_up_mo.gif' alt='Deselect All' width='9' height='9'>Deselect All";
			document.getElementById("selectAllResultsOnPageLink").innerHTML = inhtml;
			document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlBottom;
			if ((countSelected() == document.getElementById("totalresultscount").value)){
			document.getElementById("selectAllResultsMessage").innerHTML='All <b> '+document.getElementById("totalresultscount").value+' </b>results are selected. <a href=\"#\" class="results_link refine_more" onclick="clearSelection();return false;">Clear Selection.</a>';
		}
	}
		displayResultsSelectionMessage();
	}
}

function monitorSelectedResults(){
	if (document.getElementById("allSelectedinAllPages").value == "true"){
		if( countSelected() < document.getElementById("resultsPerPage").value  ) {
			document.getElementById("isAllSelectedOnPage").value = false;
			var inhtml = "<img src='/static/images/grant/icon_sel_col_down.gif' rsrc='/static/images/grant/icon_sel_col_down_mo.gif' alt='Select All' width='9' height='9'>Select All";
			var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.gif' rsrc='/static/images/grant/icon_sel_col_up_mo.gif' alt='Select All' width='9' height='9'>Select All";
			document.getElementById("selectAllResultsOnPageLink").innerHTML= inhtml;
			document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlBottom;
		}else if( countSelected() == document.getElementById("resultsPerPage").value  ) {
			document.getElementById("isAllSelectedOnPage").value = true;
			var inhtml = "<img src='/static/images/grant/icon_sel_col_down_mo.gif' alt='Deselect All' width='9' height='9'>Deselect All";
			var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up_mo.gif' alt='Deselect All' width='9' height='9'>Deselect All";
			document.getElementById("selectAllResultsOnPageLink").innerHTML= inhtml;
			document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlBottom;
	}
		displayResultsSelectionMessage();
	} else {
	if(	(countSelected() == document.getElementById("resultsPerPage").value) && (countSelected() < document.getElementById("totalresultscount").value)){
		document.getElementById("isAllSelectedOnPage").value = true;
		var inhtml = "<img src='/static/images/grant/icon_sel_col_down_mo.gif' alt='Deselect All' width='9' height='9'>Deselect All";
		var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up_mo.gif' alt='Deselect All' width='9' height='9'>Deselect All";
		document.getElementById("selectAllResultsOnPageLink").innerHTML= inhtml;
		document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlBottom;		
		document.getElementById("selectAllResultsMessage").innerHTML='All<b> '+countSelected()+'</b> results on this page are selected. <a href=\"#\" class="results_link refine_more" onclick=\"selectAll();return false;\">Select all <b>'+document.getElementById("totalresultscount").value+'</b> results.</a>';
	}
		else if( (countSelected() == document.getElementById("resultsPerPage").value) && (countSelected() == document.getElementById("totalresultscount").value) ) {
		document.getElementById("isAllSelectedOnPage").value = true;
		var inhtml = "<img src='/static/images/grant/icon_sel_col_down_mo.gif' alt='Deselect All' width='9' height='9'>Deselect All";
		var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up_mo.gif' alt='Deselect All' width='9' height='9'>Deselect All";
		document.getElementById("selectAllResultsOnPageLink").innerHTML= inhtml;
		document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlBottom;
		document.getElementById('selectAllResultsMessage').innerHTML='All <b> '+document.getElementById("totalresultscount").value+' </b>results are selected. <a href=\"#\" class="results_link refine_more" onclick="clearSelection();return false;">Clear Selection.</a>';
	}
	else{
		document.getElementById("isAllSelectedOnPage").value = false;
		var inhtml = "<img src='/static/images/grant/icon_sel_col_down.gif' alt='Select All' width='9' height='9'>Select All";
		var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up_mo.gif' alt='Deselect All' width='9' height='9'>Select All";
			document.getElementById('selectAllResultsOnPageLink').innerHTML = inhtml;
			document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlBottom;
			if(document.getElementById('selectAllResultsMessage')){
				document.getElementById('selectAllResultsMessage').innerHTML="";
			}
	}
}
}

/*
 * this function clears the selection of all the search results in all pages
 */
function clearSelection(){
	var searchResults = document.getElementById("results_on_page").getElementsByTagName("input");
	for(var i=0; i<searchResults.length; i++){
						if(searchResults[i].type=="checkbox"){
							searchResults[i].checked=false;
							}
	}
	document.getElementById("selectedResults").value ="";
	document.getElementById("deselectedResults").value ="";
	var inhtmlup = "<img src='/static/images/grant/icon_sel_col_up_mo.gif'  alt='Select All' width='9' height='9'>Select All";
	var inhtmldown = "<img src='/static/images/grant/icon_sel_col_down_mo.gif'  alt='Select All' width='9' height='9'>Select All";
	document.getElementById("selectAllResultsOnPageLink").innerHTML = inhtmldown;
	document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlup;
		if(document.getElementById('selectAllResultsMessage')){
			document.getElementById('selectAllResultsMessage').innerHTML="";
		}
	document.getElementById('allSelectedinAllPages').value = false;
}

function selectAll(){
	var searchResults = document.getElementById("results_on_page").getElementsByTagName("input");
	for(var i=0; i<searchResults.length; i++){
		if(searchResults[i].type=="checkbox"){
			searchResults[i].checked=true;
		}
	}
	document.getElementById("deselectedResults").value ="";
	document.getElementById('allSelectedinAllPages').value = true;
	if(document.getElementById('selectAllResultsMessage')){
		document.getElementById('selectAllResultsMessage').innerHTML ='All <b> '+document.getElementById("totalresultscount").value+' </b>results are selected. <a href=\"#\" class="results_link refine_more" onclick="clearSelection();return false;">Clear Selection.</a>';
	}
}
//----------------------------------------------------------------------------
//JS functions related to search field description
//----------------------------------------------------------------------------

var LabeltipOver = false;
var version = navigator.appVersion; // IE Version
var iev;
if(version.indexOf("MSIE")!= -1)
{
	version = version.substr(version.indexOf("MSIE"),version.length);
	iev = parseInt(version.split(";")[0].split(" ")[1]);
}

var iframeObj;

function showLabeltipTimeout(object, labeltipId) {
	var objectId = object.getAttribute('id');
	LabeltipOver = true;
	setTimeout('showLabeltip(\'' + objectId + '\',\'' + labeltipId + '\')', 250);
}

function showLabeltip(objectId, labeltipId) {
	if (LabeltipOver) {
		var labeltipElement = document.getElementById(labeltipId);
		labeltipElement.style.display = "block";
		
		var objectElement = document.getElementById(objectId);
		var text = objectElement.getAttribute('labeltip');
		labeltipElement.innerHTML = text;
		
		var pos = findPos(objectElement);
		labeltipElement.style.left = pos.x + 'px';
		labeltipElement.style.top = (pos.y + 20) + 'px';
		
		iframeObj = window.document.getElementById("iframetooltip");
			
		if(iframeObj && iev < 7){
			iframeObj.style.display = "block";
			iframeObj.style.top = labeltipElement.style.top;
			iframeObj.style.left = labeltipElement.style.left;
			iframeObj.style.width = labeltipElement.offsetWidth + "px";
			iframeObj.style.height = labeltipElement.offsetHeight + "px";
		}
	}
}


//----------------------------------------------------------------------
//Functions to change the sort image on mouse over and mouse out
//----------------------------------------------------------------------

function changeSortImageOnOver(sortValue, sortName){
	var asc= sortValue.concat("_a");
	var des= sortValue.concat("_d");	
	var id= "sort_"+sortValue;	
	if(sortName == asc){
		document.getElementById(id).src = '/static/images/grant/sort_up_mo.gif';
	}else if (sortName == des){
		document.getElementById(id).src = '/static/images/grant/sort_down_mo.gif';
	}
}

function changeSortImageOnOut(sortValue, sortName){
	var asc= sortValue.concat("_a");
	var des= sortValue.concat("_d");	
	var id= "sort_"+sortValue;	
	if(sortName == asc){
		document.getElementById(id).src = '/static/images/grant/sort_up.gif';
	}else if (sortName == des){
		document.getElementById(id).src = '/static/images/grant/sort_down.gif';
	}
}

//----------------------------------------------------------------------
//Functions to closed opportunities
//----------------------------------------------------------------------

/*
 * this function is used handles a mouse click on the check
 * box corresponding to a search result.
 */

function handleSelectionClosed(resultId){
	var isAllResults = document.getElementById("allSelectedinAllPagesClosed").value; 
	var elementId = "doc_select_closed_" + resultId;
	var status = document.getElementById(elementId).checked;
	if(isAllResults == "false"){
		if(status){
			addResultIdTocheckedListClosed(resultId);
		}else{
			removeResultIdFromcheckedListClosed(resultId);	
		}
	}
	else{
		if(status){
			removeResultIdFromUncheckedListClosed(resultId);
		}else{
			addResultIdToUncheckedListClosed(resultId);	
		}
	}
	monitorSelectedResultsClosed();	
}

function addResultIdTocheckedListClosed(resultId){
	document.getElementById("selectedResultsClosed").value = document.getElementById("selectedResultsClosed").value + resultId + ";";
}

function removeResultIdFromcheckedListClosed(resultId){
	var list = document.getElementById("selectedResultsClosed").value;
	resultId = resultId + ";";
	list = list.replace(resultId,"");
	document.getElementById("selectedResultsClosed").value = list;
}

/*
*count the number of selected results.
*/

function countSelectedClosed(){
	var searchResults = document.getElementById("results_on_page_closed").getElementsByTagName("input");
	var count =0;
	for(var i=0; i<searchResults.length; i++){
		if(searchResults[i].type=="checkbox"){
			if(searchResults[i].checked==true){
			count++;
			}
		}
	}
	return count;
}

function addResultIdToUncheckedListClosed(resultId){
	document.getElementById("deselectedResultsClosed").value = document.getElementById("deselectedResultsClosed").value + resultId + ";";
}

function removeResultIdFromUncheckedListClosed(resultId){
	var list = document.getElementById("deselectedResultsClosed").value;
	resultId = resultId + ";";
	list = list.replace(resultId,"");
	document.getElementById("deselectedResultsClosed").value = list;
}


function selectAllResultsOnPageClosed(){
	
	var searchResults = document.getElementById("results_on_page_closed").getElementsByTagName("input");
	var selectAllResultsOnPageLinkClosed; 
	if(document.all){
		selectAllResultsOnPageLinkClosed = document.getElementById("selectAllResultsOnPageLinkClosed").innerText;
	} else{
		selectAllResultsOnPageLinkClosed = document.getElementById("selectAllResultsOnPageLinkClosed").textContent;
	}

	if(selectAllResultsOnPageLinkClosed =="Deselect All"){
		
			for(var i=0; i<searchResults.length; i++){
				if(searchResults[i].type=="checkbox"){
					searchResults[i].checked=false;
					var id = searchResults[i].value;
					removeResultIdFromcheckedListClosed(id);
					}
			}			
		document.getElementById("isAllSelectedOnPageClosed").value = false;
		var inhtml = "<img src='/static/images/grant/icon_sel_col_down.gif' rsrc='/static/images/grant/icon_sel_col_down_mo.gif' alt='Select All' width='9' height='9'>Select All";
		var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.gif' rsrc='/static/images/grant/icon_sel_col_up_mo.gif' alt='Select All' width='9' height='9'>Select All";
		document.getElementById("selectAllResultsOnPageLinkClosed").innerHTML = inhtml;
		document.getElementById("selectAllResultsOnPageLinkAtBottomClosed").innerHTML = inhtmlBottom;
		document.getElementById('selectAllResultsMessageClosed').innerHTML="";
	}

	else if(selectAllResultsOnPageLinkClosed =="Select All"){
		
		for(var i=0; i<searchResults.length; i++){
			if(searchResults[i].type=="checkbox"){
				searchResults[i].checked=true;
				var id = searchResults[i].value;
				addResultIdTocheckedListClosed(id);
				}
		}
		var list = document.getElementById("selectedResultsClosed").value;
		document.getElementById("isAllSelectedOnPageClosed").value = true;
		var inhtml = "<img src='/static/images/grant/icon_sel_col_down.gif' rsrc='/static/images/grant/icon_sel_col_down_mo.gif' alt='Deselect All' width='9' height='9'>Deselect All";
		var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.gif' rsrc='/static/images/grant/icon_sel_col_up_mo.gif' alt='Deselect All' width='9' height='9'>Deselect All";
		document.getElementById("selectAllResultsOnPageLinkClosed").innerHTML = inhtml;
		document.getElementById("selectAllResultsOnPageLinkAtBottomClosed").innerHTML = inhtmlBottom;
		if(countSelectedClosed() == document.getElementById("resultsPerPage").value){
			document.getElementById("selectAllResultsMessageClosed").innerHTML='All<b> '+countSelectedClosed()+'</b> results on this page are selected. <a href=\"#\" onclick=\"selectAllClosed();return false;\">Select all <b>'+document.getElementById("totalresultscountClosed").value+'</b> results.</a>';
		}else{
			document.getElementById("selectAllResultsMessageClosed").innerHTML="All<b> "+countSelectedClosed()+"</b> results are selected.";
		}
	}
}

function monitorSelectedResultsClosed(){
	if (document.getElementById("allSelectedinAllPagesClosed").value == "true"){
	return;
	}
	if(countSelectedClosed() == document.getElementById("resultsPerPage").value){
		document.getElementById("isAllSelectedOnPageClosed").value = true;
		var inhtml = "<img src='/static/images/grant/icon_sel_col_down_mo.gif' alt='Deselect All' width='9' height='9'>Deselect All";
		var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up_mo.gif' alt='Deselect All' width='9' height='9'>Deselect All";
		document.getElementById("selectAllResultsOnPageLinkClosed").innerHTML= inhtml;
		document.getElementById("selectAllResultsOnPageLinkAtBottomClosed").innerHTML = inhtmlBottom;
		document.getElementById('selectAllResultsMessageClosed').innerHTML="All<b> "+countSelectedClosed()+"</b> results on this page are selected. <a href=\"#\" onclick=\"selectAllClosed();return false;\">Select all <b>"+document.getElementById("totalresultscountClosed").value+"</b> results.</a>";
	}
	else{
		document.getElementById("isAllSelectedOnPageClosed").value = false;
		var inhtml = "<img src='/static/images/grant/icon_sel_col_down.gif' alt='Select All' width='9' height='9'>Select All";
		var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up_mo.gif' alt='Deselect All' width='9' height='9'>Select All";
			document.getElementById('selectAllResultsOnPageLinkClosed').innerHTML = inhtml;
			document.getElementById("selectAllResultsOnPageLinkAtBottomClosed").innerHTML = inhtmlBottom;
			if(document.getElementById('selectAllResultsMessageClosed')){
				document.getElementById('selectAllResultsMessageClosed').innerHTML="";
			}
	}
}

/*
 * this function clears the selection of all the search results in all pages
 */
function clearSelectionClosed(){
	var searchResults = document.getElementById("results_on_page_closed").getElementsByTagName("input");
	for(var i=0; i<searchResults.length; i++){
						if(searchResults[i].type=="checkbox"){
							searchResults[i].checked=false;
							}
	}
	document.getElementById("selectedResultsClosed").value ="";
	document.getElementById("deselectedResultsClosed").value ="";
	var inhtml = "<img src='/static/images/grant/icon_sel_col_up_mo.gif'  alt='Select All' width='9' height='9'>Select All";
	document.getElementById("selectAllResultsOnPageLinkClosed").innerHTML = inhtml;
	document.getElementById("selectAllResultsOnPageLinkAtBottomClosed").innerHTML = inhtml;
		if(document.getElementById('selectAllResultsMessageClosed')){
			document.getElementById('selectAllResultsMessageClosed').innerHTML="";
		}
	document.getElementById('allSelectedinAllPagesClosed').value = false;
}

function selectAllClosed(){
	var searchResults = document.getElementById("results_on_page_closed").getElementsByTagName("input");
	for(var i=0; i<searchResults.length; i++){
		if(searchResults[i].type=="checkbox"){
			searchResults[i].checked=true;
		}
	}
	document.getElementById("deselectedResultsClosed").value ="";
	document.getElementById('allSelectedinAllPagesClosed').value = true;
	if(document.getElementById('selectAllResultsMessageClosed')){
		document.getElementById('selectAllResultsMessageClosed').innerHTML ="All <b> "+document.getElementById("totalresultscountClosed").value+" </b>results are selected. <a href=\"#\" class=\"results_link refine_more\" onclick='clearSelectionClosed();return false;'>Clear Selection.</a>";
	}
}

function changeSorting(sOrder, obj, name) {	
	if (sOrder) {
		if (sOrder == name + '_a ') {
			obj.className = 'sort_down';

		} else if (sOrder == name + '_d') {
			obj.className = 'sort_up';

		} else if (sOrder != name + '_a') {			
			obj.className = 'res_col_sort_mo';
		} else if (sOrder != name + '_d') {
			obj.className = 'res_col_sort_mo';
		} 
	} else {
		obj.className = 'res_col_sort_mo';
	}
}

function getRecommendationsTitle(title,itemId,id) {	
	
	var size = readCookie('goTextSize');	
	
	if(size == null) {
		size = '0.7em';	
	}
	var obj = window.document.getElementById(id);	
	var maxTitleLength;
	var decimal;
	
	if ((screen.width > 1024) && (screen.height > 768) && size == '0.7em') {
		decimal=.045;
		maxTitleLength= document.body.clientWidth*decimal;
		if(title.length > maxTitleLength){
			title = title.substring(0, maxTitleLength) + "...";
		}
	} else if ((screen.width > 1024) && (screen.height > 768) && size == '0.77em') {
		decimal=0.038;
		maxTitleLength= document.body.clientWidth*decimal;
		if(title.length > maxTitleLength){
			title = title.substring(0, maxTitleLength) + "...";
		}
	} else if ((screen.width > 1024) && (screen.height > 768) && size == '0.83em') {
		decimal=0.0355;
		maxTitleLength= document.body.clientWidth*decimal;
		if(title.length > maxTitleLength){
			title = title.substring(0, maxTitleLength) + "...";
		}
	} else if ((screen.width <= 1024) && (screen.height <= 768)	&& size == '0.7em') {		
		decimal=0.055;
		maxTitleLength= document.body.clientWidth*decimal;
		if(title.length > maxTitleLength){
			title = title.substring(0, maxTitleLength) + "...";
		}
	} else if ((screen.width <= 1024) && (screen.height <= 768)	&& size == '0.77em') {
		decimal=0.045;
		maxTitleLength= document.body.clientWidth*decimal;
		if(title.length > maxTitleLength){
			title = title.substring(0, maxTitleLength) + "...";
		}
	} else if ((screen.width <= 1024) && (screen.height <= 768)	&& size == '0.83em') {
		decimal=0.04;
		maxTitleLength= document.body.clientWidth*decimal;
		if(title.length > maxTitleLength){
			title = title.substring(0, maxTitleLength) + "...";
		}
	}
		
	if(obj)
	{			
		curtitle += "<a href='/opportunity/"+ itemId +"' style='text-decoration:none;color:#333399;'>" + title + "</a>";			
	}else {		
		document.write(title);
	}
}

function textSize_RecTitle(){	
	
	curtitle="";	
	
	for(var j=0;j<textSize.length;j++) {
		
		getRecommendationsTitle(textSize[j],itemIden[j],'showText');
	}	
	
	document.getElementById('showText').innerHTML = curtitle;
	hideDiv('defaultText');
	return false;
}
function storeTitle(title,itemId) {	
	textSize[i] = title;
	itemIden[i] = itemId;	
	i++;
}


function loginOnEnterKeyPress(e) {
	 var evt = (e) ? e : window.event;
     var key = (evt.keyCode) ? evt.keyCode : evt.which;
     
     if(key != null) {
         key = parseInt(key, 10);        
         if(key==13){document.getElementById('association').click(); return false;}
     }   
     return true;     
}

function enable_QuickSearch(obj)
{
	var qsEmptyText = '  Quick Search';
	if (obj.value == qsEmptyText){
		obj.value='';
		document.getElementById('qssubmit').disabled=false
	};
	obj.className='input input_sel';return false
}

function postHitTerm(eid,hitTerms)
{
	hittermpostform=document.getElementById('hitTermPostForm');	
	hittermpostform.elements["hitTerms"].value=hitTerms;	
	hittermpostform.action="/opportunity?id="+eid;
	hittermpostform.submit();	
}

function submitRecScivalPage(event)
{ 
	if(event.keyCode == 13){
		recscivalform = document.getElementById('recommendScival');
		recscivalform.submit();
	}
}