/********************************************************************
	Sniffing the browser type based on code from CodeHouse.
	You can obtain this script at http://www.codehouse.com
********************************************************************/
function CJL_BrowserSniffer()
{
	var ua = navigator.userAgent;

	this.isOpera = function()
	{
		return /Opera/.test(ua);
	}

	this.isSafari = function()
	{
		return /Safari/.test(ua);
	}

	this.isGecko = function()
	{
		return navigator.product == "Gecko" && ! ( this.isOpera() || this.isSafari() );
	}

	this.isIEWin = function()
	{
		return window.external && /Win/.test(ua);
	}

	this.isIEMac = function()
	{
		return window.external && /Mac/.test(ua);
	}

	this.getVersion = function()
	{
		if( this.isIEWin() || this.isIEMac() )
		{
			return Number(ua.match(/MSIE ([0-9.]+)/)[1]);
		}
		else if ( this.isSafari() )
		{
			return Number(ua.match(/[0-9.]+$/));
		}
		else if ( this.isGecko() )
		{
			var n = ua.match(/rv:([0-9.]+)/)[1];

			var ar = n.split(".");

			var s = ar[0] + ".";

			for(var i = 1; i < ar.length; ++i)
			{
				s += ("0" + ar[i]).match(/.{2}$/)[0];
			}

			return Number(s);
		}
		else if ( this.isOpera() )
		{
			return Number(ua.match(/Opera ([0-9.]+)/)[1]);
		}
		else
		{
			return null;
		}
	}
}

sniffer = new CJL_BrowserSniffer();

if ( sniffer.isIEWin() )
{
	browserType = "iewin";
}
else if ( sniffer.isIEMac() )
{
	browserType = "iemac";
}
else if ( sniffer.isSafari() )
{
	browserType = "safari"
}
else if ( sniffer.isGecko() )
{
	browserType = "gecko";
}
else if ( sniffer.isOpera() )
{
	browserType = "opera";
}
else
{
	browserType = "unknown";
}

// alert( "Your browser type is \"" + browserType + "\"" );

/********************************************************************
	Allows a main check-box to toggle a group of checkboxes prefixed
	with the same name.
********************************************************************/
function checkGroup( mainCheck, subCheck )
{
	e = document.getElementsByName( subCheck );
	for( i=0; i< e.length; i++ )
	{
		if( e[i].type == "checkbox" )
		{
			e[i].checked=mainCheck.checked;
		}
	}
}
      
/********************************************************************
	Toggle display status of a block based on id name.
********************************************************************/
function showHideById( name )
{

	// check for DOM1 compatibility
	if( document.getElementById )
	{

		// loop thru all the elements
		for( var i = 0; document.getElementById( name + i ) != null; i++ )
		{
			var element = document.getElementById( name + i );
	
			if( element.style.display != 'none' )
			{
				element.style.display = 'none';
			}
			else
			{
				element.style.display = '';
			}
		}
	}

}


/********************************************************************
	hide a block based on id name.
********************************************************************/
function hideById( name )
{

	// check for DOM1 compatibility
	if( document.getElementById )
	{

		// loop thru all the elements
		for( var i = 0; document.getElementById( name + i ) != null; i++ )
		{
			var element = document.getElementById( name + i );
	
			if( element.style.display != 'none' )
			{
				element.style.display = 'none';
			}
		}
	}

}

/********************************************************************
	Disable a form input field.
********************************************************************/
function disableInput(form, name) {
	form[name].disabled = true;
	return true;
}

/********************************************************************
	These scripts propertly change pull-down menus that represent a
	date in a form.
********************************************************************/
//
// dateSelect is the publically called function.
//
function dateSelect( formName, property, mode )
{
	var propstring = property.split( "." );
	var table = propstring[0];
	var prop = propstring[1];
	
	// change date menu when a year or month is changed.
	if( mode != 'day' ) {
		calPop( formName, prop );
	}

	setHidden( formName, prop, table );
//	alert((eval(formName + "['" + table + "." + prop + "']")).value)
}

//
// Check for leap year.
//
function LeapYear(year)
{
	if ((year/4)   != Math.floor(year/4))	return false;
	if ((year/100) != Math.floor(year/100)) return true;
	if ((year/400) != Math.floor(year/400)) return false;
	return true;
}

