//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(
					'#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,.details_navigation',
			'10px', true);
	DD_roundies.addRule('h3#all_corners,.browse_header', '10px', true);
	DD_roundies.addRule('h1#all_corners', '10px', true);
	
	DD_roundies.addRule('ul#ser a', '10px 10px 0 0', true);
	
	DD_roundies.addRule('#selected_profiles_action,#related_window_bottom_bar,#bulk_page_container,#limit_end',
			'0 0 10px 10px', true);
	DD_roundies
			.addRule(
					'h3,#homepage_box,#homepage_box_award,#homepage_box_rec,.page_title_head,#bulk_page_title',
					'10px 10px 0 0', true);
	

}
// this function handles all functions that need to be loaded "onLoad"
function init(domain) {

	IconOver();
	inputHelp();
	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;
	}
	selectItemsOnload();
}


function navigatorShrink(){    
    o = document.getElementById('queryshrink');
    var bool;
     var size = readCookie('goTextSize');

        if (size == null) {

              size = '0.77em';

        }
    
    if ((screen.width > 1024) && (screen.height > 768) && size == '0.7em') {

          if(!o){
                return false;
          }           
          if(o.offsetWidth > 1150)
                bool=true;
          
          while(o.offsetWidth > 1150){
          
                o.innerHTML = o.innerHTML.substring(0,o.innerHTML.length-1);
          }
          if(bool)
                o.innerHTML  += '...';

} else if ((screen.width > 1024) && (screen.height > 768) && size == '0.77em') {

      if(!o){
                return false;
          }           
          if(o.offsetWidth > 1000)
                bool=true;
          
          while(o.offsetWidth > 1000){
          
                o.innerHTML = o.innerHTML.substring(0,o.innerHTML.length-1);
          }
          if(bool)
                o.innerHTML  += '...';

} else if ((screen.width > 1024) && (screen.height > 768) && size == '0.83em') {

      if(!o){
                return false;
          }           
          if(o.offsetWidth > 950)
                bool=true;
          
          while(o.offsetWidth > 950){
          
                o.innerHTML = o.innerHTML.substring(0,o.innerHTML.length-1);
          }
          if(bool)
                o.innerHTML  += '...';

} else if ((screen.width <= 1024) && (screen.height <= 768) && size == '0.7em') {

      if(!o){
                return false;
          }           
          if(o.offsetWidth > 850)
                bool=true;
          
          while(o.offsetWidth > 850){
          
                o.innerHTML = o.innerHTML.substring(0,o.innerHTML.length-1);
          }
          if(bool)
                o.innerHTML  += '...';

} else if ((screen.width <= 1024) && (screen.height <= 768) && size == '0.77em') {

      if(!o){
                return false;
          }           
          if(o.offsetWidth > 750)
                bool=true;
          
          while(o.offsetWidth > 750){
          
                o.innerHTML = o.innerHTML.substring(0,o.innerHTML.length-1);
          }
          if(bool)
                o.innerHTML  += '...';

} else if ((screen.width <= 1024) && (screen.height <= 768) && size == '0.83em') {

      if(!o){
                return false;
          }           
          if(o.offsetWidth > 750)
                bool=true;
          
          while(o.offsetWidth > 750){
          
                o.innerHTML = o.innerHTML.substring(0,o.innerHTML.length-1);
          }
          if(bool)
                o.innerHTML  += '...';

}

return false;
}



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 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) {
	//Variable to store the record tye (award/oppurtunity)
	var recordType;

	if(divid=='award'){
			recordType="award";
		}else{
			recordType="opportunity";
	}
	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 must select at least one "+recordType+" to email.");
			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 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
// --------------------------------------

function buildSaveSearchFromHistory(){
	buildSaveSearch('','', '', '', '');
}

/*
 * Gather the data from the page to build the request to save a search.
 */
function buildSaveSearch(content, searchtext, limtext, extext, hits,searchURL,editURL)

{
	
	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,searchURL,editURL);
}

/*
 * Make call to save the search.
 */
var totalHitSearch;
function saveSearch(title, content, searchtext, limtext, extext, hits, alert,
		frequency, email, format, searchURL, editURL) {
	totalHitSearch = hits;
	// Build the parameters string
	var parms;
	var searchHistoryId = document.getElementById('history_id_save').value;
	if(searchHistoryId != null && searchHistoryId.length > 0){
		parms = 'searchHistoryId=' + searchHistoryId +'&title=' + encode_utf8(title)
	}else{
	parms = 'title=' + encode_utf8(title) + '&content=' + content
			+ '&searchtext=' + encode_utf8(searchtext) + '&limtext='
			+ encode_utf8(limtext) + '&extext=' + encode_utf8(extext)
			+ '&hits=' + hits + '&searchURL=' + encode_utf8(searchURL) 
			+ '&editURL=' + encode_utf8(editURL);
	}
	if (alert) {
		// If we're alerting on this, add that data to the string.
		parms = parms + '&frequency=' + frequency + '&email='
				+ encode_utf8(email) + '&format=' + format;
	}
	jQuery.ajax({
		 type: "POST",
		   url: "/my/search/save",
		   data: parms,
		   success: doneSavingSearch
		});
}

function showSaveOverlayFromHistory(historyId,saveName){
	document.getElementById('history_id_save').value = historyId ;
	showOverlayById('save_search',450,1,true);
	var docTitle = saveName ;
	if (docTitle && docTitle.length > 30) {
		docTitle = docTitle.substring(0,30)+'&#133;';
	}
	document.getElementById('save_name').value = 'SciVal Funding results for ' + saveName ;
	document.getElementById('save_name_header').innerHTML = docTitle ;
}

/*
 * Method that gets called after a search has been saved.
 */
function doneSavingSearch(responseText) {
	
	var statusText = jQuery(responseText).find("status").text();
	if (statusText == "error") {
		var statusMsg = jQuery(responseText).find("message").text();
		alert('Unable to save search: ' + statusMsg  );
	} 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;
	var frequency = document.getElementById('search_frequency_' + id).value;
	var email = document.getElementById('search_email_' + id).value;
	var format;
	if (document.getElementById('search_format_html_' + id).checked) {
		format = "H";
	} else {
		format = "T";
	}
	editSearch(id, title,frequency,email,format);
}

/*
 * Make call to Edit the Saved Search.
 */
function editSearch(id, title,frequency,email,format) {
	// Build the parameters string
	var parms;
	parms = 'id=' + id + '&title=' + title+ '&frequency=' + frequency + '&email='
			+ encode_utf8(email) + '&format=' + format;
	
	jQuery.ajax({
		 type: "POST",
		   url: "/my/search/edit",
		   data: parms,
		   success: doneEditingSavedSearch
		});
	
}
/*
 * Method that gets called after Editing a Saved Search.
 */
