/***************************************
Purpose:  javascript library for mirador
By: Richard Strub and Tilak Joshi

$Id: mirador.js,v 1.91 2009/10/29 13:43:19 rstrub Exp $
-@@@ Mirador, Version: $Name: Patch-1_32_Perf_Checkout $
****************************************/

//////////////Variable Declarations

var Events_TT = 	"e.g. Katrina Hurricane, Dennis Tropical Storm";

var Location_TT = 	"gazetteer locations such as Kansas or Ice Shelf; OR <br>" +
			" a bounding box: <b>(minLat,minLon),(maxLat,maxLon)</b> (LL),(UR)" +
			" (Mirador will choose smallest area)  <br>OR " +
			" 80N 20s 120east 20wes OR<br>" +
			" a partial Lat/Lon: of 22n is equivalent to (22,180),(-90,-180)";

var TimeSpan1_TT = 	"e.g. 5-10-05, May 4th 2004<br>" +
			"An empty field defaults to 1/1/1978";

var TimeSpan2_TT = 	"e.g. 5-10-05, May 4th 2004<br>" +
			"An empty field defaults to Today:23:59:59";

var Keyword_TT = 	"<ul><li> an instrument: AIRS or a parameter: ozone, clouds</li>" +
                         "<li>'OR'  search: volcano OR sulfur </li>" +
                         "<li>'NOT' search use hyphen: trmm <b>-</b>csi</li></ul>";

var MODIS_TT = 		"MODAPS is sending metadata and browse products for MODIS L1 and atmospheres" +
			" data to the ECHO" +
			" to support cross data center" +
			" product search and ordering. (follow link)";

var ascii =		"01234567890123456789012345678901"  +
			" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"+
			"[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

var IllegalAscii = 	" #'$%;*+<>?@[\\]^`{}~";

var LegalAscii =	"&=01234567890123456789012345678901"  +
			" !\"(),-./0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ"+
			"_abcdefghijklmnopqrstuvwxyz";



//////////////Function Declarations


var current_download = "wget"; /* initial default download option (now that we have http based services*/

function showDownload(dl_option)
{
  document.getElementById(current_download + "_btn").className = "btn";        /* reset the option button to unhighlighted */
  document.getElementById(current_download).className = "downloadContent_hide";/* Hide download content */

  download = dl_option.substring(0, dl_option.lastIndexOf("_btn"));

  document.getElementById(download + "_btn").className = "btn_on";             /* highlight the option button up */
  document.getElementById(download).className = "downloadContent_show";        /* Show selected download content */

  current_download = download;                                                 /* store current selection */

}


function AFAPToCart(myint)
{
  document.getElementById("trigger").value = myint;
  document.forms.ResultsList.action = "cart.pl";
  document.forms.ResultsList.submit();
}


function AAFIAPBackToGranlist(aafiap)
{
  location.href += "&AAFIAP=Add All Files";
  location.replace; 
}


function checkHits()
{
  var the_form = window.document.ResultsList;
  var i;
  var selected = 0;
  var divTags = document.getElementsByTagName('div');
  var notags = 0;
  var TOTALITEMS = 0;
  var LBT_THRESHOLD = 0;
  for (i = 0; i < the_form.length; ++i) {
    if ((the_form[i].type == 'hidden') && (the_form[i].name == "LBT_THRESHOLD"))
      {
        LBT_THRESHOLD = the_form[i].value;
      }
  }
  for (tags = 0; tags < divTags.length; tags++) {
    //if (divTags[tags].getAttribute('class') == null)
    //getAttribute('class') does not work in IE, instead use className property
    if (!divTags[tags].className)
      {
        notags++;
      }
    else
      {
        if (divTags[tags].className.toLowerCase() == "datainfo")
          {
            break;
          }
        else
          {
            notags++;
          }
      }
  }
  for (i = 0; i < the_form.length; ++i) {
    if (the_form[i].type == 'checkbox')
      {
        if (the_form[i].checked)
          {
            //i = the_form.length;
            TOTALITEMS += parseFloat(divTags[notags+i].childNodes[0].childNodes[1].childNodes[1].nodeValue);
            selected = 1;
          }
      }
  }
  if (selected == 0)
    {
      alert("You must select at least one item.");
      return false;
    }
  else
    {
      if (TOTALITEMS >= LBT_THRESHOLD)
        {
          alert("The total number of files, " + TOTALITEMS + ", in your data sets selection has exceeded " + LBT_THRESHOLD + "\n"
                + "Please reduce the number of files by deselecting some of the data sets.");
        }
      else
        {
          document.forms.ResultsList.action = "granlist.pl";
          document.forms.ResultsList.submit();
        }
    }
}

function goToSlider()
{
  var the_form = window.document.ResultsList;
  var i;
  var selected = 0;
  for (i = 0; i < the_form.length; ++i) {
    if (the_form[i].type == 'checkbox')
      {
        if (the_form[i].checked)
          {
            i = the_form.length;
            selected = 1;
          }
      }
  }
  if (selected == 0)
    {
      alert("You must select at least one item.");
      return false;
    }
  else
    {
      document.forms.ResultsList.target = "_blank";
      document.forms.ResultsList.action = "slider.pl";
      document.forms.ResultsList.target = "_blank";
      document.forms.ResultsList.submit();
    }
}