//
// make sure menus have correct number of days for month.
//
function calPop( formName, property )
{
	var yearsel = eval ( formName + "." + property + "year" );
	var monthsel = eval( formName + "." + property + "month" );
	var daysel = eval( formName + "." + property + "day" );
	
	var daysinmonth   = new Array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	var daysinmonthLY = new Array( 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	
	var date = new Date( yearsel.options[yearsel.selectedIndex].value,
						 monthsel.options[monthsel.selectedIndex].value,
						 daysel.options[daysel.selectedIndex].value,
						 0, 0, 0, 0);
	var year = date.getFullYear();
	
	if( LeapYear( year ) )
	{
		daysinmonth = daysinmonthLY;
	}
	
	for (var i = 0; i < daysel.length; i++)
	{
		daysel.options[i] = null;
	}
	
	var i = 0;
	for (i = 0; i < daysinmonth[monthsel.selectedIndex]; i++)
	{
		daysel.options[i] = new Option(i+1, i+1, false, false);
	}
	
//	alert("length: " + daysel.options.length);
//	alert("last item is: " + daysel.options[i-1].value);
}

function setHidden( formName, property, table )
{
	var yearsel = eval ( formName + "." + property + "year" );
	var monthsel = eval( formName + "." + property + "month" );
	var daysel = eval( formName + "." + property + "day" );
//	alert("yearsel: " + yearsel.value + ", monthsel: " + monthsel.value + ", daysel: " + daysel.value);
	
	// month array is zero-based, but need months starting at 1.
	var month = Number(monthsel.value) + 1;

	var datefield = eval( formName + "['" + table + "." + property + "']" );
	// need date in "yyyy-mm-dd" format
	var datefieldval = yearsel.value + "-" + month + "-" + daysel.value;

	datefield.value = datefieldval;
//	 alert( datefield.value );
}

/********************************************************************
  U.S. state is selected iff country == US
********************************************************************/
function usstatesel( formName, property, attribute )
{
	if( property == null )
	{
		var state = eval ( formName + ".statecode" );
		var country = eval ( formName + ".countrycode");
	}
	else if ( attribute == null )
	{
		var state = eval ( formName + "['" + property + "' + '.' + 'statecode']" );
		var country = eval ( formName + "['" + property + "' + '.' + 'countrycode']");
	}
	else
	{
		var state = eval ( formName + "['" + property + "' + '.' + '" + attribute + "statecode']" );
		var country = eval ( formName + "['" + property + "' + '.' + '" + attribute + "countrycode']");
	}
	
	if( state.options[state.selectedIndex].value != "" )
	{
		for( var i = 0; i < country.options.length; i++ )
		{
			if( country.options[i].value == "US" )
			{
				country.options[i].selected = true;
				break;
			}
		}
	}
	else {
		country.options[0].selected = true;
	}
}

function nonuscountrysel( formName, property, attribute )
{
	if( property == null )
	{
		var state = eval ( formName + ".statecode" );
		var country = eval ( formName + ".countrycode");
	}
	else if ( attribute == null )
	{
		var state = eval ( formName + "['" + property + "' + '.' + 'statecode']" );
		var country = eval ( formName + "['" + property + "' + '.' + 'countrycode']");
	}
	else
	{
		var state = eval ( formName + "['" + property + "' + '.' + '" + attribute + "statecode']" );
		var country = eval ( formName + "['" + property + "' + '.' + '" + attribute + "countrycode']");
	}

	if( country.options[country.selectedIndex].value != "US" )
	{
		state.options[0].selected = true;
	}
}

//
// Set the browser's title
//
function setTitle(title)
{
	window.document.title = "RenewableEnergyWorld.com | " + title;
}

// clear out a field with a specified regexp
function clearit(expression, field) {
	widget = eval(field);
	if (widget.value.match(expression) != null)
	{
		return widget.value = "";
	}
}

function stripHtml(contentString) {
	var newContentString = contentString.replace(/(<([^>]+)>)/ig,"");
	return newContentString;
}

/**
 * Used to set a pages focus field, using id="focusfield" in a tag def.
 * Eg. <input type="text" id="focusfield">
 */
function focusField() {
	if(document.getElementById("focusField"))
	{
    	document.getElementById("focusField").focus();
    }
}

// Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	return LTrim(RTrim(value));	
}	


