
function checkToggle(radioName, toggleList) {

	// match on variablecode + ',' to prevent D4.V2 being a match for D4.V22,D4.V23
	var checkList = toggleList + ',';
	var radios = document.form[radioName];
	for (var n = 0; n < radios.length; n++)
		if (radios[n].checked)
			var curradio = radios[n].value;

	for (var n = 1; n < 20; n++) {
		var select = document.form['B_' + n];
		if (select == null)
			break;
		var index = select.selectedIndex;
		var code = select.options[index].value;
	
		// match on variablecode + ',' to prevent D4.V2 being a match for D4.V22,D4.V23
		var testcode = code + ',';
		if (checkList.indexOf(testcode) > -1) {
			if (curradio != code) {
				toggleRadio(radioName, code);
				toggleDisplay(code, toggleList);
			}
			break;
		}
	}
}

/*
	Open/close a request form section, 
	toggle open/close button, 
	set value of hidden input with id=id and name=O_id to 'open' or 'close'
*/
function openCloseSection(action, id, count) {

	if (action == '')
		action = 'close';

	var openButton = id + '-open';
	var closeButton = id + '-close';

	if (action == 'open') {
		replaceClass(openButton, 'display-inline', 'displayoff');
		replaceClass(closeButton, 'displayoff', 'display-inline');
	}
	else {
		replaceClass(openButton, 'displayoff', 'display-inline');
		replaceClass(closeButton, 'display-inline', 'displayoff');
	}

	for (var n = 1; n < count + 1; n++) {
		var section = id + '-' + n;
		openCloseSection2(action, section);
	}

	var elem = (document.getElementById) ? document.getElementById(id) :
				((document.all) ? document.all(id) : null);
	if (elem != null)
		elem.value = action;
}

function openCloseSection2(action, section) {

	if (action == 'open')
		replaceClass(section, 'displayoff', 'displayon');
	else
		replaceClass(section, 'displayon', 'displayoff');
}

function replaceClass(id, oldclass, newclass) {

	var elem = (document.getElementById) ? document.getElementById(id) :
				((document.all) ? document.all(id) : null);
	if (elem == null)
		return;

	if (elem.className == null || elem.className == '')
		elem.className = newclass;
	else if (elem.className.indexOf(newclass) > -1)
		return;
	else if (elem.className.indexOf(oldclass) > -1)
		elem.className = elem.className.replace(oldclass, newclass);
	else
		elem.className += " " + newclass;
}

var sendTimeoutId = ' ';
var tabsend = false;
var mapchart = '';

function sendCancel() {
	sendMsgClear();
	if (window.stop)
		window.stop();
	else
		document.execCommand('Stop');
}

function sendMsgClear() {

	var elem = (document.getElementById) ? document.getElementById('send-msg') :
				((document.all) ? document.all('send-msg') : null);
	if (elem != null)
		elem.className = 'displayoff';

	elem = (document.getElementById) ? document.getElementById('export-text') :
				((document.all) ? document.all('export-text') : null);
	if (elem != null)
		elem.className = 'displayoff';

	if (!sendTimeoutId == ' ') {
		clearTimeout(sendTimeoutId);
		sendTimeoutId = ' ';
	}

}

function finishLoad() {
	formHasLoaded = true;
}

function sendMsgInit() {
	document.write(
	'<center><table id="send-msg" class="displayoff" cellspacing="0" cellpadding="0" width="550px">' +
	'<tr><td id="send-text">Processing Request, please wait for results...</td></tr>' +
	'<tr><td><div id="progress-bar" style="width:10px">&nbsp;</div></td></tr>' +
	'<tr><td align="center"><input type="button" value="Cancel Request" onclick="sendCancel()" class="button1" style="margin:10px"></td></tr>' +
	'<tr class="displayoff" id="export-text"><td>Click "Cancel Request" to clear this message when download is complete</td></tr>' +
	'</table></center>');
}