function chunk_goToCart(mylink, windowname)
{
  var the_form = window.document.ResultsList;
  var i;
  var selected = 0;
  var url = "limit=150";
  var startTime;
  var endTime;
  // new stuff start
  for (i = 0; i < the_form.length; ++i) {
    //alert(the_form[i].name + " " + the_form[i].value );
    if (the_form[i].name == 'CGISESSID') {
      url = url + '&CGISESSID=' + the_form[i].value;
    }
    if (the_form[i].name == 'location') {
      url = url + '&location=' + the_form[i].value;
    }
    if (the_form[i].name == 'pointLocation') {
      url = url + '&pointLocation=' + the_form[i].value;
    }
    if (the_form[i].name == 'limit') {
      url = url + '&limit=' + the_form[i].value;
    }
    if (the_form[i].name == 'event') {
      url = url + '&event=' + the_form[i].value;
    }
    if (the_form[i].name == 'searchType') {
      url = url + '&searchType=' + the_form[i].value;
    }
    if (the_form[i].name == 'order') {
      url = url + '&order=' + the_form[i].value;
      // no order is provided at the collectionlist level.
      // we default to D, descending
    }
    if (the_form[i].name == 'dayNight') {
      url = url + '&dayNight=' + the_form[i].value;
    }
    if (the_form[i].name == 'endTime') {
      endTime = the_form[i].value;
    }
    if (the_form[i].name == 'startTime') {
      startTime = the_form[i].value;
    }
    if (the_form[i].type == 'checkbox') {
      if (the_form[i].checked) {
        url = url + '&shortnames=' + the_form[i].value;
        ++selected;
      }
    }
  }
  if (selected == 0) {
    alert("No items are selected.");
    return false;
  }
  url = "chunkclient.pl?order=D&trigger=4&" + url;
  if (url.lastIndexOf("Event") < 0) {
    chunkgranlist("AddToCart", url, startTime, endTime);
  }
  else { // do what we used to do -- disabling chunking for events from collectionlist page
    for (i = 0; i < the_form.length; ++i) {
      if (the_form[i].type == 'checkbox') {
        if (the_form[i].checked) {
          i = the_form.length;
          selected = 1;
        }
      }
    }
    if (selected == 0) {
      alert("No items are selected. (This processing can take some time with many granules)");
      return false;
    }
    else {
      button = document.getElementById("AddToCart");
      button.value = "With many granules this may take a while...";
      button.className = "btn_message";
    }

    document.forms.ResultsList.action = "cart.pl";
    document.forms.ResultsList.submit();

    if (! window.focus)return true;
    var href;
    if (typeof(mylink) == "string")
      href = mylink;
    else
      href = mylink.href;
    //window.open(href, windowname, "width=900, height=100, top=0");
    return true;
  }
}


function goToCart(mylink, windowname)
{
  var the_form = window.document.ResultsList;
  var i;
  var selected = 0;
  var divTags = document.getElementsByTagName('div');
  var notags = 0;
  var TOTALITEMS = 0;
  var MAXFILES = 0;
  for (i = 0; i < the_form.length; ++i) {
    if ((the_form[i].type == 'hidden') && (the_form[i].name == "MAXFILES"))
      {
        MAXFILES = the_form[i].value;
      }
  }
  for (tags = 0; tags < divTags.length; tags++) {
    //if (divTags[tags].getAttribute('class') == null)
    //getAttribute('class') does not work in IE, instead use className property
    if (!divTags[tags].className)
      {
        notags++;
      }
    else
      {
        if (divTags[tags].className.toLowerCase() == "datainfo")
          {
            break;
          }
        else
          {
            notags++;
          }
      }
  }
  for (i = 0; i < the_form.length; ++i) {
    if (the_form[i].type == 'checkbox')
      {
        if (the_form[i].checked)
          {
            //i = the_form.length;
            TOTALITEMS += parseFloat(divTags[notags+i].childNodes[0].childNodes[1].childNodes[1].nodeValue);
            selected = 1;
          }
      }
  }
  if (selected == 0)
    {
      alert("No items are selected. (When items are selected, processing can take some time with many granules)");
      return false;
    }
  else
    {
      if (TOTALITEMS >= MAXFILES)
        {
          alert("The total number of files, " + TOTALITEMS + ", in your data sets selection has exceeded " + MAXFILES + "\n"
                + "Only the first " + MAXFILES + " will be added to the cart.");
        }
      /*
      else
        {
          button = document.getElementById("AddToCart");
          button.value = "With many granules this may take a while...";
          button.className = "btn_message";
        }
      */
      // In case user hits back button:
      if (tI = document.getElementById('totalItemsId'))
        {
          the_form.removeChild(tI);
        }

      // Adding node to URL
      var inputNode = document.createElement("INPUT");
      inputNode.setAttribute("type", "hidden");
      inputNode.setAttribute("name", "totalItems");
      inputNode.setAttribute("id", "totalItemsId");
      inputNode.setAttribute("value", TOTALITEMS);
      the_form.appendChild(inputNode);
      document.forms.ResultsList.action = "cart.pl";
      document.forms.ResultsList.submit();
    }
}


function editSWitem(id, currentText, context, editor)
{
  href = "/cgi-bin/mirador/acceptSWedits.pl?id=" + id + "&currentText=" + currentText + "&context=" + context + "&editor=" + editor;
  window.open(href, "editingWindow", "width=1000, height=250, top=0");
}


function removeReq()
{
  var keyword = document.forms.dataEntryForm.keyword.value;

  if (keyword == "Required") {
    document.forms.dataEntryForm.keyword.value = "";
    return false;
  }
}


