/*******************************************************************************
   airnowtech.js
   Copyright 2005 Sonoma Technology, Inc. (STI); All Rights Reserved.
   Version 0.9.5 - 2005-07-11
   
   NOTE: If all goes well, this file will reach version 1.0 with the deployment
         of the AIRNow-Tech Enhancements and version 2.0 with the deployment of
         the AIRNow Response changes.  After version 2.0, please log any 
         changes to this file here.
*******************************************************************************/

// Conversion factors
var FEET_PER_METER = 3.2808399;
var METERS_PER_FOOT = 0.3048;

function openSiteSelector( opts ) {
	var url = "SiteSelector.cfm";
	if( opts ) url += "?" + opts;
	var selWindow = window.open( url, "SiteSelector", "toolbar=no,location=no,directories=no,status=no,resizable=yes,scrollbars=yes,left=5,top=5,width=600,height=500" );
}

function fireSiteSelector( sitelist, newListName ) {
	// Check every form in the current document
	for( var i = 0; i < document.forms.length; i++ ) {
		// If the form has a field called "selectorSiteList", stuff the sites into it
		if( document.forms[i].selectorSiteList ) {
			document.forms[i].selectorSiteList.value = sitelist;
			var len = sitelist.split(",").length;
			if( document.forms[i].selectorNewSiteListName && newListName ) {
				// If we're creating a new list, save the name
				document.forms[i].selectorNewSiteListName.value = newListName;
			}
			// If it's got the selector drop-down box, update the count of sites in the current selection
			if( document.forms[i].selectorSiteGroup ) {
				document.forms[i].selectorSiteGroup[0].text = "Current Selection ( " + len + " sites )";
				document.forms[i].selectorSiteGroup[0].selected = true;
				// If we're creating a new list, add the option to the drop-down box
				if( newListName ) {
					var sel = document.forms[i].selectorSiteGroup;
					sel[ sel.length ] = new Option( newListName, "new", true );
				}
			}
		}
	}
	// Or, if there's a custom JS handler defined, fire it
	if( window.updateSitesStatus ) {
		updateSitesStatus( sitelist );
	}
}

/**
 * GetSite( sAIRSCode )
 *
 * Navigate to site edit page for new site
 */
function GetSite(uAgencyID,sAIRSCode) {
	location.href = 'sitedetail.cfm?uAgencyID='+uAgencyID+'&sAIRSCode='+sAIRSCode;
}

function GetSiteParam(sAIRSCode,uParamID,uAgencyID,showDisabled) {
	location.href = 'sitedetail.cfm?sAIRSCode='+sAIRSCode+'&uParamID='+uParamID+'&uAgencyID='+uAgencyID+'&showDisabled='+showDisabled+'#SiteForm';
	//location.href = 'sitedetail.cfm?sAIRSCode='+sAIRSCode+'&uParamID='+uParamID+'#SiteForm';
}
function EnableEdit(value) {
	// location.href = "sitedetail.cfm?bEnableEdit="+value;
	// DP: This does the same thing as the line above, but it also preserves any URL variables
	var s = location.pathname;
	if(location.search.indexOf("bEnableEdit=") != -1) {
		s += location.search.replace(/bEnableEdit=[01]/,"bEnableEdit=" + value);
	} else {
		s += location.search ? location.search + "&bEnableEdit=" + value: "?bEnableEdit=" + value;
	}
	location.href = s + location.hash;
}

function ValidateIt(name,value,from,to){
	if((value < from)||(value > to)){
	alert(name);
	}	
}

function setAllQC() {
	// Save the form object in a shorter name
	var f = document.forms.QCCriteria;
	
	// If the QCCriteria form doesn't exist, then we're on the wrong page, so just terminate right here
	if( !f ) return;
	
	// Array of columns in the QCCriteria table
	var ar = [ 
		"iMaxSuspect", 
		"iMaxSevere", 
		"iRatesOfChange", 
		//"iMinNumBuddySites", 
		//"iBuddyCheckRange", 
		"iStickingCheckNumHours", 
		"iStickingCheckValue", 
		"iMinDrift" ];
	
	// Loop through the columns (as defined in the array above)
	for(var i=0; i < ar.length; i++) {
		try {
			// Get the value from the "all" box corresponding to the column we're looking at
			var v = f[ ar[i] + "_all" ].value;
			// If the box is empty, ignore it; otherwise...
			if( v ) {
				// Loop through the column of inputboxes and set the value to whatever's in the "all" box
				for(var j=0; j < f[ ar[i] ].length; j++)
					f[ ar[i] ][j].value = v;
				
				// ... and clear the "all" box when we're done
				f[ ar[i] + "_all" ].value = "";
			}
		} catch( e ) {
			// If there are any errors along the way, ignore them and try to keep on going
			continue;
		}
	}
}

