
// MAKES an AJAX request for a url and calls proper function with the response
function makeXMLRequest(url, mode) {
  var httpRequest;

  if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
    if (httpRequest.overrideMimeType) {
      httpRequest.overrideMimeType('text/xml');
      // See note below about this line
    }
  }
  else if (window.ActiveXObject) { // IE
    try {
      httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
      try {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e) {}
    }
  }

  if (!httpRequest) {
    alert('Giving up :( Cannot create an XMLHTTP instance');
    return false;
  }
  httpRequest.onreadystatechange = function() {
     if (mode == "displayData")
         displayData(httpRequest);
     else if (mode == "createNav")
         createNav(httpRequest);
  }
  httpRequest.open('GET', url, true);
  httpRequest.setRequestHeader("Cache-Control", "no-cache"); // Is it really doing anything?
  httpRequest.send(null);

}

// DISPLAYS data reading from the xml response (as in data.xml)
function displayData(httpRequest) {
  if (httpRequest.readyState == 4) {
    if (httpRequest.status == 200) {
      var xmldoc = httpRequest.responseXML;  //Common AJAX stuff

var mydoc = xmldoc.documentElement;
var basins = mydoc.childNodes;
if (navigator.userAgent.indexOf("Firefox") != -1) // set nodelist counter for firefox as 1
   counter = 1;
else // for other browsers
   counter = 0;

//if (basins[0].nodeName == "basin")
  var catchments = basins[counter].childNodes; 
//else if (basins[1].nodeName == "basin")
//  var catchments = basins[1].childNodes; // assuming basins[1]=fitzroy for FF
//else
//  alert("No basin element found!");
var catchmentURL = unescape(getQryStr('catchment'));
document.getElementById("subheading").innerHTML = '<h3>' + catchmentURL + ' water quality monitoring site</h3>';
// 12-Aug-08 As main image is same as imagery...  var imgFile = 'images/main_' + catchmentURL.toLowerCase().replace(/\s+/g, '') + '.jpg';
var imgFile = 'images/imagery_' + catchmentURL.toLowerCase().replace(/\s+/g, '') + '.jpg'; // 12-Aug-08 As main image is same as imagery...
//alert(imgFile);
imgHtml = '';
//imgHtml += '<div style="float:left"><img name="mainimg" src="' + imgFile + '" border="0" width="399" height="565" alt="Satellite Imagery of ' + catchmentURL + '"></div>';
preloadImages(imgFile); // get other images (invoked on toggle) preloaded right now
var photoFile = 'images/photo_' + catchmentURL.toLowerCase().replace(/\s+/g, '') + '.jpg';
imgHtml += '<div style="float:right; vertical-align:top">';
imgHtml += '<p>Photo Image: ' + catchmentURL + ' sampling site<br />';
imgHtml += '<img src="' + photoFile + '" border="0" width="225" height="169" alt="Photo Image: ' + catchmentURL + ' sampling site">';
imgHtml += '<p>Click on a map type below to refresh the map image';
imgHtml += '<p><input type="button" name="btnLandTypes" value="Show Land Types map" style="width:180px;background-color:#5f9ea0" onclick="toggleImage(\'landtype\')">';
imgHtml += '<p><input type="button" name="btnSalinity" value="Show Salinity Threat map" style="width:180px;background-color:#5f9ea0" onclick="toggleImage(\'salinity\')">';
imgHtml += '<p><input type="button" name="btnImagery" value="Show Satellite Imagery" style="width:180px;background-color:#5f9ea0" onclick="toggleImage(\'imagery\')" disabled>';
imgHtml += '<p><b>Legend</b></p>';
imgHtml += '<div id="legend" style="width:225px;height:193px;overflow:auto"><img src="legend_imagery.jpg" border="0" width="225" height="193"></div>';
imgHtml += '</div>';
imgHtml += '<p><img name="mainimg" src="' + imgFile + '" border="0" width="470" height="553" alt="Satellite Imagery of ' + catchmentURL + '" style="border:solid;border-color:black;border-width:1px">';
document.getElementById("imgspace").innerHTML = imgHtml;
myHtml = '<p><b>All results for site ' + catchmentURL + '</b>';
for (i=counter;i<catchments.length;i++) {
//  if ( (catchments[i].nodeType == 1) && (catchments[i].getAttribute('id') == catchmentURL) ) {
    var sites = catchments[i].childNodes;
    myHtml += '<table width="690" cellpadding="2" cellspacing="0">';
    myHtml += '<tr style="background-color:#5f9ea0">';
    myHtml += '<th width="20%" style="border-width:1px;border-style:solid;border-color:white">Site Name</th><th style="border-width:1px;border-style:solid;border-color:white">Date</th><th style="border-width:1px;border-style:solid;border-color:white">Time</th><th style="border-width:1px;border-style:solid;border-color:white">Specific Conductivity (&micro;S/cm)</th><th style="border-width:1px;border-style:solid;border-color:white">pH</th><th style="border-width:1px;border-style:solid;border-color:white">Turbidity (NTU)</th><th style="border-width:1px;border-style:solid;border-color:white">TSS (mg/L)</th><th style="border-width:1px;border-style:solid;border-color:white">Total Nitrogen (mg/L)</th><th style="border-width:1px;border-style:solid;border-color:white">Total Phosphorus (mg/L)</th>';
    myHtml += '</tr>';
    for (j=counter;j<sites.length;j++) {
      if ((sites[j].nodeType == 1) && (sites[j].getAttribute('id').toLowerCase() == catchmentURL.toLowerCase()) ){
        myHtml += '<tr style="background-color:#cdcdcd">';
        myHtml += '<td style="border-width:1px;border-style:solid;border-color:white">' + sites[j].getAttribute('id') + '</td>';
        if (sites[j].hasChildNodes()) {
          var values = sites[j].childNodes;
          if (values[counter].getAttribute('value') == '') {
//            myHtml += '<td style="border-width:1px;border-style:solid;border-color:white">' +  values[0].getAttribute('value') + '</td>';
            myHtml += '<td colspan="8">Data currently not available for this site.</td>';
          } else
          for (k=0;k<values.length;k++) {
            if (values[k].nodeType == 1)
              myHtml += '<td style="border-width:1px;border-style:solid;border-color:white">' +  values[k].getAttribute('value') + '</td>';
          }
        }
        myHtml += '</tr>';
      }
    }
    myHtml += '</table>';
//  } //END if
} //END for
document.getElementById("xmldata").innerHTML = myHtml;

    } else { //END Common AJAX stuff
      alert('There was a problem with the request.');
    }
  }
}