/*
	Call with action == 'reset' to reset the progress bar, otherwise the progress bar
	is incremented by 10px.
*/
function sendMsgProgressBar(action) {

	var elem = (document.getElementById) ? document.getElementById('progress-bar') :
				((document.all) ? document.all('progress-bar') : null);
	if (elem == null)
		return;

	var style = elem.getAttribute('style');
	if (style.width) {
		var width = elem.style.width;
		var len = width.substring(0, width.length - 2);
		len = parseInt(len) + 10;
		if (len > 300 || action == 'reset')
			len = 10;
		elem.style.width = len;
	}
	else {
		var attrs = style.split(';');
		var newstyle = '';
		for (var n = 0; n < attrs.length; n++) {
			var attr = attrs[n];
			if (attr == '')
				continue;
			if (attr.indexOf('width') == -1 && attr.indexOf('WIDTH') == -1) {
				newstyle += attr + ';';
				continue;
			}
		
			var index = attr.indexOf(':');
			var len = attr.substring(index + 2, attr.length - 2);
			var num = parseInt(len) + 10;
			if (num > 300 || action == 'reset')
				num = 10;
			len = num + '';
			newstyle += 'width:' + len + 'px;';
		}

		elem.setAttribute('style', newstyle);
	}

/*	Old method with dots...
	var node = sendMsgTextNode();
	if (node == null)
		return;

	var str = node.nodeValue;
	var len = str.length;
	if (str.charAt(len - 1) == ' ' || str.charAt(len - 1) == '\n')
		str = str.substring(0, len - 1);
	str = str + '.';
	node.nodeValue = str;
	sendTimeoutId = setTimeout('sendMsgUpdate()', 2000);
*/
}

var formHasLoaded = false;

function sendMsgSet(flag) {

	if ( !formHasLoaded ) {
		alert('The page has not finished loading. Please wait a moment and try again.');
		return false;
	}

	/* Tab or finder control clicked, do nothing, set by sendTab() */
	if (tabsend) {
		tabsend = false;
		return true;
	}

	var stdmsg = 'Processing Request, please wait for results...';
	var mapmsg = 'Processing Map Request, please wait for results...';
	var chartmsg = 'Processing Chart Request, please wait for results...';
	var stillmsg = 'Still Processing, Click "Cancel Request" to stop...';
	var textnode = sendMsgTextNode();

	/* Another Send already in process */
	if (sendTimeoutId != ' ') {
		if (textnode == null)
			return;
		textnode.nodeValue = stillmsg;
		window.scrollTo(0,0);
		return false;
	}
	
	/* hide error message */
	var errormsg = document.getElementById('error-table');
	if (errormsg == null)
		errormsg = document.getElementById('error-messages');
	if (errormsg != null )
		errormsg.className = 'displayoff';

	/* Start new data request Send */
	var elem1 = (document.getElementById) ? document.getElementById('send-msg') :
				((document.all) ? document.all('send-msg') : null);
	if (elem1 == null)
		return true;

	/* Unhide text related to export if doing an export */
	var elem2 = (document.getElementById) ? document.getElementById('export-option') :
				((document.all) ? document.all('export-option') : null);
	if (elem2 != null && elem2.checked) {
		var elem3 = (document.getElementById) ? document.getElementById('export-text') :
				((document.all) ? document.all('export-text') : null);
		elem3.className = '';
	}

	sendMsgProgressBar('reset');
	if (textnode != null) {
		if (mapchart != '') {
			if (mapchart == 'map')
				textnode.nodeValue = mapmsg;
			else if (mapchart == 'chart')
				textnode.nodeValue = chartmsg;
			mapchart = '';
		}
		else if (flag == null)
			textnode.nodeValue = stdmsg;
		else if (flag == 'map')
			textnode.nodeValue = mapmsg;
		else if (flag == 'chart')
			textnode.nodeValue = chartmsg;
	}
	elem1.className = '';

	window.scrollTo(0,0);
	sendTimeoutId = setTimeout('sendMsgUpdate()', 1000);

	return true;
}

function sendMsgTextNode() {
	var elem = (document.getElementById) ? document.getElementById('send-text') :
				((document.all) ? document.all('send-text') : null);
	if (elem == null)
		return null;
	return elem.childNodes[0];
}

function sendMsgUpdate() {

	sendTimeoutId = setTimeout('sendMsgUpdate()', 1000);
	sendMsgProgressBar('bump');
}

/*
	Called by the onclick handler of tabs so the sendMsgSet function knows a tab was clicked
*/
function sendTab() {
	tabsend = true;
}

function sendTab2(mapchartStr) {
	mapchart = mapchartStr;
}