/**
 * initSiteForm()
 * 
 * Sets up event handlers for various inputs in the site form
 */
function initSiteForm() {
	var f = document.forms['form'];
	// Handlers for meters/feet conversion
	f.iElevation.onchange = convert_feet2meters;
	f.iElevation.onkeyup = convert_feet2meters;
	f.iElevationmt.onchange = convert_meters2feet;
	f.iElevationmt.onkeyup = convert_meters2feet;
	
	// Handlers for degrees conversion
	f.rLatitudeDecimalDeg.onchange = convert_decimaldeg2deg;
	f.rLatitudeDecimalDeg.onkeyup = convert_decimaldeg2deg;
	f.rLongitudeDecimalDeg.onchange = convert_decimaldeg2deg;
	f.rLongitudeDecimalDeg.onchange = convert_decimaldeg2deg;
	if (f.iLatitudeDeg != null)
	{
		f.iLatitudeDeg.onchange = convert_Lat_deg2decimaldeg;
		f.iLatitudeDeg.onkeyup = convert_Lat_deg2decimaldeg;
	}
	if (f.iLatitudeMin != null)
	{
		f.iLatitudeMin.onchange = convert_Lat_deg2decimaldeg;
		f.iLatitudeMin.onkeyup = convert_Lat_deg2decimaldeg;
	}
	if (f.iLatitudeSec != null)
	{
		f.iLatitudeSec.onchange = convert_Lat_deg2decimaldeg;
		f.iLatitudeSec.onkeyup = convert_Lat_deg2decimaldeg;
	}
	if (f.iLongitudeDeg != null)
	{
		f.iLongitudeDeg.onchange = convert_Lon_deg2decimaldeg;
		f.iLongitudeDeg.onkeyup = convert_Lon_deg2decimaldeg;
	}
	if (f.iLongitudeMin != null)
	{
		f.iLongitudeMin.onchange = convert_Lon_deg2decimaldeg;
		f.iLongitudeMin.onkeyup = convert_Lon_deg2decimaldeg;
	}
	if (f.iLongitudeSec != null)
	{
		f.iLongitudeSec.onchange = convert_Lon_deg2decimaldeg;
		f.iLongitudeSec.onkeyup = convert_Lon_deg2decimaldeg;
	}
}

function convert_feet2meters() {
	document.forms['form'].iElevationmt.value = document.forms['form'].iElevation.value * METERS_PER_FOOT;
	return true;
}

function convert_meters2feet() {
	document.forms['form'].iElevation.value = document.forms['form'].iElevationmt.value * FEET_PER_METER;
	return true;
}

function convert_decimaldeg2deg() {
	// Get values
	var truelat = parseFloat( document.forms['form'].rLatitudeDecimalDeg.value );
	var truelon = parseFloat( document.forms['form'].rLongitudeDecimalDeg.value );
	var lat = Math.abs( truelat );
	var lon = Math.abs( truelon );
	// Convert Latitude
	var latD = parseInt( lat );
	var latM = (lat - latD) * 60;
	var latS = (latM - parseInt( latM ) ) * 60;
	if( lat != truelat ) latD = -latD;
	latM = parseInt( latM );
	latS = parseInt( latS );
	// Convert Longitude
	var lonD = parseInt( lon );
	var lonM = (lon - lonD) * 60;
	var lonS = (lonM - parseInt( lonM ) ) * 60;
	if( lon != truelon ) lonD = -lonD;
	lonM = parseInt( lonM );
	lonS = parseInt( lonS );
	// Convert NaN to empty strings
	if( isNaN( latD ) ) latD = "";
	if( isNaN( latM ) ) latM = "";
	if( isNaN( latS ) ) latS = "";
	if( isNaN( lonD ) ) lonD = "";
	if( isNaN( lonM ) ) lonM = "";
	if( isNaN( lonS ) ) lonS = "";
	// Set values in form
	document.forms['form'].iLatitudeDeg.value = latD;
	document.forms['form'].iLatitudeMin.value = latM;
	document.forms['form'].iLatitudeSec.value = latS;
	document.forms['form'].iLongitudeDeg.value = lonD;
	document.forms['form'].iLongitudeMin.value = lonM;
	document.forms['form'].iLongitudeSec.value = lonS;
}