// CREATES navigation for homepage reading from the xml response (as in data.xml)
function createNav(httpRequest) {
  if (httpRequest.readyState == 4) {
    if (httpRequest.status == 200) {
      var xmldoc = httpRequest.responseXML;  //Common AJAX stuff

if (navigator.userAgent.indexOf("Firefox") != -1) // set nodelist counter for firefox as 1
   counter = 1;
else // for other browsers
   counter = 0;
var mydoc = xmldoc.documentElement;
var basins = mydoc.childNodes;
var catchments = basins[counter].childNodes; 
/*****************************
if (basins[0].nodeName == "basin")
  var catchments = basins[0].childNodes; // assuming basins[0]=fitzroy for IE
else if (basins[1].nodeName == "basin")
  var catchments = basins[1].childNodes; // assuming basins[1]=fitzroy for FF
else
  alert("No basin element found!");
**************************/
navHtml = '<table cellpadding="2" cellspacing="0">';
for (i=counter;i<catchments.length;i++) {
    var sites = catchments[i].childNodes;
    var siteName = '';
    var prefix = 1;
    for (j=counter;j<sites.length;j++) {
      if ( (sites[j].nodeType == 1) && (siteName != sites[j].getAttribute('id')) ) {
        siteName = sites[j].getAttribute('id');
        navHtml += '<tr style="background-color:#cdcdcd">';
        navHtml += '<td style="border-width:1px;border-style:solid;border-color:black">' + '<a href="catchment.html?catchment=' + siteName + '">' + prefix++ + '. ' + siteName + '</a></td>';
        navHtml += '</tr>';
      }
    } // END for loop sites
} // END for loop catchments
navHtml += '</table>';
document.getElementById("navigation").innerHTML = navHtml;

    } else { //END Common AJAX stuff
      alert('There was a problem with the request.');
    }
  }
}