function doneEditingSavedSearch(responseText) {
	var statusText = jQuery(responseText).find("status").text();
	if (statusText == "error") {
		var statusMsg = jQuery(responseText).find("message").text();
		alert('Unable to set alert: ' + statusMsg);
	} 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(searchId,alertId) {
	var frequency = document.getElementById('alert_frequency_' + searchId).value;
	var email = document.getElementById('alert_email_' + searchId).value;
	var format;
	if (document.getElementById('alert_format_html_' + searchId).checked) {
		format = "H";
	} else {
		format = "T";
	}

	setAlert(searchId,alertId,frequency, email, format);
}

/*
 * Make call to set the alert.
 */
function setAlert(searchId, alertId, frequency, email, format) {
	// Build the parameters string
	var parms;
	var reqURL;
	parms = 'id=' + searchId + '&frequency=' + frequency + '&email='
			+ encode_utf8(email) + '&format=' + format;

	if(searchId =='rec'){
		if(frequency == 'N'){
			reqURL = '/my/recommendations/alert/delete';
		}else{
			reqURL = '/my/recommendations/alert/save';
		}
	}else{
		if(frequency == 'N'){
			reqURL = '/my/alert/delete';
			parms = 'id=' + alertId;
		}else{
			reqURL = '/my/alert/save';
		}
	}
	jQuery.ajax({
		 type: "POST",
		   url: reqURL,
		   data: parms,
		   success: doneSettingAlert
		});
	
}



/*
 * Method that gets called after an alert has been set.
 */
function doneSettingAlert(responseText) {
	var statusText = jQuery(responseText).find("status").text();
	if (statusText == "error") {
		var statusMsg = jQuery(responseText).find("message").text();
		alert('Unable to set alert: ' + statusMsg  );
	} 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;

	jQuery.ajax({
		 type: "POST",
		   url: '/my/content/alert/save',
		   data: parms,
		   success: doneSettingContentAlert
		});
}

/*
 * Method that gets called after an alert has been set.
 */
function doneSettingContentAlert(responseText) {
	var statusText = jQuery(responseText).find("status").text();
	if (statusText == "error") {
		var statusMsg = jQuery(responseText).find("message").text();
		alert('Unable to set alert: ' + statusMsg);
	} 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;
	}

	jQuery.ajax({
		 type: "POST",
		   url: '/my/document/save',
		   data: parms,
		   success: doneSavingDocument
		});
}

/*
 * Method that gets called after a document has been saved.
 */
function doneSavingDocument(responseText) {
	var statusText = jQuery(responseText).find("status").text();
	if (statusText == "error") {
		var statusMsg = jQuery(responseText).find("message").text();
		alert('Unable to save favorite: ' + statusMsg);
	} 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 = "";
	if(path.indexOf("?") != -1){
		url = path;
	}else{
		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;

	jQuery.ajax({
		 type: "POST",
		   url: '/my/recommendations/alert/save',
		   data: parms,
		   success: doneSettingRecommendationAlert
		});
}

/*
 * Method that gets called after an alert has been set.
 */
function doneSettingRecommendationAlert(responseText) {
	var statusText = jQuery(responseText).find("status").text();
	if (statusText == "error") {
		var statusMsg = jQuery(responseText).find("message").text();
		alert('Unable to set alert: ' + statusMsg);
	} 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;
	jQuery.ajax({
		 type: "POST",
		   url: '/my/recommendations/alert/save',
		   data: parms,
		   success: doneEditingRecommendationAlert
		});
}

/*
 * Method that gets called after an alert has been edited.
 */
function doneEditingRecommendationAlert(responseText) {
	var statusText = jQuery(responseText).find("status").text();
	if (statusText == "error") {
		var statusMsg = jQuery(responseText).find("message").text();
		alert('Unable to edit alert: ' + statusMsg);
	} 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) {
		jQuery.ajax({
			 type: "POST",
			   url: '/my/recommendations/alert/delete',
			   data: parms,
			   success: doneDeletingRecommendationAlert
			});
	}
	
}

/*
 * Method that gets called after an alert has been deleted.
 */
function doneDeletingRecommendationAlert(responseText) {
	var statusText = jQuery(responseText).find("status").text();
	if (statusText == "error") {
		var statusMsg = jQuery(responseText).find("message").text();
		alert('Unable to delete alert: ' + statusMsg);
	} 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;

	jQuery.ajax({
		 type: "POST",
		   url: '/my/document/save/multiple',
		   data: parms,
		   success: doneSavingSelectedDocuments
		});
}

/*
 * Method that gets called after a document has been saved.
 */
function doneSavingSelectedDocuments(responseText) {
	var statusText = jQuery(responseText).find("status").text();
	if (statusText == "error") {
		var statusMsg = jQuery(responseText).find("message").text();
		alert('Unable to save favorites: ' + statusMsg);
	} 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;
	//Variable to store the record tye (award/oppurtunity)
	var recordType;

		if(content=='S'){
			recordType="opportunity";
		}else{
			recordType="award";
		}
	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 must select at least one "+recordType+" to print.");
		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, searchStringDisplay) {

	// 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, searchStringDisplay);
}
// ----------------------------------------
// 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, searchStringDisplay) {

	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;
	var reqURL = "";
	if (ids
			&& (content == 'S' || content == 'SO' || content == 'SC'
					|| content == 'R' || content == 'RP')) {
		parms = parms + '&content=' + content + '&id=' + ids + '&searchStringDisplay=' + searchStringDisplay;
		reqURL = '/email/opportunity/searchresults';
	} else if (ids && content == 'A') {
		parms = parms + '&id=' + ids + '&searchStringDisplay=' + searchStringDisplay;
		reqURL = '/email/award/searchresults'
	}
	
	if(reqURL != ""){
		jQuery.ajax({
			 type: "POST",
			   url: reqURL,
			   data: parms,
			   success: doneSendingResults
			});
	}

	return false;
}
/*
 * Method that gets called after a results has been sent .
 */
function doneSendingResults(responseText) {
	var statusText = jQuery(responseText).find("status").text();
	if (statusText == "error") {
		var statusMsg = jQuery(responseText).find("message").text();
		alert('Unable to send email: ' + statusMsg);
	} 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;
	//Variable to store the record tye (award/oppurtunity)
	var recordType;

		if(content=='S'){
				recordType="opportunity";
			}else{
				recordType="award";
		}
	// 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 must select at least one "+recordType+" to export.");
		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 export 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 export 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 export 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;
}