function validation()
{
  var keyword = document.forms.dataEntryForm.keyword.value;
  var location = document.forms.dataEntryForm.location.value;
  var startTime = document.forms.dataEntryForm.startTime.value;
  var endTime = document.forms.dataEntryForm.endTime.value;
  var event;
  if (document.forms.dataEntryForm.event) {
    event = document.forms.dataEntryForm.event.value;
  }
  var fields = new Array(keyword, location, startTime, endTime, event);
  var names = new Array("keyword", "location", "startTime", "endTime", "event");

  keyword = keyword.replace(/^\s*|\s*$/g, "");

  if (keyword == "" || keyword == "Required") {
    alert('Keyword must be entered');
    return false;
  }

  var loctest = /\.*\(\s*(\-*\d+.*\d*)\s*,\s*(\-*\d+.*\d*)\s*\)\s*,\s*\(\s*(\-*\d+.*\d*)\s*,\s*(\-*\d+.*\d*)\s*\)\.*/;
  if (loctest.test(location)) {
    var alertString = "";
    var boolean = false;
    if (Math.abs(RegExp.$1) > 90) {
      alertString=RegExp.$1 + " is supposed to be a latitude, and therefore between -90 and 90 \n";
      boolean = true;
    }
    if (Math.abs(RegExp.$3) > 90) {
      alertString += RegExp.$3 + " is supposed to be a latitude, and therefore between -90 and 90 \n";
      boolean = true;
    }
    if (Math.abs(RegExp.$2) > 180) {
      alertString += RegExp.$2 + " is supposed to be a longitude, and therefore between -180 and 180 \n";
      boolean = true;
    }
    if (Math.abs(RegExp.$4) > 180) {
      alertString += RegExp.$4 + " is supposed to be a longitude, and therefore between -180 and 180";
      boolean = true;
    }
    if (boolean) {
      alert(alertString);
      return false;
    }
  }

  for (i = 0; i < fields.length; ++i) {
    if (fields[i]) {
      for (k = 0; k < fields[i].length; k++) {
        l = fields[i].charAt(k);
        if (LegalAscii.lastIndexOf(l) < 0) {
          if (l.match("'")) {
            alert("Please use double quotes instead of single quotes");
          }
          else {
            alert("Char: " + l + " found in field: " + names[i] + " is not allowed");
          }
          return false;
        }
      }
    }
  }

  return true;
}


function validate_item(item)
{
  var strng = document.forms.ResultsList.email.value;
  var emailFilter = /^.+@.+\..{2,3}$/;
  if (!(emailFilter.test(strng))) {
    alert("ERROR: not a valid e-mail address");
    return false;
  }
  var strng = document.forms.ResultsList.phone.value;
  var phoneFilter = /^\(*[0-9]{0,3}\)*\s*[\.-]?[0-9]{3,5}\s*[\.-]?[0-9]{0,5}$/;
  //var phoneFilter=/^[0-9]{0,3}\s*[\.-]?[0-9]{3,5}\s*[\.-]?[0-9]{0,5}$/;
  var phoneFilter2 = /^[0-9]{5,10}$/;
  if (!( (phoneFilter.test(strng)) || (phoneFilter2.test(strng)) ) ) {
    alert("ERROR: not a valid phone number");
    return false;
  }
  var strng = document.forms.ResultsList.firstname.value;
  if (strng == "") {
    alert("ERROR: not a valid first name");
    return false;
  }
  var strng = document.forms.ResultsList.lastname.value;
  if (strng == "") {
    alert("ERROR: not a valid last name");
    return false;
  }
  return true;
}


function chunkgranlist(textid, granlistURLstart, starttime, endtime)
{
  var xmlHttpReq = null;
  var self = this;
  var counter = 0;
  var limit = 0;
  var n = 150;

  var form = window.document.ResultsList;
  for (i = 0; i < form.length; ++i) {
    if (form[i].type == 'button' || form[i].type == 'submit') {
       form[i].disabled = true;
    }
  }
  document.getElementById(textid).value= 'adding  files...';
  //Get xml http object and continue if it is returned
  if (self.xmlHttpReq = getXmlHttpObject()) {
    var granlistURL = granlistURLstart + "&startTime=" + starttime + "&endTime=" + endtime;
    var currStartTime;
    var currEndTime;
    //alert(endtime);
    // Place subsequent requests inside the readystatechange reference:
    self.xmlHttpReq.onreadystatechange = function bla() {
      if (self.xmlHttpReq.readyState == 4) {
        var doc = self.xmlHttpReq.responseXML;
        //alert(doc.getElementsByTagName("count")[0].childNodes[0].nodeValue);
        n = parseInt(doc.getElementsByTagName("count")[0].childNodes[0].nodeValue);
        //currStartTime = doc.getElementsByTagName("start")[0].childNodes[0].nodeValue;
        //currEndTime   = doc.getElementsByTagName("end")[0].childNodes[0].nodeValue;
        counter = counter + n;
        document.getElementById(textid).value = 'added ' + counter + ' files to cart';

        //If condition below is true, send out another ajax request using the SAME request object
        //alert("n:" + n + " limit:" + limit );
        if (n == 150 && limit < 20000/150) {
          //Everytime the object is ready send out another request if above criteria match
          // GranlistQuery.pm handles subsequent start and endtimes
          granlistURL = granlistURLstart;
          //alert("endtime from ajax:" + currEndTime );
          self.xmlHttpReq.open('GET', granlistURL, true);
          self.xmlHttpReq.onreadystatechange = bla;
          //self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
          self.xmlHttpReq.send(""); // if doing post you put parameters here
          ++limit;
        }
        else {
          // Now that we're done. lets go on to the cart page
          document.forms.ResultsList.action = "cart.pl";
          document.forms.ResultsList.submit();
        }
      }
    }
    //Send out the first request
    self.xmlHttpReq.open('GET', granlistURL, true);
    self.xmlHttpReq.send("asdfasdfasdfa"); // if doing post you put parameters here
    ++limit;
  }
}