/*
 * Replaces certain characters with certain other characters.
 *
 * Based on filterChars.js, which was originally 
 * written by: David Lindquist (dave@gazingus.org)
 * Graciously brought to our attention by timdude@timdude.com
 * Modified for our use by matthew@re-access.com
 *
 */
String.prototype.filterChars = function()
{
	var formatted = trim(this);
	
	// all values following the \u are HEX Unicode values of special Unicode characters
	var AMPERSAND           = new RegExp( '&amp;', 'g' );
	var GREATERTHAN         = new RegExp( '&gt;', 'g' );
	var LESSTHAN            = new RegExp( '&lt;', 'g' );
	var SMART_QUOTE         = new RegExp( '(\u201C|\u201D|&ldquo;|&rdquo;)', 'g' );
	var SMART_APOSTROPHE    = new RegExp( '(\u2018|\u2019|&lsquo;|&rsquo;)', 'g' );
	var NB_SPACE            = new RegExp( '(\u00A0)', 'g' );

	// Make the replacements
	formatted = formatted.replace( AMPERSAND,         '&' );
	formatted = formatted.replace( GREATERTHAN,       '>' );
	formatted = formatted.replace( LESSTHAN,          '<' );
	formatted = formatted.replace( SMART_QUOTE,       '"' );
	formatted = formatted.replace( SMART_APOSTROPHE,  '\'' );
	formatted = formatted.replace( NB_SPACE,          '&nbsp;' );

	return formatted;
}


function getElement(resource)
{
	var element;
	
	if(typeof(resourceId) == "object")
		element = resource;
	else
	{
		if(document.getElementById(resource) != null)
			element = document.getElementById(resource);
	}	

	return element;
}

function toggleDisplay(resource)
{
	var element = getElement(resource);
	
	if(element.style.display == "none")
		element.style.display = "block";
	else
		element.style.display = "none";
}

function setStoryImageWidth(image, imageId, maxWidth)
{
	var img = new Image();
	img.src  = image;
	
	var imgWidth = img.width;

	var imgElement = document.getElementById(imageId);	

	if(imgWidth > maxWidth)
	 	imgElement.width = maxWidth;
	else
		imgElement.width = imgWidth;
 
	imgElement.style.display = "block";
}