/*
 * Gather the selections of leaguetabel and output a csv file with the contents
 * of the selections.
 */
function exportSelectedLeagueContentById() {
	var ids;
	var validExport = false;
	ids = document.getElementById('selectedResults').value;
	if(ids != null && ids.length > 0){
		validExport = true;
	}
	ids = ids.replace('/;/g',',');
	var parms = 'id=' + ids;
	var selectAll = '';
	if(document.getElementById('select_whole_league') != null){
		 selectAll = document.getElementById('select_whole_league').value;
		 if(selectAll == 'true'){
			 validExport = true;
			 var paramPrefix = 'leagueTableFrameBean.'
			 parms =  paramPrefix + 'selectAll=true';
			 if(document.getElementById('selected_alphabet') != null
					 && document.getElementById('selected_alphabet').value != "all"  ){
				 parms = parms + '&' + paramPrefix + 'alphabet=' + document.getElementById('selected_alphabet').value;
			 }
		 }
	}
	if(validExport == true){
		window.location = buildURL('/export/leaguetable', null, parms, null,
				null);
	}else{
		alert("You must select atleast one sponsor to export");
	}
		
	 	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("You must select two opportunities 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 = 5;
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();
}

function showClusters(clusterLimit){
	clusteringShowing = clusterLimit;
	showClustering();
}

/*
 * When the user clicks the "more" link, this function will be called to cause
 * more clustering categories to be shown.
 */
function showMoreClustering(i,id) {
	document.getElementById(id).style.overflow='auto';
	if (clusteringShowing == 3) {
		clusteringShowing = 10;
	} else {
		clusteringShowing = clusteringShowing * 2;
	}
	showColumnClustering(i,id);
}

/*
 * When the user clicks the "less" link, this function will be called to cause
 * fewer clustering categories to be shown.
 */
function showLessClustering(i,id) {
	if (clusteringShowing == 10) {
		clusteringShowing = 3;
	} else {
		clusteringShowing = clusteringShowing / 2;
	}
	showColumnClustering(i,id);
}

/*
 * 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,id) {
	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");
		document.getElementById(id).style.overflow='hidden';
	}

	// 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();
var selectedCountryElement = 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;
}
function addBulkOnEnterKeyPress(event) {
	if (event.value == 'showregister') {
		addItem('subjectArea', 'displaySubjectArea', 'selectedSubjectArea',
				'subject area');
		hideDiv('subjectarea_add');
		return false;
	} else
		return true;
}

/*GEOEXP - Profile - Start*/

/*
 * This function is called when Enter Key is pressed after selecting the country
 * from the drop-down.
 */
function addCountryOnEnterKeyPress(event) {
	if ((event.which && event.which == 13)
			|| (event.keyCode && event.keyCode == 13)) {		
		addItem('country','displayCountry','selectedCountry','country');
	
		return false;
	} else
		return true;
}
/*GEOEXP - Profile - End*/

/*
 * 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, displayElementId, msg);
		} else {
			addSelected(id.value,displayElementId, 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, displayElementId, msg) {
	var length = id.length;
	if (displayElementId != "displayCountry") {
		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 + ".");
		}
	}else{
		var selectedCountryElementLength = selectedCountryElement.length;
		var item;
		if (selectedCountryElementLength == 0 ) {
			for ( var i = 2; i < length; i++) {
				item = id.options[i].value;
				selectedCountryElement.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,displayElementId, msg) {
	if (displayElementId != "displayCountry") {
		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);
		}
	}else{
		var length = selectedCountryElement.length;
		var flag = new Boolean("true");
		if (length == 0) {
			selectedCountryElement.push(value);
			flag = false;
		} else {
			for ( var i = 0; i < length; i++) {
				if (selectedCountryElement[i] == value) {
					alert("You have already selected that " + msg + ".");
					flag = false;
					return;
				}
			}
		}
		if (flag) {
			selectedCountryElement.push(value);
		}
	}
}

/*
 * This function is called to display the selectedElement in a particular div id
 */
function displaySelected(displayElementId, hiddenElementId) {

	var closebuttontag;

	if (displayElementId != "displayCountry") {
		var tmpSelectedElement;
		var length = selectedElement.length;
		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;
	}else{
		var tmpSelectedCountryElement;
		var length = selectedCountryElement.length;
		document.getElementById(displayElementId).innerHTML = "";
		for ( var i = 0; i < length; i++) {
			if (selectedCountryElement[i] != "null"
					&& selectedCountryElement[i] != "undefined" && selectedCountryElement[i] !=  undefined) {
				tmpSelectedCountryElement += ";" + selectedCountryElement[i];
				closebuttontag = '<img src="/static/images/grant/icon_delete.gif" style="vertical-align:super" id="'
						+ selectedCountryElement[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 += selectedCountryElement[i]
						+ closebuttontag + ", ";
			}
		}
		document.getElementById(hiddenElementId).value = tmpSelectedCountryElement;
	}
}

/*
 * This function is called to delete a particular element
 */
function deleteSelected(deleteItemId, displayElementId, hiddenElementId) {
	removeSelected(deleteItemId, displayElementId, hiddenElementId);
}
/*
 * This function is called to delete a particular element.
 */
function removeSelected(item, displayElementId, hiddenElementId) {
	var newSelectedElement = new Array();
	var newSelectedCountryElement = new Array();
	if (displayElementId != "displayCountry") {
		var length = selectedElement.length;
		for ( var i = 0; i < length; i++) {
			if (selectedElement[i] != item) {
				newSelectedElement.push(selectedElement[i]);
			}
		}
		selectedElement = newSelectedElement;
	} else {
		var length = selectedCountryElement.length;
		for ( var i = 0; i < length; i++) {
			if (selectedCountryElement[i] != item) {
				newSelectedCountryElement.push(selectedCountryElement[i]);
			}
		}
		selectedCountryElement = newSelectedCountryElement;
	}
	displaySelected(displayElementId, hiddenElementId);
}

function showSelectedSubjectArea(selectedSubjectArea, displayElementId,
		hiddenElementId) {
	if (selectedSubjectArea.length != 0) {
		var tmpSelectedElement = selectedSubjectArea.split(";");
		for ( var i = 1; i < tmpSelectedElement.length; i++) {
			selectedElement.push(tmpSelectedElement[i]);
		}
		displaySelected(displayElementId, hiddenElementId);
	}
	return false;
}

/*GEOEXP - Profile - Start*/
function showSelectedCountry(selectedCountry, displayElementId, hiddenElementId){	
	if (selectedCountry.length != 0) {
		var tmpSelectedElement = selectedCountry.split(";");		
		for ( var i = 0; i < tmpSelectedElement.length; i++) {
				if (tmpSelectedElement[i]!=""){
					selectedCountryElement.push(tmpSelectedElement[i]);
				}
		}		
		displaySelected(displayElementId, hiddenElementId);
	}
	return false;
}
/*GEOEXP - Profile - End*/

/*
 * 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();
	updateSelectedResultsInCookie();
}

function updateSelectedResultsInCookie(){
	
	var cookieName = retrieveCookieNameByTab();
	eraseCookie(cookieName);
	createCookie(cookieName , jQuery("#selectedResults").val(), "");
	
}

function retrieveCookieNameByTab(){
	var cookieName = "selectedResults";
	if(jQuery("#current_tab") != null
		&& jQuery("#current_tab").val() != null
		&& jQuery("#current_tab").val().length > 0){
		var current_tab_value = jQuery("#current_tab").val();
		if(current_tab_value == "OPP_TAB"){
			cookieName ="oppSelectedResults";
		}else if(current_tab_value == "INACTIVE_OPP_TAB"){
			cookieName ="InactiveOppSelectedResults";
		}else if(current_tab_value == "AWARD_TAB"){
			cookieName ="awardSelectedResults";
		}
	}
	return cookieName;
}

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) {
	var selectedResultsValue = document.getElementById("selectedResults").value;
	if(selectedResultsValue.indexOf(resultId) == -1){
		document.getElementById("selectedResults").value 
								= selectedResultsValue	+ 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;
	}
	selectAllResultsOnPageLink = jQuery.trim(selectAllResultsOnPageLink);
	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_dwn.png' rsrc='/static/images/grant/icon_sel_col_dwn.png' alt='Select All' >Select All";
			var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.png' rsrc='/static/images/grant/icon_sel_col_dwn.png' alt='Select All' >Select All";
			document.getElementById("selectAllResultsOnPageLink").innerHTML = inhtml;
			document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlBottom;
			document.getElementById('selectAllResultsMessage').innerHTML = "";
			jQuery("#selectAllResultsOnPageLink").attr("title","Select all results");
			jQuery("#selectAllResultsOnPageLinkAtBottom").attr("title","Select all results");
			
		}

		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_dwn.png' rsrc='/static/images/grant/icon_sel_col_dwn.png' alt='Deselect All' >Deselect All";
			var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.png' rsrc='/static/images/grant/icon_sel_col_dwn.png' alt='Deselect All' >Deselect All";
			document.getElementById("selectAllResultsOnPageLink").innerHTML = inhtml;
			document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlBottom;
			jQuery("#selectAllResultsOnPageLink").attr("title","Deselect all results");
			jQuery("#selectAllResultsOnPageLinkAtBottom").attr("title","Deselect all results");
			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_dwn.png' rsrc='/static/images/grant/icon_sel_col_dwn.png' alt='Select All' >Select All";
			var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.png' rsrc='/static/images/grant/icon_sel_col_dwn.png' alt='Select All' >Select All";
			document.getElementById("selectAllResultsOnPageLink").innerHTML = inhtml;
			document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlBottom;
			jQuery("#selectAllResultsOnPageLink").attr("title","Select all results");
			jQuery("#selectAllResultsOnPageLinkAtBottom").attr("title","Select all results");
		} 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_dwn.png' rsrc='/static/images/grant/icon_sel_col_dwn.png' alt='Deselect All' >Deselect All";
			var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.png' rsrc='/static/images/grant/icon_sel_col_up.png' alt='Deselect All' >Deselect All";
			document.getElementById("selectAllResultsOnPageLink").innerHTML = inhtml;
			document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlBottom;
			jQuery("#selectAllResultsOnPageLink").attr("title","Deselect all results");
			jQuery("#selectAllResultsOnPageLinkAtBottom").attr("title","Deselect all results");
			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 selectAllOnPage() {
	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;
//	}
//	selectAllResultsOnPageLink = jQuery.trim(selectAllResultsOnPageLink);
	if (jQuery("#selectAllResultsOnPageLink").hasClass("select_all_active")) {

//			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_dwn.png' rsrc='/static/images/grant/icon_sel_col_dwn.png' alt='Select this page&#39;s results' >Select page";
//			var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.png' rsrc='/static/images/grant/icon_sel_col_dwn.png' alt='Select this page&#39;s results' >Select page";
//			document.getElementById("selectAllResultsOnPageLink").innerHTML = inhtml;
//			document.getElementById("selectAllResultsOnPageLinkAtBottom").innerHTML = inhtmlBottom;
//			document.getElementById('selectAllResultsMessage').innerHTML = "";
//			jQuery("#selectAllResultsOnPageLink").attr("title","Select this page&#39;s results");
//			jQuery("#selectAllResultsOnPageLinkAtBottom").attr("title","Select this page&#39;s results");
//			jQuery('#selectAllResultsOnPageLink').removeClass("select_all_active");
//			jQuery('#selectAllResultsOnPageLinkAtBottom').removeClass("select_all_active");
			clearSelection();
		}else {
			selectAllCheckBoxesInThePage();
			document.getElementById("isAllSelectedOnPage").value = true;

			jQuery("#selectAllResultsOnPageLink").addClass("select_all_active");
			jQuery("#selectAllResultsOnPageLinkAtBottom").addClass("select_all_active");
			
			jQuery('#selectWholeResultsLink').removeClass("select_all_active");
			jQuery("#selectWholeResultsLinkBottom").removeClass("select_all_active");
			
		}
	
}

function monitorSelectedResults() {
	var numSelectedCount = countSelected();
	if (document.getElementById("allSelectedinAllPages").value == "true") {
		if (numSelectedCount < document.getElementById("resultsPerPage").value) {
			document.getElementById("isAllSelectedOnPage").value = false;
		} else if (numSelectedCount == document.getElementById("resultsPerPage").value) {
			document.getElementById("isAllSelectedOnPage").value = true;
		}
	} else {
		if ((numSelectedCount == document.getElementById("resultsPerPage").value)
				&& (numSelectedCount < document
						.getElementById("totalresultscount").value)) {
			document.getElementById("isAllSelectedOnPage").value = true;
		} else if ((numSelectedCount == document
				.getElementById("resultsPerPage").value)
				&& (numSelectedCount == document
						.getElementById("totalresultscount").value)) {
			document.getElementById("isAllSelectedOnPage").value = true;
		} else {
			document.getElementById("isAllSelectedOnPage").value = false;
		}
	}
	
	if(document.getElementById("isAllSelectedOnPage").value == "true"
			&& document.getElementById('allSelectedinAllPages').value == "false"
			){
		if(!jQuery('#selectAllResultsOnPageLink').hasClass("select_all_active")){
			jQuery("#selectAllResultsOnPageLink").addClass("select_all_active");
			jQuery("#selectAllResultsOnPageLinkAtBottom").addClass("select_all_active");
			
			jQuery('#selectWholeResultsLink').removeClass("select_all_active");
			jQuery("#selectWholeResultsLinkBottom").removeClass("select_all_active");
		}
		
	}else{
		jQuery("#selectAllResultsOnPageLink").removeClass("select_all_active");
		jQuery("#selectAllResultsOnPageLinkAtBottom").removeClass("select_all_active");
	}
	
	if(document.getElementById('allSelectedinAllPages').value == "true"
			&& document.getElementById("isAllSelectedOnPage").value == "true"
			){
		if(!jQuery('#selectWholeResultsLink').hasClass("select_all_active")){
			jQuery('#selectWholeResultsLink').addClass("select_all_active");
			jQuery("#selectWholeResultsLinkBottom").addClass("select_all_active");
		}
		
	}else if(document.getElementById('isAllSelectedOnPage').value == "false"
		|| document.getElementById('allSelectedinAllPages').value == "false"){
		jQuery('#selectWholeResultsLink').removeClass("select_all_active");
		jQuery("#selectWholeResultsLinkBottom").removeClass("select_all_active");
	}
}
//Start FIT_Carryover-10_1 changes
/*
 * This function handles the selection of excluded eids and it submit it to the action bean 
 */
function excludeSelectedContent(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 must select at least one opportunity to exclude.");
		return false;
	}
	if(confirm('Excluding this opportunity will remove it from subsequent opportunity recommendations in future. Do you wish to proceed?')){
	// 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('excludedRecomendationsMaxSelectCount').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 exclude a maximum of " + maxSelectCount
					+ " items.Select OK to " + "proceed to exclude 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;
		}

	}

	
	if (resultsSelectionLimited) {
		/*
		 * send to the action bean a flag indicating that the user was forced
		 * select limited set of results
		 */
		
		document.excludeOpportunity.resultsSelectionLimited.value = 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;

	}

	var excludeOpportunity = document.getElementById('excludeOpportunity');
	document.excludeOpportunity.deselectedResults.value = desel;
	document.excludeOpportunity.allSelectedinAllPages.value = allsel;
	document.excludeOpportunity.excludedId.value = ids;
	document.excludeOpportunity.submit();
}
}
/*
 * This function handles the selection of included eids and it submit it to the action bean 
 */