function setfocus(win_name) {

	var win = window.open('', win_name);

	var width = (window.screen.availWidth * .9);
	var height = (window.screen.availHeight * .9);
	win.resizeTo(width, height);

	var x_pos = (window.screen.availWidth/2) - (width / 2);
	var y_pos = (window.screen.availHeight/2) - (height / 2);
	win.moveTo(x_pos, y_pos);

	win.focus();
}

var submitButton = '';
function submitGet() {
	return submitButton;
}
function submitSet(button) {
	submitButton = button.value;
}

/*	
	BUG NOTE:
	toggleBys() is used, via toggleOptions(), by radio buttons to change the selected by-variable in the Group By list.
	This is done because a radio button is selected that represents a by-variable that is mutually exclusive of 
	another by-varaible already selected in the listbox, e.g. two different age groups or state and msa.

	The manipulation of the list boxes and radio buttons is normally done by using the variable code e.g D42.V2, 
	for the radio button which is what is used in the group by list box.

	However, this link can be broken when the value on the radio button doesn't match the values for the options 
	in the list box. The result is that user can change radio button but not change selected by-variable in the 
	Group By list box. This feature has been used on radio buttons for variables which are not mutually exclusive, 
	e.g. state and regions.

	Actually this "feature" is normally created accidently when using radio buttons for finders. The .xsl code 
	automatically appends the level to the value used in the Group By listbox, e.g. D45.V2-level1. The programmer 
	has forgotten to use the level in the values for the radio button when creating his .xsl file.

	There is a problem although when one but not all the value for the radio buttons and options in the listbox match.  
	You end up with mixed behavior. Changing the radio buttons affects some selected by-variables in the Group By 
	listbox and others it does not affect. To make things more confusing the result is that normally the Group By 
	list box gets reset to the default value instead of the by-variable represented by the selected radio button.

	BUG FIX:
	If you ever get the mixed behavior, and don't want the link between the radio buttons and the Group By listbox, 
	then you can basically negate the code which causes the problem in the toggleBys() function by putting a blank 
	version of toggleBys() in your .xsl file. See std.xsl for example.

*/
function toggleBys(byselect, on, offList) {

	var offarr = offList.split(',');
	var found = false;
	var options = byselect.options;
	for (var n = 0; n < options.length; n++) {
		var option = options[n];
		if (!option.selected)
			continue;
		var value = option.value;
		for (var m = 0; m < offarr.length; m++) {
			if (value == offarr[m]) {
				found = true;
				option.selected = false;
			}
		}
	}

	if (!found)
		return;

	for (var n = 0; n < options.length; n++) {
		var option = options[n];
		var value = option.value;
		if (on == value) {
			option.selected = true;
		}
	}
}

function toggleDisplay(on, offList) {

	toggleDisplayLocal(on, offList)
	replaceClass(on, 'displayoff', 'displayon');

	var offarr = offList.split(',');
	// as times offList is really the complete list, including 'on'
	// don't turn 'on' off...
	for (var n = 0; n < offarr.length; n++) {
		if (on == offarr[n])
			continue;
		replaceClass(offarr[n], 'displayon', 'displayoff');
	}
}

// Placeholder. Will be overridden by datasets in the xsl request file as needed.
function toggleDisplayLocal(on, offList) {
}

/* 	BUG NOTE:
	see notes for toggleBys() above.

	in some cases user interface needs only to change display of controls in responce to change in radio buttons without this change
	getting reflected in the group by list.  the call to togglebys() is what reflects changes in group by list.
	new third parameter, doToggleBys, allows for call to toggleBys function to be optional.
*/
function toggleOptions(on, offList, doToggleBys) {

	toggleDisplay(on, offList);
	// loop through byvariables and toggle based on settings
	// look until no more found
	if (doToggleBys) {
		for (var n = 1; n < 11; n++) {
			var byselect = document.form["B_" + n];
			if (byselect == undefined)
				break;
			toggleBys(byselect, on, offList);
		}
	}
	loadFinder(on);
}

function toggleRadio(name, value) {

	var radios = document.form[name];
	for (var n = 0; n < radios.length; n++)
		radios[n].checked = (radios[n].value == value) ? true : false;
}