function newsImagePop(contentId, contentTypeId)
{
	var url = "/rea/imagegallery?cid=" + contentId + "&ctid=" + contentTypeId;

	var newwindow=window.open(url, 'name', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=650,height=600,left = 200,top = 100');
	newwindow.focus();
}

function podcastListenPop(url) {
	
	iMyWidth = (window.screen.width/2) - (350 + 10);
	
	var newwindow=window.open(url, 'name', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=780,height=250,left = ' + iMyWidth + ',top = 100');
	newwindow.focus();	
}

function storyToolPop(url)
{
	//alert(url);
	var newwindow=window.open(url,'name','height=450,width=500');
	newwindow.focus();
}

function showLayer() {
	if(browserType == "iewin") {
		var selectElements = document.getElementsByTagName("select");
		
		for (var x = 0; x < selectElements.length; x++) {
			selectElements[x].style.visibility = "hidden";
		}
	}
}

// Son of Suckerfish deals with :hover in IE
sfHover = function() {
	var sfEls = document.getElementById("headerNav").getElementsByTagName("li");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
	
	var sfEls = document.getElementById("accountNav").getElementsByTagName("li");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" alhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" alhover\\b"), "");
		}
	}	
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

function hideLayer() {
	if(browserType == "iewin") {
		var selectElements = document.getElementsByTagName("select");
		
		for (var x = 0; x < selectElements.length; x++) {
			selectElements[x].style.visibility = "visible";
		}
	}
}

function generateTaLink(taId, taName)
{
	if(taId != -1)
	{
		for(var i = 1; i <= 4; i++)
		{
			var curLink = document.getElementById("urlLink" + i);
			var curLinkText = document.getElementById("urlText" + i);
			
			if(curLink.value == "" && curLinkText.value == "")
			{
				curLink.value = "http://www.renewableenergyworld.com/rea/partner?cid=" + taId;
				curLinkText.value = taName;
				break;
			}
		}
	}
}

function generateStoryAlert(storyType)
{
	if(storyType == 6 || storyType == 14)
	{
		var storyLink = document.getElementById("urlLink1");
		var storyIntro = document.getElementById("storyIntro");
		var storyBody = document.getElementById("storyBody");
		
		if(storyLink.value != "")
		{
			storyIntro.value = storyLink.value;
			alert("Intro link has been created");
		}
		else
		{
			storyIntro.value = "*** Add story link here ***";
			alert("Add alert link to intro");
		}
		
		storyBody.value = "<!-- leave this here -->";
	}
}

function registerDrop()
{	
	var arrowImg = new Image();
	arrowImg.src = "/images/template/orange-block-arrow.gif";
	
	var opaqueLayer = document.createElement('div');
	opaqueLayer.className = 'opaqueLayer';
	opaqueLayer.style.height = (screen.height + document.body.scrollHeight) + 'px';
	opaqueLayer.style.opacity = '.7';                      
	opaqueLayer.style.MozOpacity = '.7';                   
	opaqueLayer.style.filter = 'alpha(opacity=70)';
	opaqueLayer.id = "theOpaqueLayer";	

	document.body.appendChild(opaqueLayer);
	
	var popUp = document.getElementById('registerDrop');
	popUp.style.display = "block";
}


function createRegisterCookie()
{
	if(readCookie('showRegisterDrop') == null)
		createCookie('showRegisterDrop', "yes", 365);
}

function closeRegisterDrop()
{
	var drop = document.getElementById('registerDrop');
	var opaque = document.getElementById('theOpaqueLayer');
	
	drop.style.display = "none";
	document.body.removeChild(opaque);	
}


function processCountryChange(countrySelect)
{
	var stateBlock = document.getElementById('stateBlock');
	var regionBlock = document.getElementById('regionBlock');
	
	if(countrySelect.value == "US")
	{
		stateBlock.style.display = "block";
		regionBlock.style.display = "none";
	}
	else
	{
		stateBlock.style.display = "none";
		regionBlock.style.display = "block";	
	}
}


/*******************************************************************************
*	Creates a cookie
*******************************************************************************/
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+"="+value+expires+"; path=/";
}

/*******************************************************************************
*	Reads a cookie
*******************************************************************************/
function readCookie(name)
{
	var ca = document.cookie.split(';');
	var nameEQ = name + "=";
	
	for(var i = 0; i < ca.length; i++)
		{
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
		}
		
	return null;
}

/*******************************************************************************
*	Removes a cookie
*******************************************************************************/
function eraseCookie(name)
{
  createCookie(name, "", -1);
}

function easyCheckbox(checkBoxId)
{
	var checkBox = document.getElementById(checkBoxId);
	
	if(checkBox.checked == true)
		checkBox.checked = false;
	else
		checkBox.checked = true;
}

function adminFakeLinkPop(link, offset, jSessionId)
{
	var columnBase = link.parentNode;

	var popContainer = document.createElement('div');
	popContainer.className = 'adminFakeLinkPop';
	popContainer.style.marginTop = offset + "px";
	
	var popBody = document.createElement('div');
	popBody.className = "adminFakeLinkBody";

	var closeRow = document.createElement('p');
	closeRow.className = "closeFakeLinkPop";
	closeRow.onclick = function()
	{
		this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
	};
	
	closeRow.appendChild(document.createTextNode('X Close'));
	
	popBody.appendChild(closeRow);	
		
	var mainParagraph = document.createElement('p');
	mainParagraph.style.margin = "0";
	mainParagraph.style.textAlign = "center";
	
	mainParagraph.appendChild(document.createTextNode('To use this functionality you must upgrade your account.'));
	
	popBody.appendChild(mainParagraph);
	
	var upgradeLink = document.createElement('a');
	upgradeLink.href = '/rea/admin/upgradeaccount;jsessionid=' + jSessionId + "?accountSelectType=upgrade";
	upgradeLink.appendChild(document.createTextNode('Click Here to Upgrade!'));
	upgradeLink.className = 'popUpgradeLink';
	
	popBody.appendChild(upgradeLink);
	popContainer.appendChild(popBody);
	
	columnBase.appendChild(popContainer);
	
	return false;
}