function convert_deg2decimaldeg() {
	// Convert Latitude
	var latD = parseInt( document.forms['form'].iLatitudeDeg.value );
	var latM = parseInt( document.forms['form'].iLatitudeMin.value );
	var latS = parseInt( document.forms['form'].iLatitudeSec.value );
	var lat = Math.abs( latD ) + (latM / 60) + (latS / 3600);
	if( Math.abs( latD ) != latD ) lat = -lat;
	// Convert Longitude
	var lonD = parseInt( document.forms['form'].iLongitudeDeg.value );
	var lonM = parseInt( document.forms['form'].iLongitudeMin.value );
	var lonS = parseInt( document.forms['form'].iLongitudeSec.value );
	var lon = Math.abs( lonD ) + (lonM / 60) + (lonS / 3600);
	if( Math.abs( lonD ) != lonD ) lon = -lon;
	// Convert NaN to empty strings
	if( isNaN( lat ) ) lat = "";
	if( isNaN( lon ) ) lon = "";	
	// Update the values
	document.forms['form'].rLatitudeDecimalDeg.value = lat;
	document.forms['form'].rLongitudeDecimalDeg.value = lon;
}

function convert_Lat_deg2decimaldeg() {
	// Convert Latitude
	var latD = parseInt( document.forms['form'].iLatitudeDeg.value );
	var latM = parseInt( document.forms['form'].iLatitudeMin.value );
	var latS = parseInt( document.forms['form'].iLatitudeSec.value );
	var lat = Math.abs( latD ) + (latM / 60) + (latS / 3600);
	if( Math.abs( latD ) != latD ) lat = -lat;
	// Convert NaN to empty strings
	if( isNaN( lat ) ) lat = "";
	// Update the values
	document.forms['form'].rLatitudeDecimalDeg.value = lat;
}

function convert_Lon_deg2decimaldeg() {
	// Convert Longitude
	var lonD = parseInt( document.forms['form'].iLongitudeDeg.value );
	var lonM = parseInt( document.forms['form'].iLongitudeMin.value );
	var lonS = parseInt( document.forms['form'].iLongitudeSec.value );
	var lon = Math.abs( lonD ) + (lonM / 60) + (lonS / 3600);
	if( Math.abs( lonD ) != lonD ) lon = -lon;
	// Convert NaN to empty strings
	if( isNaN( lon ) ) lon = "";	
	// Update the values
	document.forms['form'].rLongitudeDecimalDeg.value = lon;
}

/**
 * initDataSummaryForm()
 * 
 * Sets up event handlers for various inputs in the Data Summaries form
 */
function initDataSummaryForm() {
	var i;
	var f = document.forms.dataForm;
	
	for( i=0; i < f.iMetric.length; i++ ) {
		f.iMetric[i].onchange = onDataSummaryMetricChange;
	}
	
	for( i=0; i < f.iResultBy.length; i++ ) {
		f.iResultBy[i].onclick = function() { updateDataSummaryForMetric(1); };
	}
	
	for( i=0; i < f.iOperator.length; i++ ) {
		f.iOperator[i].onclick = function() { updateDataSummaryForMetric(2); };
	}

	for( i=0; i < f.iCountOfCategory.length; i++ ) {
		f.iCountOfCategory[i].onclick = function() { updateDataSummaryForMetric(3); };
	}
}

function onDataSummaryMetricChange() {
	updateDataSummaryForMetric( this.value );
}

function updateDataSummaryForMetric( iMetric ) {
	//alert( "In updateDataSummaryForMetric( '" + iMetric + "' ); ..." );
	var f = document.forms.dataForm;
	if( ! f.iMetric[ iMetric - 1 ].checked ) f.iMetric[ iMetric - 1 ].checked;
	switch( iMetric ) {
		case "1":
			//alert( "case = 1" );
			f.iResultBy[2].checked = true;
			uncheckAll( "iOperator" );			
			uncheckAll( "iCountOfCategory" );
			enableTotalBy( 1 );
			break;
		case "2":
			//alert( "case = 2" );
			uncheckAll( "iResultBy" );
			f.iOperator[1].checked = true;
			uncheckAll( "iCountOfCategory" );
			enableTotalBy( 0 );
			break;
		case "3":
			//alert( "case = 3" );
			uncheckAll( "iResultBy" );
			uncheckAll( "iOperator" );
			f.iCountOfCategory[0].checked = true;
			enableTotalBy( 0 );
			break;
	}
}

