// Functions for CICA web pages -- June 2003
// Aug 2006 (tad) - Change to DOM1 form element references

var cicalang;        // language of CICA web page

// ---- Utility functions ----

// Return true if string 's' is empty.
function isEmpty(s) {
  return ((s == null) || (s.length == 0))
}

// 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));
}

// ---- 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 are global 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 three values separated by "~":
// 1 - type of geographic selection (ba)
// 2 - geographic code of the selected area
// 3 - name of the selected area
// 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];
    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);
}

// Write in a page, where this function is invoked,
// the name of each selected geographic area as a link
// to a page containing information about monitoring sites
// in the area.
function getGeoNameLink() {
  if (geoname == "Undefined") {
    document.write(geoname);
    return;
  }
  var arealink = "";
  var gCodes = new Array;
  var gNames = new Array;
  gCodes = geocode.split(" ");
  gNames = geoname.split(",");
  var l = (isEmpty(cicalang)) ? "e" : cicalang;
  for (var i=0; i<gCodes.length; i++) {
    if (i>0) arealink += ", ";
    while (gNames[i].substring(0,1) == " ") {
      gNames[i] = gNames[i].substring(1,gNames[i].length);
    }
    arealink += "<a href=\"sites_" + gCodes[i] + "_" + l + ".html\">" + gNames[i] + "</a>";
  }
  document.write(arealink);
}

// Write in a page, where this function is invoked,
// a map that outlines each selected geographic area.
// Each outline is a link to a page that displays info
// about monitoring sites in the area.
function getGeoMapLink() {
  // This feature is disabled for Netscape 4
  if ((geoname == "Undefined") || (document.layers)) return;
  // Declare working vars
  var htm = "";
  var i = 0;
  var j = 0;
  // Get codes of the selected geographic areas
  var gCodes = new Array();
  gCodes = geocode.split(" ");
  // Define image map coords for all geographic areas
  var gAreas = new Array(14);
  gAreas[i++] = new Array('sd','shape="rect" coords="3,25,65,41"');
  gAreas[i++] = new Array('sd','shape="circle" coords="32,58,14"');
  gAreas[i++] = new Array('iv','shape="rect" coords="50,79,99,95"');
  gAreas[i++] = new Array('iv','shape="circle" coords="74,60,17"');
  gAreas[i++] = new Array('no','shape="rect" coords="128,113,175,120"');
  gAreas[i++] = new Array('no','shape="circle" coords="152,85,23"');
  gAreas[i++] = new Array('cj','shape="rect" coords="217,118,260,143"');
  gAreas[i++] = new Array('cj','shape="circle" coords="240,90,23"');
  gAreas[i++] = new Array('bl','shape="rect" coords="367,157,446,173"');
  gAreas[i++] = new Array('bl','shape="poly" coords="376,184,382,179,391,177,402,179,414,185,425,192,432,201,435,210,434,217,428,222,419,223,408,222,396,216,385,209,378,200,374,191,376,184"');
  gAreas[i++] = new Array('ot','shape="rect" coords="164,41,248,51"');
  gAreas[i++] = new Array('ot','shape="circle" coords="112,67,9"');
  gAreas[i++] = new Array('ot','shape="circle" coords="197,87,9"');
  gAreas[i++] = new Array('ot','shape="poly" coords="280,110,281,98,284,89,288,82,293,80,298,82,302,89,305,98,306,110,305,121,302,131,298,137,293,140,288,137,284,131,281,121,280,110"');
  // Get page language and set ALT text for image map
  var lang = (isEmpty(cicalang)) ? "e" : cicalang;
  var alt = (lang == "e") ? "See monitoring sites" : "Vea los sitios de la medida del agente contaminador del aire";
  // Define the containing div and base map image
  htm += '<div id="mapcontainer" style="position:relative; width:450px; height:260px;">\n';
  htm += '<img src="borderarea_' + lang + '_base.gif" width="450" height="260" border="0">\n';
  // Define image layers to show the location of each selected geographic area
  for (i=0; i<gCodes.length; i++) {
    htm += '<div id="Layer' + (i+1) + '" style="position:absolute; left:0; top:0; z-index:2;">';
    htm += '<img src="borderarea_' + lang + '_' + gCodes[i] + '.gif" width="450" height="260" border="0">';
    htm += '</div>\n';
  }
  // Define the top layer with image-map links to each selected geographic area
  htm += '<div id="LayerTop" style="position:absolute; left:0; top:0; z-index:10;">\n';
  htm += '<img src="http://www.epa.gov/epafiles/images/epafiles_misc_space.gif" width="450" height="260" border="0" usemap="#imap">\n';
  htm += '<map name="imap">\n';
  for (i=0; i<gCodes.length; i++) {
    for (j=0; j<gAreas.length; j++) {
      if (gAreas[j][0] == gCodes[i]) {
        htm += '<area ' + gAreas[j][1];
        htm += ' href="sites_' + gCodes[i] + '_' + lang + '.html"';
        htm += ' alt="' + alt + '" title="' + alt + '">\n';
      }
    }
  }
  htm += '</map></div>\n';
  // Close the container
  htm += '</div>';
  // Write the generated HTML
  document.write(htm);
}