var uploadImageCount = 0;

function addImageBlock(containerId)
{
	var container = document.getElementById(containerId);
	uploadImageCount++;

	// builds the input file block
	var mainFileDiv = document.createElement('div');
	var fileField = document.createElement('input');
	fileField.type = "file";
	fileField.name = "imageFile" + uploadImageCount.toString();
	fileField.size = "35";
	
	var textFileDiv = document.createElement('div');
	textFileDiv.appendChild(document.createTextNode("Image File"));
	
	mainFileDiv.appendChild(textFileDiv);
	mainFileDiv.appendChild(fileField);

	// builds the input text image credit block
	var mainCreditDiv = document.createElement('div');
	var creditField = document.createElement('input');
	creditField.type = "text";
	creditField.name = "imageCredit" + uploadImageCount.toString();	
	
	var textCreditDiv = document.createElement('div');
	textCreditDiv.appendChild(document.createTextNode("Image Credit"));
	
	mainCreditDiv.appendChild(textCreditDiv);
	mainCreditDiv.appendChild(creditField);
	
	
	// build the input text image caption block
	var mainCaptionDiv = document.createElement('div');
	var captionField = document.createElement('textarea');
	captionField.style.height = "50px";
	captionField.name = "imageCaption" + uploadImageCount.toString();
	
	var textCaptionDiv = document.createElement('div');
	textCaptionDiv.appendChild(document.createTextNode("Image Caption"));

	mainCaptionDiv.appendChild(textCaptionDiv);
	mainCaptionDiv.appendChild(captionField);
	
	// append the above form fields to the main div container in jsp
	container.appendChild(mainFileDiv);
	container.appendChild(mainCreditDiv);
	container.appendChild(mainCaptionDiv);
}

function getElementObj(elementResource)
{
	var elementObj = null;
	
	if(typeof(elementResource) == 'object')
		elementObj = elementResource;
	else
	{
		if(document.getElementById(elementResource) != null)
			elementObj = document.getElementById(elementResource);
	}
	
	return elementObj;
}

function toggleAdminBox(elementId, hasCompany)
{	
	var companyIsActive = parseInt(hasCompany);
	
	if(document.getElementById(elementId) == null)
	{
		if(companyIsActive > 0)
			elementId = 'navSec2';
		else
			elementId = 'navSec3';
	}
		
	var curBox;
	
	if(document.getElementById(elementId) != null)
	{
		for(var i = 1; i < 5; i++)
		{
			if(curBox = document.getElementById('navSec' + i) != null)
			{
				 curBox = document.getElementById('navSec' + i);
				 
				if(curBox.id != elementId) {
					//new Effect.SlideUp(curBox); 
					curBox.style.display = "none";
				}
				else {
					curBox.style.display = "block";
					//new Effect.BlindDown(curBox);
				}
			}
		}
	}
}

function appendActiveNavArrow(navId)
{
	if(document.getElementById(navId) != null)
		var navElement = document.getElementById(navId).style.backgroundColor = '#e2e2e2';
}

function zebraTables(tableId)
{
	var table = document.getElementById(tableId);
	var numRows = table.rows.length;
	
	if(numRows > 0)
	{
		for(var i = 0; i < numRows; i++)
		{
			var row = table.rows[i];
			if(i % 2 == 0)
				row.className = 'tableOddRow';
		}
	}
}

// Counts characters for a given form field
function characterCounter(textResource, maxCharLimit, displayResource)
{
	var textField = getElementObj(textResource);
	var displayContainer = getElementObj(displayResource);
	
	if(textField != null && displayContainer != null)
	{
		
		var numCharacters = textField.value.length;
		var charactersLeft = (maxCharLimit - numCharacters);
		
		//alert('Num characters left' + charactersLeft);
		if(charactersLeft <= 0)
		{
			charactersLeft = 0;
			textField.value = textField.value.substring(0, maxCharLimit);			
		}
		
		if(charactersLeft <= 50 && charactersLeft >= 25)
			displayContainer.parentNode.style.color = "#d1d32f";
		else
		if(charactersLeft < 25)
			displayContainer.parentNode.style.color = "#bd2432";
		else
			displayContainer.parentNode.style.color = "#000";
		
		displayContainer.innerHTML = charactersLeft;		
	}
}