function uncheckAll( el ) {
	//alert( "in uncheckAll( " + el + " ); ..." );
	var f = document.forms.dataForm;
	for( var i=0; i < f[el].length; i++ ) {
		f[el][i].checked = false;
	}
}

function enableTotalBy( bEnabled ) {
	var ar = document.forms.dataForm.iTotalBy;
	if( bEnabled ) {
		ar[0].disabled = false;
		ar[1].disabled = false;
	} else {
		ar[0].disabled = true;
		ar[1].disabled = true;
		ar[2].checked = true;
	}
}

function enableTotalByCount( bEnabled ) {
	var ar = document.forms.dataForm.iTotalBy;
	if( bEnabled ) {
		ar[2].disabled = false;
	} else {
		if( ar[2].checked ) ar[0].checked = true;
		ar[2].disabled = true;
	}
}


/**
 * initPollSummaryForm()
 * 
 * Sets up event handlers for various inputs in the Polling Summaries form
 */
function initPollSummaryForm() {
	document.forms.dataForm.uAgencyID.onchange = updateMetricOptionsForAgency;
	document.forms.dataForm.sPollMetric.onchange = updatePollSummaryForMetric;
	//updateMetricOptionsForAgency();
	updatePollSummaryForMetric();
}

function updatePollSummaryForMetric() {
	var sPollMetric = document.forms.dataForm.sPollMetric.value;
	switch( parseInt( sPollMetric ) ) {
		case 0:
		case 4:
		case 5:
		case 6:
		case 7:
		case 8:
			enableTotalByCount( 1 );
			break;
	
		case 1:
		case 2:
		case 3:
			enableTotalByCount( 0 );
			break;
	}
}

function updateMetricOptionsForAgency() {
	var uAgencyID = document.forms.dataForm.uAgencyID.value;
	var box = document.dataForm.sPollMetric;

	if( uAgencyID == "all" ) {
		box.options.length = 0;
		box.options[0] = new Option("Average minutes past hour delivered","1");
		box.options[1] = new Option("Percent of 'Good' data in OBS files","2");
		box.options[2] = new Option("Percent of OBS files delivered","3");
		//box.options[3] = new Option("Number of sites that failed automated QC","4");
		enableTotalByCount( 0 );
	} else if( uAgencyID == "0" ) {
		box.options.length = 0;
		box.options[0] = new Option("Choose an agency or select All in #1","0");
		box.options.selectedIndex = 0;
	} else if( uAgencyID != "0" && uAgencyID !="all" ) {
		//box.options[0] = new Option("Number of times each site failed QC","5");
		box.options[0] = new Option("Number of 'Missing' data values","6");
		box.options[1] = new Option("Number of 'Bad' data values","7");
		box.options[2] = new Option("Number of 'Good' data values","8");
		enableTotalByCount( 1 );
	}
}

/**
 * initForecastAccuracyForm()
 * 
 * Sets up event handlers for various inputs in the Forecast Accuracy stats page
 */
function initForecastAccuracyForm() {
	var f = document.forms.accuracyForm;
	f.uParamID.onchange = updateCompareToOptionsForParameter;
	for( var i = 0; i < f.iThreshold.length; i++ ) {
		f.iThreshold[i].onclick = function(e) { updateThreshold(); };
	}
	f.iThresholdAQI.onchange = function(e) { updateThresholdAQI(); };
	f.iThresholdAQI.onclick = function(e) { updateThresholdAQI(); };
	updateCompareToOptionsForParameter();
}

function updateCompareToOptionsForParameter(e) {
	var f = document.forms.accuracyForm;
	if( f.uParamID.value == 1 || f.uParamID.value == -1 ) {
		f.sDataType[0].checked = true;
		f.sDataType[1].disabled = true;
	} else {
		f.sDataType[1].disabled = false;
	}
}

function updateThreshold() {
	var f = document.forms.accuracyForm;
	if( getRadioValue( f.iThreshold ) == 0 ) {
		f.iThresholdAQI.focus();
	} else {
		f.iThresholdAQI.value = "";
	}
}

function updateThresholdAQI() {
	var f = document.forms.accuracyForm;
	setRadioByValue( f.iThreshold, 0 );
	updateThreshold();
}

function setRadioByValue( ar, v ) {
	for( var i=0; i < ar.length; i++ ) {
		if( ar[i].value == v ) {
			ar[i].checked = true;
		} else {
			ar[i].checked = false;
		}
	}
}

function getRadioValue( ar ) {
	for( var i=0; i < ar.length; i++ ) {
		if( ar[i].checked ) return ar[i].value;
	}
}