function includeRecommendations(name) {
	
	var count = 0;
	var id;
	// 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) {
				
				if(i>0){
				 id = id + elements[i].value + ";";
				}else{					
					 id = elements[i].value + ";";
				}
				foundOne = true;
				count += 1;
			}
		}
		if (!foundOne) {
			// There weren't any selected items.
			alert("No Recommended opportunities were selected.To include recommended opportunities , select one or more recommended opportunities and click include.");

		} else if (count <= 1) {
			if (confirm('Are you sure you want to include this recommended opportunity?')) {

				var includeOpportunity = document
						.getElementById('includeOpportunity');
				document.includeOpportunity.includedId.value = id;
				document.includeOpportunity.submit();
			}
		} else if (count > 1) {
			if (confirm('Are you sure you want to include these recommended opportunities?')) {
				var includeOpportunity = document
						.getElementById('includeOpportunity');
				document.includeOpportunity.includedId.value = id;
				document.includeOpportunity.submit();
			}
		}
	}
	return false;
}
// End FIT_Carryover-10_1 changes
/*
 * 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 = "";
	document.getElementById('allSelectedinAllPages').value = false;
	
	jQuery("#selectAllResultsOnPageLink").removeClass("select_all_active");
	jQuery("#selectAllResultsOnPageLinkAtBottom").removeClass("select_all_active");
	
	jQuery('#selectWholeResultsLink').removeClass("select_all_active");
	jQuery('#selectWholeResultsLinkBottom').removeClass("select_all_active");
}



function clearWholeSelection() {
	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 = "";
	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>';
	}
}

function selectWholeResults() {
	if(jQuery('#selectWholeResultsLink').hasClass("select_all_active")){
		clearSelection();
	}else{
		var searchResults = document.getElementById("results_on_page")
		.getElementsByTagName("input");
		jQuery('#selectAllResultsOnPageLink').removeClass("select_all_active");
		jQuery('#selectAllResultsOnPageLinkAtBottom').removeClass("select_all_active");
		
		jQuery('#selectWholeResultsLink').addClass("select_all_active");
		jQuery('#selectWholeResultsLinkBottom').addClass("select_all_active");
		
		for ( var i = 0; i < searchResults.length; i++) {
			if (searchResults[i].type == "checkbox") {
				searchResults[i].checked = true;
				addResultIdTocheckedList(searchResults[i].value);
			}
		}
		document.getElementById("deselectedResults").value = "";
		document.getElementById('allSelectedinAllPages').value = true;
	}
	
}

// ----------------------------------------------------------------------------
// 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_dwn.png' rsrc='/static/images/grant/icon_sel_col_dwn.png' alt='Select All' >Select All";
		var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.png' rsrc='/static/images/grant/icon_sel_col_up.png' alt='Select All' >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_dwn.png' rsrc='/static/images/grant/icon_sel_col_dwn.png' alt='Deselect All' >Deselect All";
		var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.png' rsrc='/static/images/grant/icon_sel_col_up.png' alt='Deselect All' >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_dwn.png' alt='Deselect All' >Deselect All";
		var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.png' alt='Deselect All' >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_dwn.png' alt='Select All' >Select All";
		var inhtmlBottom = "<img src='/static/images/grant/icon_sel_col_up.png' alt='Deselect All' >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.png'  alt='Select All' >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 maxTitleWidth;

    var decimal;



//    if ((screen.width > 1024) && (screen.height > 768) && size == '0.7em') {
//
//          decimal = .0255;
//          maxTitleLength = document.body.clientWidth * decimal;
//          if (title.length > maxTitleLength+10) {
//                var probableExtraLength=10*countCapsRatio(title); 
//                if(probableExtraLength>3)
//                title = title.substring(0, maxTitleLength-probableExtraLength+9) + "...";
//                else
//                title = title.substring(0, maxTitleLength+11) + "..."; 
//          }
//
//    } else if ((screen.width > 1024) && (screen.height > 768)
//
//                && size == '0.77em') {
//
//          decimal = 0.0255;
//          maxTitleLength = document.body.clientWidth * decimal;
//          if (title.length > maxTitleLength+6) {
//                var probableExtraLength=10*countCapsRatio(title);
//                if(probableExtraLength>3)
//                title = title.substring(0, maxTitleLength-probableExtraLength+8) + "...";
//                else
//                title = title.substring(0, maxTitleLength+10) + "...";                       
//  }
//
//    } else if ((screen.width > 1024) && (screen.height > 768)
//
//                && size == '0.83em') {
//
//          decimal = 0.0255;
//          maxTitleLength = document.body.clientWidth * decimal;
//          if (title.length > maxTitleLength+4) {
//                var probableExtraLength=10*countCapsRatio(title);          
//
//                if(probableExtraLength>3)
//                title = title.substring(0, maxTitleLength-probableExtraLength+7) + "..."; 
//                else
//                title = title.substring(0, maxTitleLength+8) + "...";                   
//
//          }
//
//    } else if ((screen.width <= 1024) && (screen.height <= 768)
//
//                && size == '0.7em') {
//
//          decimal = 0.050;
//          maxTitleLength = document.body.clientWidth * decimal;
//          if (title.length > maxTitleLength-10) {
//                var probableExtraLength=10*countCapsRatio(title);
//                if(probableExtraLength>3)
//                title = title.substring(0, maxTitleLength-probableExtraLength-3) + "...";
//                else 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-6) {
//                var probableExtraLength=10*countCapsRatio(title);         
//
//                if(probableExtraLength>3)
//                title = title.substring(0, maxTitleLength-probableExtraLength+1) + "...";      
//
//                else if(title.length > maxTitleLength)                	
//                title = title.substring(0, maxTitleLength+1) + "...";                   
//
//          }
//
//    } else if ((screen.width <= 1024) && (screen.height <= 768)
//
//                && size == '0.83em') {
//
//          decimal = 0.04;
//          maxTitleLength = document.body.clientWidth * decimal;
//          if (title.length > maxTitleLength-4) {
//                var probableExtraLength=10*countCapsRatio(title);           
//
//                if(probableExtraLength>3)
//                title = title.substring(0, maxTitleLength-probableExtraLength+3) + "...";      
//
//                else
//                title = title.substring(0, maxTitleLength+2) + "...";             
//
//          }
//
//    }

    if(title.length > 29){
		title = title.substring(0, 26) + "...";
	}
    if (obj) {

          curtitle += "<a href='/opportunity/" + itemId

                      + "' style='text-decoration:none;color:#333399;'>" + title

                      + "</a>";

    } else {
    	
          document.write(title);

    }

}

function countCapsRatio(title) {
	var count=0;			
   for(var i=0; i < title.length/5; i++) { 
	if((title.charCodeAt(i) >= 65 && title.charCodeAt(i) <= 90) || title.charCodeAt(i) ==" " || title.charCodeAt(i) =="-")
		count++;	
	}	
   return 5*count/title.length;
} 
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.toLowerCase(); 
	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_SearchWithin(obj) {
	var swEmptyText = '  Search within results';
	if (obj.value == swEmptyText) {
		obj.value = '';
		document.getElementById('swsubmit').disabled = false
	}
	;
	obj.className = 'input input_sel';
	return false
}
function enable_QuickSearch(obj) {
	var qsEmptyText = '  Enter a new search';
	if (obj.value == qsEmptyText) {
		obj.value = '';
		document.getElementById('qssubmit').disabled = false
	}
	;
	obj.className = 'input input_sel';
	return false
}

function checkText(){
	var qsfield = document.getElementById('quicksearchText');
	var qssubmit = document.getElementById('qssubmit');
	if (qsfield.value.length == 0 || qsfield.value == '' ) {
		qsfield.className='input input_des';
		qsfield.value=qsEmptyText;
	} else {
		qsfield.className='input input_sel';
	}
}

function postHitTerm(eid, hitTerms, currOffset) {
	hittermpostform = document.getElementById('hitTermPostForm');
	hittermpostform.elements["hitTerms"].value = hitTerms;
	hittermpostform.elements["currOffset"].value=currOffset;
	hittermpostform.action=hittermpostform.action+"?id="+eid;	
	hittermpostform.submit();
}
function postHitTermRecommendations(eid, hitTerms, currOffset,auid) {
	hittermpostform = document.getElementById('hitTermPostForm');
	hittermpostform.elements["hitTerms"].value = hitTerms;
	hittermpostform.elements["currOffset"].value=currOffset;
	hittermpostform.action=hittermpostform.action+"/"+eid +"?"+auid;	
	hittermpostform.submit();
}
function submitRecScivalPage(event) {
	if (event.keyCode == 13) {
		recscivalform = document.getElementById('recommendScival');
		recscivalform.submit();
	}
}

function postDetails(eventType){	
	detailspostform = document.getElementById('detailsPostForm');
	document.getElementById('event').value = eventType;	
	detailspostform.action=detailspostform.action+"?id="+detailspostform.elements["id"].value;
	detailspostform.appendChild(document.getElementById('event'));
	detailspostform.submit();
}

function postBulkDetails(eventType){
	var bulkPostform = document.getElementById('bulkPostForm');
	document.getElementById('event').value = eventType;
	bulkPostform.appendChild(document.getElementById('event'));
	bulkPostform.submit();
}

function postToEmailAction(){
	document.getElementById('detailsPostFormEmail').submit();
	}

function removeAuthorFromProfile(auid){
	if (confirm('Are you sure you want to remove this Publication Profile? Removing this profile will also remove all of the subject areas and keywords associated with it?')) {
	var removeAuthorDetails = document.getElementById('removeAuthorDetails');
	document.removeAuthorDetails.userSelectedAuthorId.value = auid;
	document.removeAuthorDetails.submit();
	}
}
function removeSubjectArea(subjectArea){
	if (confirm('Are you sure you want to remove this Subject Area?')) {
	var removeAuthorDetails= document.getElementById('removeAuthorDetails');
	document.removeAuthorDetails.userSelectedAuthorSubjectArea.value = subjectArea;
	document.removeAuthorDetails.submit();
	}
}function removeKeyword(subjectArea){
	if (confirm('Are you sure you want to remove this Keyword?')) {
		var removeAuthorDetails = document.getElementById('removeAuthorDetails');
		document.removeAuthorDetails.userSelectedAuthorKeyword.value = subjectArea;
		document.removeAuthorDetails.submit();
		}
	}
function mouseOver(id, name) {
	var divId = id + name;
	document.getElementById(divId).className = 'hover';
}
function mouseOut(id, name) {
	var divId = name + id;
	if (!document.getElementById(divId).checked) {
		document.getElementById(id + name).className = 'none';
	} else {
		document.getElementById(id + name).className = 'selected';
	}
}
function onClickTask(id, name) {
	var divId = name + id;	
	var namesArray = document.getElementsByName(name);
	var namesLength = namesArray.length;
		if (id != '1' ) {
			if(document.getElementById(name + id).checked){
				var selectedAll = true;
				for ( var i = 2; i <= namesLength; i++) {
					if(!document.getElementById(name + i).checked){
						selectedAll = false;
					}
				//document.getElementById(i + name).className = 'none';
				}
				if(selectedAll == true){
					document.getElementById(name + 1).checked = true;
					document.getElementById(1 + name).className = 'selected';
				}else{
					document.getElementById(name + 1).checked = false;
					document.getElementById(1 + name).className = 'none';
				}
			}else{
				document.getElementById(name + 1).checked = false;
				document.getElementById(1 + name).className = 'none';
			}
		}
		if (id == '1') {
			
			if(name == "terms.countries"
				&& !isNaN(document.getElementById("terms.countries_groupcount").value)){
				namesLength = namesLength + parseInt(document.getElementById("terms.countries_groupcount").value);
			}
			for ( var i = 2; i <= namesLength; i++) {
				document.getElementById(name + i).checked = document.getElementById(name + 1).checked;
				if(document.getElementById(name + i).checked){
					document.getElementById(i + name).className = 'selected';
				}else{
					document.getElementById(i + name).className = 'none';
				}
			//document.getElementById(i + name).className = 'none';
			}
		}
	if (document.getElementById(divId).checked) {
		document.getElementById(id + name).className = 'selected';
	} else {
		document.getElementById(id + name).className = 'none';
	}

}

function checkBoxGroupSelection(groupHeaderId,startIndex, endIndex, idPrefix){
	var incrGroup= 0;
	var groupHeaderValue = false;
	if(document.getElementById(groupHeaderId) != null){
		groupHeaderValue = document.getElementById(groupHeaderId).checked
	}
	for(incrGroup=startIndex; incrGroup<= endIndex; incrGroup++){
		if(document.getElementById(idPrefix + incrGroup) != null){
			document.getElementById(idPrefix + incrGroup).checked = groupHeaderValue;
			if(groupHeaderValue == true){
				document.getElementById(incrGroup + idPrefix).className = 'selected';
			}else{
				document.getElementById(incrGroup + idPrefix).className = 'none';
			}
			
		}
	}
}

function handleChildSelection(groupHeaderId,childId,startIndex, endIndex, idPrefix){
	var incrGroup= 0;
	var childValue = false;
	if(document.getElementById(childId) != null){
		childValue = document.getElementById(childId).checked
	}
	if(childValue == true
			&& isAllInGroupSelected(groupHeaderId,startIndex, endIndex, idPrefix)){
		document.getElementById(groupHeaderId).checked = true;
	}else{
		document.getElementById(groupHeaderId).checked = false;
	}
}


function isAllInGroupSelected(groupHeaderId,startIndex, endIndex, idPrefix){
	var selectedCount = 0;
	var unSelectedCount = 0;
	for(incrGroup=startIndex; incrGroup<= endIndex; incrGroup++){
		if(document.getElementById(idPrefix + incrGroup) != null){
			if(document.getElementById(idPrefix + incrGroup).checked){
				selectedCount++;
			}else{
				unSelectedCount++;
			}
		}
	}
	if(selectedCount > 0 && unSelectedCount < 1){
		return true;
	}
	return false;
}

function checkItOnLoad(name) {
	var namesArray = document.getElementsByName(name);
	var allFlag = true;
	var namesLength = namesArray.length;
	if(name == "terms.countries"
		&& !isNaN(document.getElementById("terms.countries_groupcount").value)){
		namesLength = namesLength + parseInt(document.getElementById("terms.countries_groupcount").value);
	}
	for ( var i = 1; i <= namesLength; i++) {
		if (document.getElementById(name + i) != null
				&& document.getElementById(i + name) != null) {
			if (document.getElementById(name + i).checked) {
				document.getElementById(i + name).className = 'selected';
				allFlag = false;
			}
		}
	}
	if (allFlag) {
		document.getElementById(1 + name).className = 'selected';
		document.getElementById(name + 1).checked = true;
		for ( var i = 1; i <= namesLength; i++) {
			if (document.getElementById(name + i) != null
					&& document.getElementById(i + name) != null) {
				document.getElementById(name + i).checked = true;
				document.getElementById(i + name).className = 'selected';
			}
		}
	}
}

function showSetAlertOverlay(divid,frequencyid){
	var freqSelectBox = document.getElementById(frequencyid);
	var freqValue = '';
	if(freqSelectBox != null ){
		freqValue = freqSelectBox.options[freqSelectBox.selectedIndex].value;
	}
	
	if(divid == 'set_alert_rec'  || (freqValue != null && freqValue.length > 0 && freqValue != "N")){
		//document.getElementById(frequencyid+'_disp').innerHTML = freqSelectBox.options[freqSelectBox.selectedIndex].text;
		showOverlayById(divid,400,1,true);
	}else{
		alert("Please select a frequency to set an alert");
	}
}

function selectItemsOnload(){
	if (document.getElementById("results_on_page") != null) {
		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;
			}
		}
		checkSelected();
	}
}

function checkSelected(){
	var selectedArr = new Array();
	var selectedStr = "";
	if(document.getElementById("select_whole_league") != null ){
		var wholeLeagueValue = document.getElementById("select_whole_league").value;
		if(wholeLeagueValue == "true"){
			selectAllItems('chk');
			leagueSelectAllMessage('select_whole_league');
			return;
		}
	}
	var selectedCount = 0;
	if (document.getElementById("selectedResults") != null) {
		selectedStr = document.getElementById("selectedResults").value;
		if (selectedStr.length > 0) {
			selectedArr = selectedStr.split(";");
			if (selectedArr.length > 0) {
				for ( var incr = 0; incr < selectedArr.length; incr++) {
					var checkBoxToBeSelected = document
							.getElementById("doc_select_"
									+ selectedArr[incr]);
					if (checkBoxToBeSelected != null) {
						checkBoxToBeSelected.checked = true;
						selectedCount++;
					}
				}
			}
		}
	}
	
	if(document.getElementById('resultsNavigationDropDownList') != null 
		&& selectedCount == document.getElementById('resultsNavigationDropDownList').value){
		allSelectedOnLeague();
	}
	
	
}

function allSelectedOnLeague(){
	
	document.getElementById('selectAll').style.display = 'none';
	document.getElementById('DeselectAll').style.display = 'block';
	if(document.getElementById('select2All')){
		document.getElementById('select2All').style.display = 'none';
		document.getElementById('Deselect2All').style.display = 'block';
	}
	var field = document.getElementsByName('chk');
	
	for (i = 0; i < field.length; i++)
	{
		field[i].checked = true ;
		var id = field[i].id;
		addResultIdTocheckedList(id.replace('doc_select_',''));
	}
	setSelectAllLeague('true');
	leagueSelectAllMessage('select_all_page');

}

function selectWholeLeague(){
	setSelectWholeLeague('true');
	leagueSelectAllMessage('select_whole_league');
}

function clearLeagueSelection(){
	if (document.getElementById("selectedResults") != null) {
		document.getElementById("selectedResults").value = "";
	}
	setSelectWholeLeague('false');
	setSelectAllLeague('false');
	leagueSelectAllMessage('clear_selection');
}

function setSelectWholeLeague(value){
	if(document.getElementById('select_whole_league') != null){
		document.getElementById('select_whole_league').value = value;
	}
}

function setSelectAllLeague(value){
	if(document.getElementById('select_all_page_league') != null){
		document.getElementById('select_all_page_league').value = value;
	}
}

function leagueSelectAllMessage(action){
	if(action == 'select_all_page'){ 
		showDiv('div_select_all_page_message');
		hideDiv('div_select_whole_message');
	}else if(action == 'select_whole_league'){
		hideDiv('div_select_all_page_message');
		showDiv('div_select_whole_message');
	}else{
		hideDiv('div_select_all_page_message');
		hideDiv('div_select_whole_message');
	}
}

function allDeselectedOnLeague(){
	document.getElementById('DeselectAll').style.display = 'none';
	document.getElementById('selectAll').style.display = 'block';
	if(document.getElementById('Deselect2All')){
		document.getElementById('select2All').style.display = 'block';
		document.getElementById('Deselect2All').style.display = 'none';
	}
	var field = document.getElementsByName('chk');
	for (i = 0; i < field.length; i++)
	{
		field[i].checked = false ;
		var id = field[i].id;
		removeResultIdFromcheckedList(id.replace('doc_select_',''));
	}
	clearLeagueSelection();
}

function handleLeagueSelection(resultId){
	if(resultId != null){
		var elementId = "doc_select_" + resultId;
		var status = document.getElementById(elementId).checked;
		if(status == true){
			addResultIdTocheckedList(resultId);
		}else{
			removeResultIdFromcheckedList(resultId);
			clearLeagueSelection();
		}
	}
}

function showLoadingImage(){
	jQuery("#loading_overlay_background").show();
	jQuery("#loading_overlay_image").show();
}

function hideLoadingImage(){
	jQuery("#loading_overlay_background").hide();
	jQuery("#loading_overlay_image").hide();
}

function toggleDivById(showId,hideId){
	jQuery("#"+showId).show();
	jQuery("#"+hideId).hide();
	
}

function selectAllCheckBoxesInThePage(){
	var searchResults = document.getElementById("results_on_page")
										.getElementsByTagName("input");
	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);
			}
		}
	}
}

function scrollme(){
	dh=document.body.scrollHeight
	ch=document.body.clientHeight
	if(dh>ch){
	moveme=dh-ch
	window.scrollTo(0,moveme)
	}
	}
function expandOrCollapseDiv(img_id, div_nav_id){
	
	if(jQuery("#" + img_id).hasClass("div_expand_home")){
		 jQuery("#" + img_id).removeClass("div_expand_home");
		 jQuery("#" + img_id).addClass("div_collapse_home");
		 jQuery("#" + img_id).attr("src", "/static/images/grant/minus_icon.png");
		 jQuery("#" + div_nav_id).show();
		
		 
	 }else{
		 jQuery("#" + img_id).removeClass("div_collapse_home");
		 jQuery("#" + img_id).addClass("div_expand_home");
		 jQuery("#" + img_id).attr("src", "/static/images/grant/plus_icon.png");
		 jQuery("#" + div_nav_id).hide();
		 
	 }
}

function getCountryResults(countryName){
	
	location.href="/browse/opportunities/location?id=10&country=" +countryName;
}

function getCountryGroupResults(countryGroupName){
    
    location.href="/browse/opportunities/location?id=10&country=&countryGroup=" +countryGroupName;
}


function getSubjectResults(subjectCode){
	
	location.href="/browse/opportunities?id=" + subjectCode;
}

function getSubjectGroupResults(subjectGroupName){
    
    location.href="/browse/opportunities?id=777&subjectGroup=" + subjectGroupName;
}

function getSearchResults()
{
	var text="";
	var radio;
	if(document.getElementById('homesearchText').value != ""){
		text = document.getElementById('homesearchText').value;
	}
	if(document.getElementById('sel').checked == true){
		radio = document.getElementById('sel').value;
	}
	else if(document.getElementById('desel').checked == true){
		radio = document.getElementById('desel').value;
	}
	
	if (text == "" || text.length == 0) {
		alert('Please enter keyword to search.');
		return false;
	} else {
		window.location="/search/quick?quicksearchText=" + text + "&quicksearchContent=" +radio;
	}
	
}

function searchKeyPress(e)
{
		// look for window.event in case event isn't passed in
        if (window.event) { e = window.event; }
        if (e.keyCode == 13)
        {
        	getSearchResults();
        }
}

function openInNewWindow(newWindowUrl){
	window.open(newWindowUrl,
		 'open_window',
		 'menubar=no, toolbar=no,scrollbars=no, resizable=yes,width=890, height=560,left=0, top=0')
		
}

function openHelpUrl(){
	openInNewWindow(jQuery('#helpUrl').val());
}

function openCustomLink(url){
	window.location = url;
}

function helpHover()
{
	document.getElementById("textZone").style.color = "#339900";
}

function helpUnhover(){
	document.getElementById("textZone").style.color = "#333399";
}

function isValidString(strValue){
	if(strValue != null && jQuery.trim(strValue).length > 0){
		return true;
	}
	return false;
}
function getSpecialInterestResults(linkId){
	location.href="/specialinterest?linkId=" + linkId;
}