function getHeightOffset()
{
	var scrOfY = 0;
	
	if(typeof(window.pageYOffset) == 'number')
		scrOfY = window.pageYOffset;
	else if(document.body && (document.body.scrollLeft || document.body.scrollTop))
		scrOfY = document.body.scrollTop;
	else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop))
		scrOfY = document.documentElement.scrollTop;
	
	return scrOfY;
}

function createOpaqueLayer()
{
	var opaqueLayer = document.createElement('div');
	opaqueLayer.className = 'opaqueLayer';
	opaqueLayer.style.height = (screen.height + document.body.scrollHeight) + 'px';
	opaqueLayer.style.opacity = '.5';                      
	opaqueLayer.style.MozOpacity = '.5';                   
	opaqueLayer.style.filter = 'alpha(opacity=50)';
	opaqueLayer.id = "theOpaqueLayer";	

	document.body.appendChild(opaqueLayer);
	return opaqueLayer;
}

function removeOpaqueLayer()
{
	var opaque = document.getElementById('theOpaqueLayer');
	document.body.removeChild(opaque);	
}

function IeSucksUrlDate()
{
	return new Date();
}

function toggleContentSearchItem(container) {
	if(container.className == "contentSearchItem")
		container.className = "contentActiveSearchItem";
	else
		container.className = "contentSearchItem";
}

function limitString(str, limit, delim) {
	var retStr = "";
	var strArray = str.split(delim);
	if(strArray.length > limit) {
		for(var i = 0; i < limit; i++) {
			retStr += strArray[i];
			if(limit - 1 != 1)
				retStr += delim;
		}
		retStr += "...";
	}
	else {
		retStr = str;
	}
	
	return retStr;
}

function changeFontSize(containerId, direction, defaultSize) {
	
	var container = document.getElementById(containerId);
	var fontStyle = container.style.fontSize;
	var fontSize = defaultSize;
	
	if(fontStyle != "") {
		var fontStyleArray = fontStyle.split('px');
		fontSize = fontStyleArray[0];
	}
	
	if(direction == 'up') {
		fontSize++;
	}
	else {
		fontSize--;
	}
	
	container.style.fontSize = fontSize + "px";	
}

function doSideNavBoxMore(listId, toggleSwitch, startIndex) {
	toggleSwitch = getElementObj(toggleSwitch);
	var list = document.getElementById(listId);
	var listElements = list.getElementsByTagName('a');
	var numListElements = listElements.length;
	var listElement;
	var writeShowLess = false;
	var showMoreText;
	
	for(var i = startIndex; i < numListElements; i++) {
		listElement = listElements[i];
		if(listElement.style.display == "block") {
			listElement.style.display = "none";
		}
		else {
			listElement.style.display = "block";
			writeShowLess = true;
		}
	}
	
	if(writeShowLess)
		showMoreText = "less options";
	else
		showMoreText = "more options";
	toggleSwitch.removeChild(toggleSwitch.childNodes[0]);
	toggleSwitch.appendChild(document.createTextNode(showMoreText));
	toggleSwitch.style.display = "block";
	
	return false;
}

function doSideNavBoxToggle(bodyId, toggleSwitch) {
	var boxBody = document.getElementById(bodyId);
	if(boxBody.style.display == "none") {
		boxBody.style.display = "block";
		// new Effect.SlideDown(boxBody);
		toggleSwitch.src = "/images/template/side-nav-arrow-down.jpg";
		toggleSwitch.alt = "Close";
		toggleSwitch.title = "Close";
	}
	else {
		boxBody.style.display = "none";
		// new Effect.SlideUp(boxBody);
		toggleSwitch.src = "/images/template/side-nav-arrow-right.jpg";
		toggleSwitch.alt = "Open";
		toggleSwitch.title = "Open";		
	}
}