/**
 * DataExport()
 *
 * Pops up a new window, which will fill with the exported data. 
 */
function DataExport() {
	url = "DataExport.cfm";
	if( location.href.indexOf( "fss/" ) != -1 ) { url = "../" + url; }
	var exportWindow = window.open( url );
}

/**
 * doGraph()
 *
 * Pops up a new window, which will fill with the exported data. 
 */
function doGraph( nSites, format ) {
	if( nSites > 10 ) {
		alert('There are '+nSites+' sites selected containing data. For graphing, use no more than 10 data-containing sites.');
		return;
	}
	
	var url = "graph.cfm?GraphFormat=" + format;
	var graphWindow =  window.open( url, "Graph_Data", "toolbar=no,location=no,directories=no,status=no,resizable=yes,scrollbars=yes,left=5,top=5,width=700,height=600" );
}

/**
 * displayPopup()
 *
 * just pops up a window
 */
function displayPopup( page, title, width, height  ) {
	var selWindow = window.open( page, title, "toolbar=no,location=no,directories=no,status=no,resizable=yes,scrollbars=yes,left=5,top=5,width="+width+",height="+height );
}

function setSource(forecaster) {
	if( forecaster != 0 ) { 
		//alert('hi');
		document.accuracyForm.sSource.selectedIndex = 1; 
	}
}

function setForecaster(source) {
	if( source == "Guidance" ) { 
		//alert('hi');
		document.accuracyForm.uUserID.selectedIndex = 0; 
	}
}

function updateDateRange() {
	//check if iForecastday is -1
	//if it is hide dEnd input field
	//else show the field
	menu = document.getElementById( 'iForecastday' );
	endField = document.getElementById( 'endDate' );
	iCatEq = document.getElementById( 'iCatEq' );
	iCatID = document.getElementById( 'iCatID' );
	iAqiEq = document.getElementById( 'iAqiEq' );
	iAqi = document.getElementById( 'iAqi' );
	iParamID = document.getElementById( 'iParamID' );
	
	if( menu.options.selectedIndex == 0 ) {
		endField.style.display = 'none'; 
		iCatEq.disabled = 1; 
		iCatID.disabled = 1; 
		iAqiEq.disabled = 1; 
		iAqi.disabled = 1; 
		iParamID.disabled = 1;
	} else {
		endField.style.display = 'inline';
		iCatEq.disabled = 0;
		iCatID.disabled = 0;
		iAqiEq.disabled = 0; 
		iAqi.disabled = 0; 
		iParamID.disabled = 0;
	}
}

	
//clears all the checkboxes for a given list of checkboxes
function clearCheckBoxes( eleName ) {
	cbArray = document.getElementsByName( eleName );
	
	for( i=0; i < cbArray.length; i++ )
		cbArray[i].checked = false;
		
}
	
//get the numbered of checked items on a given checkbox list
function getNumCheckedItems( ele ) {
	numCheckedItems = 0;
	for( i=0; i<ele.length;i++ )
		if( ele[i].checked == true )
			numCheckedItems++;
	return numCheckedItems;
}

//get a string list of checked items on a given checkbox list
function getCheckedItems( ele ) {
	idList = "";
	for( i=0; i<ele.length;i++ ) {
		if( ele[i].checked == true ) {
			if( i != 0 )
				idList = idList + ',';
			idList = idList + ele[i].value;
		}
	}
	return idList;
}
	
//adds an option to a given select menu at the top of the menu
function addOption(selectbox,text,value ) {		
	var optn = document.createElement("OPTION");
	optn.text = text;
	optn.value = value;
	selectbox.options.add(optn,1);	
	selectbox.options[1].selected = true;
}

//removes option for a given select menu and the value of the item to remove
function removeOption( selectbox,value ) {
	id = 0;
	for(i=0; i< selectbox.options.length; i++ )
		if( selectbox.options[i].value == value ) {
			id=i;
			i=selectbox.options.length;
		}
	selectbox.remove(id);
}

//shows or hides a given block element, based on its current state
function showHideBlock( id ) {
	ele = document.getElementById( id );
	
	if ( ele.style.display != 'block' )
		ele.style.display = 'block';
	else
		ele.style.display = 'none';
}


// Check for privacy policy confirmation
//
function CheckPolicyAgree() {
var s = document.getElementById('PolicySpan');
var e = document.getElementById('PolicyError'); 	
	if ( document.getElementById('PolicyAgree').checked == false ) {
		s.style.border  = '1px solid red';
		e.style.visibility = 'visible';
	}
	return document.getElementById('PolicyAgree').checked;
}