// 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 u = url.substring(0,i) + window.location.search + url.substring(i,url.length);
  window.location.href = u;
}

// ---- 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;
}

// 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 CICA reports -- transfers geographic selection code
// to form variables, and validates report column selections.
function doFormSubmit(form) {
  var i = 0;
  var msg = "";
  var lang = (isEmpty(cicalang)) ? "e" : cicalang;
  SubmitOk = false;   // initialize to "do not submit" state

  // Check if a geographic area is selected, and if not,
  // open the geographic selection page.
  if (geoname == "Undefined") {
    msg = (lang == "s") ? "Usted necesita seleccionar un área geográfica antes de generar un informe" : "You need to select a geographic area before generating a report";
    alert(msg);
    window.location.href = "geosel_" + lang + ".html";
    return;
  }

  form.elements["geotype"].value = geotype;
  form.elements["geocode"].value = geocode;
  form.elements["geoinfo"].value = unescape(location.search);
  // Report generation programs need 'geoinfo' to generate the
  // "New Report Criteria" link on report pages.

  // Set the language to use for report generation
  if (form.elements["lang"]) {
    form.elements["lang"].value = lang;
  }

  // Get pollutant and year selections from secondary forms
  // and store them in the main form.
  var pol,polform,pols;
  pol = form.elements["pol"];
  polform = document.forms["polform"];
  if (polform) pols = polform.elements["pols"];
  if (pol && polform && pols) {
    i = getOptions(pols);
    if (i > 0) pol.value = optval;
    if (i < 1) {
      msg = (lang == "s") ? "Seleccione por favor un agente contaminador" : "Please select a pollutant";
      return warnInvalid(pols, msg);
    }
		var maxpols = polform.elements["maxpols"];
    var p = (maxpols) ? maxpols.value : i;
    if (i > p) {
			if (lang == "s") msg = "Seleccionar por favor no más de " + p + " agentes contaminadores (se seleccionan " + i + ")";
      else msg = "Please select no more than " + p + " pollutants (" + i + " are selected)";
      return warnInvalid(pols, msg);
    }
  }
  var year,yearform,years;
  year = form.elements["year"];
  yearform = document.forms["yearform"]
  if (yearform) years = yearform.elements["years"];
  if (year && yearform && years) {
    i = getOptions(years);
    if (i > 0) year.value = optval;
    else {
      msg = (lang == "s") ? "Seleccione por favor un año" : "Please select a year";
      return warnInvalid(years, msg);
    }
  }

  // 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;
      }
    }
    if (lang == "s") {
      alert("\n No se selecciona ninguna columna del informe \n\n"+
        "Seleccione por favor por lo menos una columna ");
    }
    else {
      alert("\n No Report Column is selected \n\n"+
        "Please select at least one Column ");
    }
  }
}