function updateAndSubmit(fieldId, fieldValue, formId) {
	var fieldIds = fieldId.split(",");
	var fieldValues = fieldValue.split(",");
	var numFields = fieldIds.length;

	if(numFields > 0) {
		var form = document.getElementById(formId);
		for(var i = 0; i < numFields; i++) {
			document.getElementById(fieldIds[i]).value = fieldValues[i];
		}
		form.submit();
	}
}

function moveFeaturedContent(setSessionVar, action, direction) {
	var contentContainer = document.getElementById('featuredContent');	
	var newContainer = document.getElementById('featuredContent' + direction);
	var moveLink = document.getElementById('moveDownLink');
	
	if(direction == 'Up')
		moveLink.style.display = "block";
	if(direction == 'Down') {
		contentContainer.style.marginTop = "25px";
		moveLink.style.display = "none";
	}
		
	newContainer.appendChild(contentContainer);
	
	if(setSessionVar) {
		var params = 'action=' + action + '&ieSucks=' + IeSucksUrlDate();
		new Ajax.Request('/rea/generalajax', 
		{
			method: 'get',
			parameters: params,
			onSuccess: function(transport) {}
		});
	}	
}

var prevCellId;
function showContentDetails(contentId, headline, intro, link, imgSrc, imgSrcPath, xOffset, yOffset) {
	hideContentDetails(false);
	
	if(prevCellId != contentId) {
		// change quick icon image
		var quickViewIcon = document.getElementById('quickViewIcon' + contentId);
		quickViewIcon.src = '/images/template/quick-view-close.gif';
		var popContainer = document.createElement('div');
		popContainer.style.display = "none";
		popContainer.id = 'contentPopContainer';
		
		if(xOffset != '')
			popContainer.style.marginLeft = xOffset + "px";
		
		var topImgCorner = new Image(402, 21);
		topImgCorner.src = "/images/template/content-pop-top.png";
		var bottomImgCorner = new Image(402, 21);
		bottomImgCorner.src = "/images/template/content-pop-bottom.png";
		
		var backgroundContainer = document.createElement('div');
		backgroundContainer.id = 'contentPopBack';
		
		var contentContainer = document.createElement('div');
		contentContainer.id = 'contentPopContent';
		
		var popCloser = new Image(18, 18);
		popCloser.src = "/images/template/pop-closer.jpg";
		popCloser.alt = "Close";
		popCloser.title = "Close";
		popCloser.id = "popCloser";
		popCloser.style.cursor = "pointer";
		popCloser.onclick = new Function("hideContentDetails(true)");
		
		var headlineLink = document.createElement('a');
		headlineLink.href = link;
		headlineLink.target = "_blank";
		headlineLink.id = "headlineLink";
		headlineLink.appendChild(document.createTextNode(headline));
		
		var headlineContainer = document.createElement('div');
		headlineContainer.style.marginBottom = "10px";
		
		headlineContainer.appendChild(popCloser);
		headlineContainer.appendChild(headlineLink);
		
		contentContainer.appendChild(headlineContainer);
		
		var introP = document.createElement('p');
		introP.style.margin = "5px 0 0 0";
		if(intro != null && intro != "") {				
			introP.appendChild(document.createTextNode(intro + " "));				
		}
		
		var fullDetails = document.createElement('a');
		fullDetails.href = link;
		fullDetails.appendChild(document.createTextNode('Full Details'));
		fullDetails.style.fontWeight = "normal";
		fullDetails.target = "_blank";
		introP.appendChild(fullDetails);
		
		
		
		if(imgSrc != null && imgSrc != "") {
			var img = document.createElement('img');
			img.style.width = "120px";
			img.align = "right";
			img.style.margin = "0";
			img.style.padding = "0 0 5px 5px";					
			img.src = imgSrcPath + imgSrc;
			contentContainer.appendChild(img);
		}
		
		contentContainer.appendChild(introP);
		
		var divClear = document.createElement('div');
		divClear.className = "clearBoth";
		contentContainer.appendChild(divClear);				
		
		backgroundContainer.appendChild(contentContainer);
		
		popContainer.appendChild(topImgCorner);
		popContainer.appendChild(backgroundContainer);
		popContainer.appendChild(bottomImgCorner);
		
		var cellContainer = document.getElementById('cell' + contentId);
		cellContainer.appendChild(popContainer);
		
		popContainer.style.display = "block";
		prevCellId = contentId;
	}
	else
		prevCellId = null;
}

