// Functions for AIRData web pages -- July 2001
// Changed form object references to be compatible with xhtml -- June 2007

// ---- Utility functions ----

// Return true if string 's' is empty.
function isEmpty(s) {
	return ((s == null) || (s.length == 0))
}

// Return true if character 'c' is a digit (0 .. 9).
function isDigit (c) {
	return ((c >= "0") && (c <= "9"))
}

// Return true if all characters in string 's' are digits
function isInteger (s) {
	if (isEmpty(s)) return true;  // empty value is OK
	for (var i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if (!isDigit(c)) return false;
	}
	return true;   // All characters are digits
}

// Remove leading zeroes from string 's'
function stripLeadingZero(s) {
	if (s.length < 2) return s;
	for (var i=0; i<s.length-1; i++) {
		if (s.charAt(i) != "0") break;
	}
	return s.substring(i,s.length);
}

// Remove characters from string 's' that are in string 'bag'.
function stripCharsInBag (s, bag) {
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

// Return the filename part of a URL (default URL is current page).
// host/path/thispage.html?a=b&c=d yields "thispage"
function pageName(url) {
	var i,j = 0;
	var s = (isEmpty(url)) ? window.location.href : url;
	var q = window.location.search;
	i = (isEmpty(q)) ? -1 : s.indexOf(q);
	if (i != -1) s = s.substring(0,i);
	i = s.lastIndexOf("/");
	j = s.lastIndexOf(".");
	if (j == -1) j = s.length;
	return (s.substring(i+1,j));
}

// Open (or reuse) a browser window to display a sample report/map.
// Width and height are optional.  Invoked by onclick event of an anchor.
// Returns false so the "calling" link does not open in the main window.
function showSamp(url,w,h) {
	if (isEmpty(url)) return true;  // no URL, can't open window, use anchor href
	if (isEmpty(w) || w<100) w = 337;
	if (isEmpty(h) || h<100) h = 410;
	var opt = "menubar,scrollbars,resizable,width=" + w + ",height=" + h;
	sampWin = window.open(url,"sampWin",opt);
	sampWin.focus();
	return false;
}

// Display a sub-page (e.g., map preferences) in a new browser window
// 'wid' pixels wide and 'hi' pixels high
function doNew(url,wid,hi) {
	if (isEmpty(url)) return;
	if ((isEmpty(wid)) || (wid == 0)) wid = 350;
	if ((isEmpty(hi)) || (hi == 0)) hi = 450;
	var opts = "resizable,scrollbars,width=" + wid + ",height=" + hi;
	var wname = pageName(url);
	var newWind = window.open(url,wname,opts);
	newWind.focus();
	return;
}

// Display a help page in a new browser window or in the current window
function doHelp(url,samewin) {
	if (isEmpty(url)) {  // build help URL from current page URL
		var wname = "h" + pageName();
		if (wname.length > 8) wname = wname.substring(0,8);
		url = "help/" + wname + ".html";
	}
	if (samewin == true) window.location.href = url;
	else {
		var wid = 500;
		var hi = 430;
		var opts = "resizable,scrollbars,menubar,toolbar,width=" + wid + ",height=" + hi;
		var helpWind = window.open(url,wname,opts);
		helpWind.focus();
	}
	return;
}

// ---- Geographic area functions ----

// Geographic area selection is passed from page to page as the
// "search" part of a URL -- the string following a "?", as in
// pagename.html?geotype~geocode~geoname
// where geotype = us (USA), re (EPA region), st (state),
//                 co (county), ms (MSA), zi (ZIP Code)
//       geocode is state abbrev, county FIPS code, etc.
//       geoname is state name, county name, etc.

// Note: These global are variables
var geotype = "";    // type of geographic area
var geocode = "";    // code(s) of the selected geo area(s)
var geoname = "Undefined";  // name(s) of selected geo area(s)

// Extract geographic area selection from the "search"
// part of a URL into global variables.  The search string
// contains up to four values separated by "~":
// 1 - type of geographic selection (us, re, st, co, ms, zi)
// 2 - geographic code of the selected area
// 3 - name of the selected area
// 4 - state abbreviation (used with county selection only)
// Parameter 's', if provided, is the search part only of a URL.
function getGeoSelection(s) {
	var selections = isEmpty(s) ? unescape(location.search) : unescape(s);
	if (selections.length > 1) {  // is there a search string?
		// strip the leading "?"
		selections = selections.substring(1,selections.length);
		selection = selections.split("~")
		geotype = selection[0];
		geocode = selection[1];
		geoname = selection[2];
		// If there is a 4th value, assume it is state abbreviation
		// to be appended to a county name in 'geoname'.
		if ((selection.length == 4)  && (!isEmpty(selection[3]))) // four values
			geoname += ", " + selection[3];
		return true;
	}
	return false;
}
// Execute the function "automatically" during page loading
getGeoSelection();

// Insert the name of the selected geographic area in a page
function getGeoName() {
	document.write(geoname);
}

// Check if a geographic area is selected, and if not,
// open the geographic selection page.
// Disable the check on local file system. (tad 12/13/01)
function checkGeoName(reportmap) {
	if ((geoname == "Undefined") && (location.protocol != "file:")) {
		alert("You need to select a geographic area before generating a " + reportmap)
		window.location.href = "geosel.html"
	}
	else return;
}

// Append geo selection values to a URL, and display the new URL
function toPage(url) {
	var i = url.indexOf("#");
	if (i == -1) i = url.length;
	var s = window.location.search;
	if (isEmpty(s)) s = "?" + geotype + "~" + escape(geocode) + "~" + escape(geoname);
	var u = url.substring(0,i) + s + url.substring(i,url.length);
	window.location.href = u;
	return false;
}

// Open the report/map selection page for the selected geographic
// area type. Use this function (primarily) in breadcrumbs. If no
// area type is selected, default to state. Parameter 'path' is a
// relative or absolute path to the location of reps??.html files.
function repmapPage(path) {
	var g = isEmpty(geotype) ? "st" : geotype;
	var url = "reps" + g + ".html";
	if (!isEmpty(path)) {
		if (path.substring(path.length-1,path.length) != "/") url = "/" + url;
		url = path + url;
	}
	toPage(url);
}

// ---- Form-handling functions (lists, radio buttons, etc.) ----

// Note: These are global variables
var optval = "";     // value(s) of selected list option(s)
var opttxt = "";     // text(s) of selected list option(s)

// Determine which options of a selection list are selected, and
// return the count. Store in global variable 'optval' the value
// of all selected options, delimited by 'dlimVal' (default: <space>).
// Store in global variable 'opttxt' the text of all selected options,
// delimited by 'dlimTxt' (default: <comma><space>). List options
// having no value are ignored. (This allows a list to have an entry
// like '<option value="">None of these'.)
function getOptions(list,dlimVal,dlimTxt) {
	optval = "";
	opttxt = "";
	var vdlim = " ";   // default option.value delimiter
	var tdlim = ", ";  // default option.text delimiter
	var n = 0;
	if (list) {  // can't do anything if the list doesn't exist
		if ((dlimVal) && (!isEmpty(dlimVal))) vdlim = dlimVal;
		if ((dlimTxt) && (!isEmpty(dlimTxt))) tdlim = dlimTxt;
		// fix for single-choice selection lists -
		// get first/only selected option
		var j = list.selectedIndex;
		for (var i=0; i<list.length; i++) {
			if (((i == j) || (list.options[i].selected)) && (!isEmpty(list.options[i].value))) {
				n++;
				if (n > 1) {
					optval += vdlim;
					opttxt += tdlim;
				}
				optval += list.options[i].value;
				opttxt += list.options[i].text;
			}
		}
	}
	return n;
}
// Returns the index of the selected radio button
// in group 'radioGroup'.
function whichButton (radioGroup) {
	if (radioGroup) {
		for (var i=0; i<radioGroup.length; i++) {
			if (radioGroup[i].checked)
				return i;
		}
	}
	return -1;
}

// Display a message about object 'theField' and give it focus.
// String 's' is the [error] message to display. If object 'theField'
// is a text input form field, select (highlight) it also.
function warnInvalid (theField, s) {
	if (theField) {
		theField.focus()
		if ("text textarea password file".indexOf(theField.type) > -1) {
			theField.select()
		}
	}
	alert(s)
	return false
}

// ---- Report/map functions ----

// Global variables
var SubmitOk = true;   // submit HTML form if true

// For AirData reports -- 
// -- Select all optional report columns
function selectAllCols() {
	var form = document.forms["rptform"];
	if (form) {
		for (var i=0; i < form.elements.length; i++) {
			if (form.elements[i].name == "fld" && form.elements[i].type == "checkbox") 
				form.elements[i].checked = true;
		}
	}
}
// -- Select default set of optional report columns
function selectDefaultCols() {
	var form = document.forms["rptform"];
	if (form) {
		for (var i=0; i < form.elements.length; i++) {
			if (form.elements[i].name == "fld" && form.elements[i].type == "checkbox") 
				form.elements[i].checked = form.elements[i].defaultChecked;
		}
	}
}

// For AirData reports -- transfers geographic selection code
// to form variables, and validates report column selections.
function doFormSubmit(form) {
	var i = 0;
	var f,s;
	SubmitOk = false;   // initialize to "do not submit" state
	if (isEmpty(geocode)) {
		alert("\n No geographic area selected - cannot generate a report");
		return;
	}
	form.geotype.value = geotype;
	form.geocode.value = geocode;
	s = unescape(location.search);
	form.geoinfo.value = s.substring(1,s.length);  // strip the leading '?'
	// Report generation programs need 'geoinfo' to generate the
	// "New Report Criteria" link on report pages.

	// Get pollutant and year selections from secondary forms
	// and store them in the main form.
	if ((form.pol) && (f=document.forms["polform"]) && (document.forms["polform"]["pols"])) {
		i = getOptions(f.pols);
		if (i > 0) form.pol.value = optval;
		if (i < 1) {
			alert("Please select a pollutant");
			f.pols.focus();
			return;
		}
		var p = (f.maxpols) ? f.maxpols.value : i;
		if (i > p) {
			alert("Please select no more than " + p + " pollutants" + 
						" (" + i + " are selected)");
			f.pols.focus();
			return;
		}
	}
	if ((form.year) && (f=document.forms["yearform"]) && (document.forms["yearform"]["years"])) {
		i = getOptions(f.years);
		if (i > 0) form.year.value = optval;
		else {
			alert("Please select a year");
			f.years.focus();
			return;
		}
	}

	// At least one report column must be selected
	for (i=0; i < form.elements.length; i++) {
		if (form.elements[i].name == "fld" && form.elements[i].checked) {
			SubmitOk = true;
			break;
		}
	}
	if (!SubmitOk) {
		for (i=0; i < form.elements.length; i++) {
			if (form.elements[i].name == "fld") {
				form.elements[i].focus();
				break;
			}
		}
		alert("\n No Report Column is selected \n\n"+
			"Please select at least one Column ");
	}
}

// Verify that MIN does not exceed MAX (emission amounts)
function smaller(min,max,label) {
	if (isEmpty(min.value) || isEmpty(max.value)) return true;
	var themin = parseFloat(stripCharsInBag(min.value," ,"));
	var themax = parseFloat(stripCharsInBag(max.value," ,"));
	if (themin > themax) {
		min.focus();
		alert(label + " minimum may not exceed " + label + " maximum ");
		return false;
	}
	return true;
}

// Insert geographic feature choice in selection list
// if geographic scope is smaller than USA (maps)
function classname() {
	if (geotype != "us")
		document.write('<option value="J"> Class I Area Names + Outlines</option>');
}

// ---- Comments submission (Sept. 2006) ----

// web comments form
function comments (form) {
  var i;
  if (form) {
    // set the form action
    form.action = "/cgi-bin/mail.cgi";
    // add commentor's name to email subject
    if (form.Name_of_commentor && form.Subject) form.Subject.value += " from "+form.Name_of_commentor.value;
		// store referring URL in a form field
		if (form.Previous_page) form.Previous_page.value = document.referrer;
    // adjust for staging environment
    if (form.tssms && document.URL.indexOf("staging.epa")>-1) {
      i = form.tssms.value.indexOf("m");
      if (i > -1) form.tssms.value = form.tssms.value.substr(0,i)+"d";
			i = form.Next.value.indexOf("http");
			if (i == -1) form.Next.value = "http://staging.epa.gov"+form.Next.value;
    }
    return true;
  }
  else return false;
} 

// web comments link 
// (onclick event handler, smt="send mail to" the comments address)
// 'thelink' parameter is not used
// split up the address in case spam bots are reading this...
function smt (thelink) {
	var a = "to:airdata";
	var b = "mail@epa";
	window.location.href = "mail" + a + b + ".gov";
	return false;  // don't follow the clicked link
}

// --- end of airdata.js ---