function togglePageBreaks(checked, tagname) {

	var classname = checked ? "pagebreak" : "pagebreakoff";
	var divs = document.getElementsByTagName(tagname);
	for (var n = 0; n < divs.length; n++) {
		var cl = divs[n].className;
		if (cl.indexOf("pagebreak") == 0)
			divs[n].className = classname;
	}
}


/*
	function stopRKey captures all keystrokes on the page and eats the enter keystroke.
	however, tabbing to a button and hitting enter still works.
	this keeps the form from getting submitted, or a navigation tab from being activated when
	user hits the enter key in a single line edit box.
*/

function stopRKey(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
  if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
} 

document.onkeypress = stopRKey; 



/*
		new functions for nasa
*/
function toggleDisplayMany(onList, offList) {

	toggleDisplayLocal(onList, offList)

	//turn off everything first
	var offarr = offList.split(',');
	// as times offList is really the complete list, including 'on'
	// don't turn 'on' off...
	for (var n = 0; n < offarr.length; n++) {
		replaceClass(offarr[n], 'displayon', 'displayoff');
	}

	//now turn on correct ones
	var onarr = onList.split(',');
	// as times offList is really the complete list, including 'off'
	// don't turn 'off' on...
	for (var n = 0; n < onarr.length; n++) {
			replaceClass(onarr[n], 'displayoff', 'displayon');
	}

	// this is hack for nasa dataset.

	var o_max = document.getElementById('O_max');
	var o_min = document.getElementById('O_min');
	var o_hi = document.getElementById('O_hi');
	var o_dataset_id = document.getElementById('dataset_id');
	if (onList.indexOf('C') > -1){
		if (o_dataset_id.value=='D60') {								    
			o_max.value='D60.V11';
			o_min.value='D60.V13';
			o_hi.value='D60.V15';
		}
		else {
			o_max.value='D61.V11';
			o_min.value='D61.V13';
			o_hi.value='D61.V15';
		}
	}
	else {
		if (o_dataset_id.value=='D60') {
			o_max.value='D60.V10';
			o_min.value='D60.V12';
			o_hi.value='D60.V14';
		}
		else {
			o_max.value='D61.V10';
			o_min.value='D61.V12';
			o_hi.value='D61.V14';
	 	}
	}


}

/* 	BUG NOTE:
	see notes for toggleBys() above.

	in some cases user interface needs only to change display of controls in responce to change in radio buttons without this change
	getting reflected in the group by list.  the call to togglebys() is what reflects changes in group by list.
	new third parameter, doToggleBys, allows for call to toggleBys function to be optional.
*/
function toggleOptionsMany(onList, offList, doToggleBys) {

	toggleDisplayMany(onList, offList);
	// loop through byvariables and toggle based on settings
	// look until no more found
	if (doToggleBys) {
		for (var n = 1; n < 11; n++) {
			var byselect = document.form["B_" + n];
			if (byselect == undefined)
				break;
			toggleBys(byselect, on, offList);
		}
	}
//	loadFinder(on);
}



function toggleSubordinates(id,subidList){

	var parent = (document.getElementById) ? document.getElementById(id) :
				((document.all) ? document.all(id) : null);
	if (parent != null) {

		var arr = subidList.split(',');
		for (var n = 0; n < arr.length; n++) {
			if (parent.checked == true) {
				// enable the input
				var elem = (document.getElementById) ? document.getElementById(arr[n]) :
							((document.all) ? document.all(arr[n]) : null);
				if (elem != null) {
					elem.disabled = false;
				
					// disable the input label if it exist
					var label_elem = (document.getElementById) ? document.getElementById(arr[n] + '_label') :
								((document.all) ? document.all(arr[n] + '_label') : null);
					if (label_elem != null) {
						replaceClass(arr[n] + '_label', 'disabled', 'enabled');
					}
				}
			}
			else {
				// disable the input
				var elem = (document.getElementById) ? document.getElementById(arr[n]) :
							((document.all) ? document.all(arr[n]) : null);
				if (elem != null) {
					elem.disabled = true;
				
					// disable the input label if it exist
					var label_elem = (document.getElementById) ? document.getElementById(arr[n] + '_label') :
								((document.all) ? document.all(arr[n] + '_label') : null);
					if (label_elem != null) {
						replaceClass(arr[n] + '_label', 'enabled', 'disabled');
					}
				}
			}
		}
	}
	return;
}