function hideContentDetails(setToNull) {
	if(document.getElementById('contentPopContainer') != null) {
		var popContainer = document.getElementById('contentPopContainer');
		popContainer.style.display = "none";
		document.getElementById('cell' + prevCellId).removeChild(popContainer);
		
		var quickViewIcon = document.getElementById('quickViewIcon' + prevCellId);
		quickViewIcon.src = '/images/template/icon-zoom.gif';
	}
	if(setToNull)
		prevCellId = null;
}

function setSorting(sortBy, sortHow) {
	var sortByField = document.getElementById('sortBy');
	var sortHowField = document.getElementById('sortHow');
	sortByField.value = sortBy;
	sortHowField.value = sortHow;
	var theForm = document.forms[1];
	
	theForm.submit();
}

function setSortingImg(sortBy, sortHow) {
	var upOrDown = "down";
	if(sortHow == "desc")
		upOrDown = "up";
		
	var imgId = "sort_" + sortBy + "_" + sortHow;	
	var img = document.getElementById(imgId);
	img.src = "/images/template/sort-arrow-" + upOrDown + "-on.png";
	img.onmouseout = "";			
}

function doToolTip(icon, tipId) {

	var tipContainer = document.getElementById(tipId);
	if(tipContainer.style.display == "none") {
		icon.src = "/images/template/question-icon-close.jpg";
		tipContainer.style.display = "block";
	}
	else {
		icon.src = "/images/template/question-icon-blue.jpg";
		tipContainer.style.display = "none";
	}
}


function getElementsByClassName(classname, node) {
	if(!node) node = document.getElementsByTagName("body")[0];
	var a = [];
	var re = new RegExp('\\b' + classname + '\\b');
	var els = node.getElementsByTagName("*");
	for(var i=0,j=els.length; i<j; i++)
	if(re.test(els[i].className))a.push(els[i]);
	return a;
}

function showToolTips(className, node) {
	
	var nodes = getElementsByClassName(className, node);

	var toolTipField = document.getElementById('toolTipField');
	var toolTipTextContainer = document.getElementById('toolTipText');
	var nodeDisplay;
	
	toolTipTextContainer.removeChild(toolTipTextContainer.childNodes[0]);
	if(toolTipField.value == 1) {		
		toolTipTextContainer.appendChild(document.createTextNode("Hide Tool Tips"));
		toolTipField.value = 2;
		nodeDisplay = "inline";
	}
	else {
		toolTipTextContainer.appendChild(document.createTextNode("Show Tool Tips"));
		toolTipField.value = 1;
		nodeDisplay = "none";
	}
	
	for(var i = 0; i < nodes.length; i++) {
		nodes[i].style.display = nodeDisplay;
	}
}

function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

function createPopupLayer(popProperties) {	
	
	var popContainerHolder = document.createElement('div');
	popContainerHolder.id = 'popLayerHolder';
	
	var popContainer = document.createElement('div');
	popContainer.className = 'popLayer';
	popContainer.id = 'popLayer';
	popContainer.style.marginTop = (getHeightOffset() + 200) + 'px';

	if(popProperties['width'] != null)
		popContainer.style.width = popProperties['width'];
	
	createOpaqueLayer();
	popContainerHolder.appendChild(popContainer);
	document.getElementById('pageContainer').appendChild(popContainerHolder);
	
	return popContainer;
}

function removePopupLayer() {
	if(document.getElementById('popLayerHolder') != null) {
		document.getElementById('pageContainer').removeChild(document.getElementById('popLayerHolder'));
		removeOpaqueLayer();
	}
}

function highlightTableRow(row, turnOn, bgColor) {

	var numCells = row.cells.length;
	if(turnOn == false)
		bgColor = 'transparent';
	
	for(var i = 0; i < numCells; i++)
		var cell = row.cells[i].style.backgroundColor = bgColor;	

}

function highlightElement(element, turnOn, bgColor) {
	if(turnOn == false)
		bgColor = 'transparent';	
	element.style.backgroundColor = bgColor;
}