// GETS the query string parameter
function getQryStr(key)
{
  var regexS = "[\\?&]"+key+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var tmpURL = window.location.href;
  var results = regex.exec( tmpURL );
  if( results == null )
    return "";
  else
    return unescape(results[1]);
}


function preloadImages(mainfile) {
  var barefile = mainfile.substring(mainfile.indexOf("_"));
  if (document.images) {
    pic1 = new Image();
    pic1.src = 'landtype' + barefile;
    pic2 = new Image();
    pic2.src = 'salinity' + barefile;
    pic3 = new Image();
    pic3.src = 'imagery' + barefile;
    pic4 = new Image();
    pic4.src = 'legend_landtype.jpg';
    pic5 = new Image();
    pic5.src = 'legend_salinity.jpg';
    pic6 = new Image();
    pic6.src = 'legend_imagery.jpg';
  }
}


function toggleImage(str) {
  var fileurl = document.mainimg.src;
  var justfile = fileurl.substring(fileurl.lastIndexOf("_")+1, fileurl.lastIndexOf(".jpg"));
  var newfile = "images/" + str + "_" + justfile + ".jpg";
  document.mainimg.src = newfile;
  toggleLegend(str); //now change the legend accordingly
  toggleAlt(str); //now change the alt text of main image
  document.getElementById("btnImagery").disabled = false; //enable the default Imagery button
}


function toggleLegend(str) {
  legendHtml = '';
  switch(str) {
    case 'landtype':
      legendHtml += '<img src="legend_landtype.jpg" border="0" width="320" height="699">';
      break;
    case 'salinity':
      legendHtml += '<img src="legend_salinity.jpg" border="0" width="146" height="205">';
      break;
    case 'imagery':
      legendHtml += '<img src="legend_imagery.jpg" border="0" width="225" height="193">';
      break;
  }
  document.getElementById("legend").innerHTML = legendHtml;
}

function toggleAlt(str) {
  var catchmentURL = unescape(getQryStr('catchment'));
  switch(str) {
    case 'landtype':
      document.mainimg.alt = "Land Types map of " + catchmentURL;
      break;
    case 'salinity':
      document.mainimg.alt = "Salinity Risk map of " + catchmentURL;
      break;
    case 'imagery':
      document.mainimg.alt = "Satellite Imagery of " + catchmentURL;
      break;
  }
}


function transfer() {
/*  s = window.getSelection();
  var r1 = document.createRange();
  r1.setStartBefore(document.getElementById('xmldata'));
  r1.setEndAfter(document.getElementById('xmldata')) ;
  s.addRange(r1); 

  myDiv = document.getElementById('xmldata');
  dataTable = myDiv.innerHTML;
  dataTable.execCommand("Copy");
*/
    var selection, range, doc, win;
   node = document.getElementById('xmldata');
   if ((doc = node.ownerDocument) && (win = doc.defaultView) && (typeof win.getSelection != 'undefined') && (typeof doc.createRange != 'undefined') && (selection = window.getSelection()) && (typeof selection.removeAllRanges != 'undefined')) {
     range = doc.createRange();
     range.selectNode(node);
     selection.removeAllRanges();
     selection.addRange(range);
     t = window.getSelection();
   }
   else if (document.body && (typeof document.body.createTextRange != 'undefined') && (range = document.body.createTextRange())) {
     range.moveToElementText(node);
     range.select();
     t = document.selection.createRange();
     t.execCommand("Copy");
   } 
//  alert(dataTable);
}


function openwin(url){
  window.open(url,'_blank','height=600,width=500,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes');
}