function modifyLinks(procedure)
{
  var check = document.forms.ResultsList.simplerorreal.value;
  var test;
  var linksOnGranlistPage = ["descendingLink","ascendingLink","dayLink","nightLink", "bothLink",
                             "allLink","001","002","003","004",
                             "005","006","007","008","009",
                             "soacheckout","addselected","Next","Previous",">>",
                             "<<"];
  for (i = 0; i < 21; ++i) {
    if (procedure == 'add') {
      if (document.getElementById(linksOnGranlistPage[i])) {
        test = document.getElementById(linksOnGranlistPage[i]).href;
        if (test && !test.match(/simplerorreal/) ) {
          document.getElementById(linksOnGranlistPage[i]).href += '&simplerorreal=' + check;
          //alert("|" + linksOnGranlistPage[i] + "|");
        }
      }
    }
    else {
      if (document.getElementById(linksOnGranlistPage[i])) {
        test = document.getElementById(linksOnGranlistPage[i]).href;
        if (test && test.match(/simplerorreal/)) {
          document.getElementById(linksOnGranlistPage[i]).href =
            document.getElementById(linksOnGranlistPage[i]).href.replace(/&simplerorreal=on/g, "");
        }
      }
    }
  }
  /* for PageDisplay Section */
  for (i = 0; i < 200; ++i) {
    if (procedure == 'add') {
      if (document.getElementById(i)) {
        test = document.getElementById(i).href;
        if (test && !test.match(/simplerorreal/) ) {
          document.getElementById(i).href += '&simplerorreal=' + check;
        }
      }
    }
    else {
      if (document.getElementById(i)) {
        test = document.getElementById(i).href;
        if (test && test.match(/simplerorreal/) ) {
          document.getElementById(i).href =
            document.getElementById(i).href.replace(/&simplerorreal=on/g, "");
        }
      }
    }
  }
}


function DoSelectAll(toCheck, aname, series)
{
  if (aname == 'all') {
    var the_form = window.document.ResultsList;
    var i;
    for (i = 0; i < the_form.length; ++i) {
      if ( (the_form[i].type == 'checkbox') ) {
        if (the_form[i].name != 'simplerorreal') {
          if (the_form[i].disabled == false) {
            the_form[i].checked = toCheck;
          }
        }
      }
    }
  }
  else if (aname == 'Collchk') {
    var the_form = window.document.ResultsList;
    var i;
    if (toCheck)
    {
    for (i=0; i<the_form.length; ++i) {
      if ( (the_form[i].type == 'checkbox') ) {
           if (the_form[i].name != "simplerorreal") the_form[i].checked = true;
      }
    }
    }
   else
   {
    for (i=0; i<the_form.length; ++i) {
      if ( (the_form[i].type == 'checkbox') ) {
           if (the_form[i].name != "simplerorreal") the_form[i].checked = false;
      }
    }
   }
  }
  else {
    var the_Form = window.document.getElementById(aname);
    aname = aname + "_box";
    var the_form = window.document.ResultsList;
    var i;
    var j=1;
    for (i = 0; i < the_form.length; ++i) {
      if (the_form[i].id.lastIndexOf(aname) >= 0) {
        var childcb = aname + j;
        if ((the_form[i].type == 'checkbox') && (the_form[i].id == childcb)) {
          if (the_form[i].disabled == false) {
            the_form[i].checked = toCheck;
          }
        }
        ++j;
      }
    }
  }
  // This was done so that in the Services GUI columns, only the ones that
  // begin with $shortname are selected and deselected rather than everything
  // on the page
  if (series) {
    var the_form = window.document.ResultsList;
    var i;
    for (i = 0; i < the_form.length; ++i) {
      if ( (the_form[i].type == 'checkbox') ) {
        if (the_form[i].name.lastIndexOf(series) >= 0) {
          if (the_form[i].disabled == false) {
            the_form[i].checked = toCheck;
          }
        }
      }
    }
  }
}


function valueOfSelectWidget(idName) // new!!
{
  var opts = (document.getElementById(idName)).options;
  return opts[opts.selectedIndex].value;
}


function changedVersionView(verName) // new!!
{
  /*
    Called when the user changes the version being viewed.
  */
  var newURL = valueOfSelectWidget(verName);

  location.replace(newURL);
}


function GrabEventValue(idName)
{
  var opts = (document.getElementById(idName)).options;
  var textBox = document.getElementById('event');
  textBox.value = opts[opts.selectedIndex].value;
}


function changedView(idName) // new!!
{
  /*
    Called after the user changes either the "Sort by time" or "Day/night"
    options.  We refresh the list of granules.
  */
  var parts = location.href.split(/[?&]/);
  var newURL = parts[0];
  var params = [];
  var rex;

  if (idName == 'sortOrder') {
    rex = /^(?:order|dir|newtime|page|pageSet)=.*/i;
  }
  else {
    rex = /^(?:dayNight|dir|newtime|page|pageSet)=.*/i;
  }
  if (parts.length > 1) {
    for (var i = 1;  i < parts.length; ++i) {
      if (!rex.test(parts[i])) {
        params.push(parts[i]);
      }
    }
  }

  if (idName == 'sortOrder') {
    params.push("order=" + valueOfSelectWidget(idName));
  }
  else {
    params.push("dayNight=" + valueOfSelectWidget(idName));
  }
  params.push("page=1");
  params.push("pageSet=0");
  newURL += "?" + params.join("&");

  //  if (window.confirm('New URL = ' + newURL)) {
  location.replace(newURL);
  //  }
}


function changedCartView(idName) // new!!
{
  /*
    Called after the user changes either the "Sort by time" or "Day/night"
    options.  We refresh the list of granules.
  */
  var parts = location.href.split(/[?&]/);
  var newURL = parts[0];
  var params = [];

  if (valueOfSelectWidget(idName) == 'bytime' ) {
    params.push("trigger=1");
    newURL = "/cgi-bin/mirador/cartbytime.pl";
  }
  else {
    newURL = "/cgi-bin/mirador/cart.pl";
    //newURL.replace(/cartbytime.pl/ig,"cart.pl");
  }
  if (parts.length > 1) {
    /*
      Whenever we toggle asc/desc, we want to start over from page
      one. This means no newtime,page=1,pageSet=0
    */
    var rex = /^(?:trigger|dataSet|page)=.*/i;

    for (var i = 1;  i < parts.length; ++i) {
      if (!rex.test(parts[i])) {
        params.push(parts[i]);
      }
    }
  }
  else {
    /* original url to cart has nothing in url... */
    if (document.getElementById("id_CGISESSID")) {
      var local = document.getElementById("id_CGISESSID").value;
      params.push("CGISESSID=" + local);
    }
    if (document.getElementById("id_keyword")) {
      var local = document.getElementById("id_keyword").value;
      params.push("keyword=" + local);
    }
    if (document.getElementById("id_location")) {
      var local = document.getElementById("id_location").value;
      params.push("location=" + local);
    }
    if (document.getElementById("id_startTime")) {
      var local = document.getElementById("id_startTime").value;
      params.push("startTime=" + local);
    }
    if (document.getElementById("id_endTime")) {
      var local = document.getElementById("id_endTime").value;
      params.push("endTime=" + local);
    }
    if (document.getElementById("id_event")) {
      var local = document.getElementById("id_event").value;
      params.push("event=" + local);
    }
  }
  newURL += "?" + params.join("&");

  location.replace(newURL);
}


function swaptext(basecounter, maxcounter)
{
  if (document.forms.ResultsList.simplerorreal.checked) {
    for (c = basecounter; c <= maxcounter; ++c) {
      var org = "org" + c;
      var alias = "alias" + c;
      if (document.getElementById(alias)) {
        document.getElementById(org).innerHTML = document.getElementById(alias).innerHTML;
      }
    }
    modifyLinks('add');
  }
  else {
    for (c = basecounter; c <= maxcounter; ++c) {
      var org = "org" + c;
      var file = "file" + c;
      if (document.getElementById(file)) {
        document.getElementById(org).innerHTML = document.getElementById(file).innerHTML;
      }
    }
    modifyLinks('remove');
  }
}


// For versions

function popOpen(item)
{
  document.getElementById(item + " vers").style.display = "";
  var itemlink = item + " link";
  document.getElementById(itemlink).href = 'javascript: unPopOpen("' + item + '");';
}


function unPopOpen(item)
{
  document.getElementById(item + " vers").style.display = "none";
  var itemlink = item + " link";
  document.getElementById(itemlink).href = 'javascript: popOpen("' + item + '");';
}


// For the cart

function drop(item)
{
  document.getElementById(item).style.display = "";
  var itempic = item + "_pic";
  var itemlink = item + "_link";
  var itemlink2 = item + "_link2";
  document.getElementById(itempic).src = '../../open.gif';
  document.getElementById(itemlink).href = 'javascript: undrop("' + item + '");';
  document.getElementById(itemlink2).href = 'javascript: undrop("' + item + '");';
}


function undrop(item)
{
  document.getElementById(item).style.display = "none";
  var itempic = item + "_pic";
  var itemlink = item + "_link";
  var itemlink2 = item + "_link2";
  document.getElementById(itempic).src = '../../fold.gif';
  document.getElementById(itemlink).href = 'javascript: drop("'  + item + '");';
  document.getElementById(itemlink2).href = 'javascript: drop("' + item + '");';
}


// showGrans replaces the HTML contents of the (table) object whose id is
// dsId with the output generated by executing cartURL.
// This is used to provide scrollable display of the granules for a
// collection in the Mirador shopping cart.
function showGrans(dsId, cartURL)
{
  var xmlHttpReq = false;
  var self = this;
  // Mozilla/Safari
  if (window.XMLHttpRequest) {
    self.xmlHttpReq = new XMLHttpRequest();
  }
  // IE
  else if (window.ActiveXObject) {
    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (self.xmlHttpReq == null) {
    alert("Your browser does not support AJAX");
    return;
  }
  // Expect the document to have a tbody element with an id of dsId, and a
  // span element with an id of dsId concatenated with '_temp'.
  // Replace the innerHTML property of the span element, and then replace the
  // tbody element in the table with the new tbody element of the span element.
  // This dance is needed because IE does not allow the replacement of the
  // innerHTML property of a table.
  var dsId_temp = dsId + '_temp';
  var temp = document.getElementById(dsId_temp);
  temp.innerHTML = '<table><tbody id="' + dsId + '"><tr><td>&nbsp;</td></tr><tr><td>&nbsp;</td></tr><tr><td>&nbsp;</td></tr><tr><td>&nbsp;</td></tr><tr><td id="granCell"><p id="granCell"><font color="red">[The display of items can be slow when there are many items in the cart.]</font></p></td></tr><tr><td id="granCell"><p id="granCell">Loading granules...</p></td></tr><tr><td>&nbsp;</td></tr><tr><td>&nbsp;</td></tr><tr><td>&nbsp;</td></tr><tr><td>&nbsp;</td></tr><tr><td>&nbsp;</td></tr></tbody></table>';
  var tbody = document.getElementById(dsId);
  tbody.parentNode.replaceChild(temp.firstChild.firstChild, tbody);
  self.xmlHttpReq.onreadystatechange = function() {
    if (self.xmlHttpReq.readyState == 4) {
      //document.getElementById(dsId).innerHTML=self.xmlHttpReq.responseText;
      temp.innerHTML = '<table><tbody id="' + dsId + '">' + self.xmlHttpReq.responseText + '</tbody></table>';
      var tbody2 = document.getElementById(dsId);
      tbody2.parentNode.replaceChild(temp.firstChild.firstChild, tbody2);
      temp.innerHTML = '';
    }
  }
  self.xmlHttpReq.open('GET', cartURL, true);
  self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  self.xmlHttpReq.send(null);
}


// used for?

function pop(item)
{
  var tableid = item + " table";
  document.getElementById(tableid).style.display = "";
  var itemlink = item + " link";
  document.getElementById(itemlink).href = 'javascript: unpop("' + item + '");';
}


function unpop(item)
{
  var tableid = item + " table";
  document.getElementById(tableid).style.display = "none";
  var itemlink = item + " link";
  document.getElementById(itemlink).href = 'javascript: pop("' + item + '");';
}


// Send feedback message using ajax

function clearMessageBox(obj)
{
  if ( (obj.value == "Enter Feedback Here ...") || (obj.value == "Feedback Sent Successfully!") ) {
    obj.value = '';
  }
}


function checkAndSendMessage(obj)
{
  if ( (obj.value.match(/^\s*$/)) || (obj.value == "Enter Feedback Here ...") || (obj.value == "Feedback Sent Successfully") ) {
    obj.value = "Enter Feedback Here ...";
  }
  else {
    sendMessage(obj);
  }
}


function appquerystring(mytext)
{
  qstr = 'message=' + mytext;
  return qstr;
}


function sendMessage(obj)
{
  var xmlHttpReq = false;
  var strURL = 'sendmailAJAX.pl';
  var self = this;
  var mytext = obj.value;

  // Mozilla/Safari
  if (window.XMLHttpRequest) {
    self.xmlHttpReq = new XMLHttpRequest();
  }
  // IE
  else if (window.ActiveXObject) {
    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  }
  self.xmlHttpReq.open('POST', strURL, true);
  self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  self.xmlHttpReq.onreadystatechange = function() {
    if (self.xmlHttpReq.readyState == 4) {
      updatepage3(obj, self.xmlHttpReq.responseText, mytext);
    }
  }
  obj.value = 'Sending Message ...';
  obj.disabled = true;
  self.xmlHttpReq.send(appquerystring(mytext));
  //alert('sent message 3:' + mytext);
}


function getquerystring(mytext)
{
  qstr = 'message=' + mytext;
  return qstr;
}


function updatepage3(obj, str, mytext)
{
  var myRegEx = /ERROR/;
  if (!str.match(myRegEx)) {
    obj.value = str;
  }
  else {
    alert(str);
    obj.value = mytext;
  }
  obj.disabled = false;
}


// cmdGui ajax

function modifyColor(obj)
{
  obj.style.backgroundColor = '#CCFFFF';
}


function remodifyColor(obj)
{
  obj.style.backgroundColor = 'white';
}


function makeInput(obj, id, scid)
{
  var myid = '"' + id + '"';
  var myRegEx = /input/i;
  var myTextFieldName = id + "_text";
  var myText = obj.innerHTML;
  if (!myText.match(myRegEx)) {
    obj.innerHTML = "<input type='text' name='" + myTextFieldName + "' id='" + myTextFieldName + "' size=60 value='" + myText + "' />";
    myText = '"' + myText + '"';
    obj.innerHTML += "<input type='button' name='cancel' value='Cancel' onclick='doCancel(" +
      id + "," + myText + ");' />";
    obj.innerHTML += "<input type='button' name='Save' value='Save' onclick='doSave(" +
      id + "," + myid + "," + scid + "," + myText + ");' />";
  }
}


function doCancel(id, myText)
{
  id.innerHTML = myText;
}


function doSave(obj, id, scid, myText)
{
  var xmlHttpReq = false;
  var strURL = 'ajaxEnd.pl';
  var textName = id + "_text";
  var self = this;
  // Mozilla/Safari
  if (window.XMLHttpRequest) {
    self.xmlHttpReq = new XMLHttpRequest();
  }
  // IE
  else if (window.ActiveXObject) {
    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  }
  self.xmlHttpReq.open('POST', strURL, true);
  self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  self.xmlHttpReq.onreadystatechange = function() {
    if (self.xmlHttpReq.readyState == 4) {
      updatepage4(id, self.xmlHttpReq.responseText, myText, scid);
    }
  }
  self.xmlHttpReq.send(getquerystring(textName, id, scid));
}


function getquerystring(obj, id, scid)
{
  var textBox = document.getElementById(obj);
  qstr = 'new_field_val=' + textBox.value;
  qstr += '&field_name=' + id;
  qstr += '&scid=' + scid;
  document.getElementById(id).innerHTML = "<i>Saving ... </i>";
  return qstr;
}


function updatepage4(id, str, myText, scid)
{
  var obj = document.getElementById(id);
  var myRegEx = /ERROR/;
  if (!str.match(myRegEx)) {
    obj.innerHTML = "Saved.";
    obj.innerHTML = str;
    if (id == 'prodpageurl') {
      document.getElementById("prodimg").src = "http://mirador-ts2.gsfc.nasa.gov/check.png";
    }
  }
  else {
    alert(str);
    obj.innerHTML = myText;
  }
}


function showSearch()
{
  document.getElementById("advSearchOpt").style.display = "";
  document.getElementById("showSearchlink").onclick = hideSearch;
  document.getElementById("showSearchlink").innerHTML = "Hide Search Options";
}


function hideSearch()
{
  document.getElementById("advSearchOpt").style.display = "none";
  document.getElementById("showSearchlink").onclick = showSearch;
  document.getElementById("showSearchlink").innerHTML = "More Options";
}


function showmap()
{
  if (document.getElementById("location").value != '') {
    setSizeFromString(document.getElementById("location").value);
  }
  document.getElementById("rubberbandmap").style.display = "";
  document.getElementById("showmaplink").onclick = hidemap;
  document.getElementById("showmaplink").innerHTML = "Hide Map";
}


function hidemap()
{
  document.getElementById("rubberbandmap").style.display = "none";
  document.getElementById("showmaplink").onclick = showmap;
  document.getElementById("showmaplink").innerHTML = "Show Map";
}


function updateJarName(textid, jarNamerURL)
{
  var xmlHttpReq = false;
  var self = this;

  var newname = document.getElementById(textid).value;

  if (newname.lastIndexOf('.') < 0) {
    newname += '.jar';
  }

  if (newname.lastIndexOf('.jar') < 0) {
    newname = newname.substring(0, newname.lastIndexOf('.'));
    newname += '.jar';
  }
  else {
    newname = newname.substring(0, newname.lastIndexOf('.jar')+4);
  }

  jarNamerURL += "&newjarname=" +  newname;
  var oldname = document.getElementById('jar').href;
  index = oldname.lastIndexOf("/");
  prefix = oldname.substring(0, index);

  var displayname = newname;
  newname = prefix + "/" + newname

  jarNamerURL += "&oldjarname=" + oldname.substring(index+1);
  //alert(newname + " : " + jarNamerURL);
  document.getElementById('jar').href = newname;
  // Mozilla/Safari
  if (window.XMLHttpRequest) {
    self.xmlHttpReq = new XMLHttpRequest();
  }
  // IE
  else if (window.ActiveXObject) {
    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (self.xmlHttpReq == null) {
    alert("Your browser does not support AJAX");
    return;
  }

  self.xmlHttpReq.onreadystatechange = function() {
    if (self.xmlHttpReq.readyState == 4) {
      document.getElementById(textid).value = displayname;
    }
  }
  self.xmlHttpReq.open('GET', jarNamerURL, true);
  self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  self.xmlHttpReq.send(null);
}


function gldascheckboxes(shortname, balance)
{

  var meb_en = ["Surface_pressure", "Near_surface_air_temperature", "Near_surface_wind_magnitude", "Near_surface_specific_humidity",
               "Net_shortwave_radiation",   "Net_longwave_radiation", "Latent_heat_flux", "Sensible_heat_flux",
               "Average_surface_temperature", "Ground_heat_flux", "Surface_incident_shortwave_radiation",
               "Surface_incident_longwave_radiation", "Subsurface_runoff", "Surface_runoff", "Average_layer_soil_temperature"  ];


  var mwb_en = [ "Total_evapotranspiration", "Snow_water_equivalent", "Total_canopy_water_storage",
                "Average_layer_soil_moisture", "Snowmelt", "Snowfall_rate", "Rainfall_rate"  ];

  var all_en = new Array;
  all_en = all_en.concat(meb_en, mwb_en);

  var bname = shortname + "_" + balance + "_button";
  if (balance.match("BALANCE")) {
    var state = document.getElementById(bname).name;
    if (state == "Energy Balance") {
      for (i = 0; i < meb_en.length; ++i ) {
        var name = shortname + "_" + meb_en[i];
        if (document.getElementById(name)) {
          document.getElementById(name).checked = true;
        }
      }
      for (i = 0; i < mwb_en.length; ++i ) {
        var name = shortname + "_" + mwb_en[i];
        if (document.getElementById(name)) {
          document.getElementById(name).checked = false;
        }
      }
      document.getElementById(bname).value = "Water Balance";
      document.getElementById(bname).name = "Water Balance";
    }
    if (state == "Water Balance") {
      for (i = 0; i < mwb_en.length; ++i ) {
        var name = shortname + "_" + mwb_en[i];
        if (document.getElementById(name)) {
          document.getElementById(name).checked = true;
        }
      }
      for (i = 0; i < meb_en.length; ++i ) {
        var name = shortname + "_" + meb_en[i];
        if (document.getElementById(name)) {
          document.getElementById(name).checked = false;
        }
      }
      document.getElementById(bname).value = "Energy Balance";
      document.getElementById(bname).name = "Energy Balance";
    }
  }
  //alert(bname);
  if (balance.match("ALL")) {
    var state = document.getElementById(bname).name;
    if (state == "ALL") {
      document.getElementById(bname).name = "NONE";
      document.getElementById(bname).value = "Reset";
      for (i = 0; i < all_en.length; ++i ) {
        var name = shortname + "_" + all_en[i];
        if (document.getElementById(name)) {
          document.getElementById(name).checked = true;
        }
      }
    }
    else {
      document.getElementById(bname).name = "ALL";
      document.getElementById(bname).value = "Select All";
      for (i = 0; i < all_en.length; ++i ) {
        var name = shortname + "_" + all_en[i];
        if (document.getElementById(name)) {
          document.getElementById(name).checked = false;
        }
      }
    }
    //alert(document.getElementById(bname).name);
  }
}

/*
        AJAX Function to return an XmlHttpObject based on the browser used.
        Saves the work of having to rewrite these lines of codes everytime
        one uses ajax.
                -Taken from w3schools example, under suggestions. www.w3schools.com/Ajax/ajax_example_suggest.asp
        Pre: None
        Post: Returns new XmlHttpObject
*/

function getXmlHttpObject()
{
  var xmlHttp = null;
  try
    {
      //Create for Firefox, Opera and Safari
      xmlHttp = new XMLHttpRequest();
    }
  catch(e)
    {
      //Internet Explorer
      try
        {
          xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
      catch(e)
        {
          try
            {
              xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
          catch(e)
            {
              alert("Your browser does not support AJAX.");
              return false;
            }
        }
    }

  return xmlHttp;
}


function emptyCart(cartEmptyURL)
{
  var xmlHttpReq = false;
  var self = this;

  var doNotEmptyCartDiv = document.getElementById("doNotEmptyCart");
  var checkbox = document.getElementById("doNotEmptyCartCheckbox");
  if (checkbox && (checkbox.checked == false)) {
    if (window.XMLHttpRequest) {
      self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
      self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (self.xmlHttpReq == null) {
      alert("Your browser does not support AJAX, so the cart cannot be emptied.");
      return;
    }

    self.xmlHttpReq.onreadystatechange = function() {
      if (self.xmlHttpReq.readyState == 4) {
        doNotEmptyCartDiv.innerHTML = '<div id="alertBox" class="important" style="width:500px; margin:auto;">Your cart is now empty. (But your download options provided below are all still available)</div>';
      }
    }
    self.xmlHttpReq.open('GET', cartEmptyURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.send(null);
  }

  return true;
}


function dtabrowserDetect()
{
  var d, dom, ie, ie4, ie5x, moz, mac, win, lin, old, ie5mac, ie5xwin, op;

  d = document;
  n = navigator;
  na = n.appVersion;
  nua = n.userAgent;
  win = ( na.indexOf( 'Win' ) != -1 );
  mac = ( na.indexOf( 'Mac' ) != -1 );
  lin = ( nua.indexOf( 'Linux' ) != -1 );

  if (!d.layers) {
    dom = ( d.getElementById );
    op = ( nua.indexOf( 'Opera' ) != -1 );
    konq = ( nua.indexOf( 'Konqueror' ) != -1 );
    saf = ( nua.indexOf( 'Safari' ) != -1 );
    moz = ( nua.indexOf( 'Gecko' ) != -1 && !saf && !konq);
    ie = ( d.all && !op );
    ie4 = ( ie && !dom );

    /*
      ie5x tests only for functionality. ( dom||ie5x ) would be default settings.
      Opera will register true in this test if set to identify as IE 5
    */

    ie5x = ( d.all && dom );
    ie5mac = ( mac && ie5x );
    ie5xwin = ( win && ie5x );
  }
  if (!moz ) {
    if (document.getElementById('downThemAll')) {
      document.getElementById("downThemAll").style.display = "none";
    }
  }
}


function toggleDiv(divid)
{
  var label = '';
  label = document.getElementById("AdvLabel");
  if (document.getElementById(divid).style.display == 'none') {
    if (label) {
      label.innerHTML = "Basic Search";
    }
    document.getElementById(divid).style.display = 'block';
  }else{
    document.getElementById(divid).style.display = 'none';
    if (label) {
      label.innerHTML = "Advanced Search";
    }
  }
}


function osDetect()
{
  // This script sets OSName variable as follows:
  // "Windows"    for all versions of Windows
  // "MacOS"      for all versions of Macintosh OS
  // "Linux"      for all versions of Linux
  // "UNIX"       for all other UNIX flavors
  // "Unknown OS" indicates failure to detect the OS

  var OSName = "Unknown OS";
  if (navigator.appVersion.indexOf("Win") != -1) OSName = "Windows";
  if (navigator.appVersion.indexOf("Mac") != -1) OSName = "MacOS";
  if (navigator.appVersion.indexOf("X11") != -1) OSName = "UNIX";
  if (navigator.appVersion.indexOf("Linux") != -1) OSName = "Linux";
  if (OSName == "UNIX" || OSName == "Linux" ) {
    if (document.getElementById('jdownloader')) {
      // showing it for everyone now that is not the first option.
      //document.getElementById('jdownloader').style.display = 'none';
      //document.getElementById('jdownloader').style.visibility = 'hidden';
    }
    if (document.getElementById('java_download')) {
      // showing it for everyone now that is not the first option.
      // document.getElementById('java_download').innerHTML = '';
    }
  }
}
