var page_error = false;
var page_error_message = "";

// Parse a URL and returns an object with its components.
//   out.url = full URL
//   out.page = URL without query
//   out.dir = directory
//   out.query = query (all text following first question mark.
//   out.page = page (all text preceding first question mark)
function parse_url(inurl) {
  full_url = inurl;
  if ( inurl == undefined || inurl.length == 0 ) {
    full_url = document.URL;
  }
  out = new Object();
  out.url = full_url;
  out.page = full_url;
  out.query = "";
  // Find the query.
  pos = full_url.indexOf("?");
  if ( pos > 0 ) {
    out.page = full_url.substr(0,pos);
    out.query = full_url.substr(pos+1);
  }
  // Split the query.
  out.queries = out.query.split("?");
  if ( out.query.length == 0 ) out.queries.length = 0;
  // Find the directory.
  pos = out.page.length;
  while ( out.page.charAt(--pos) != "/" );
  out.dir = out.page.substr(0,pos);
  return out;
}

function show_url(inurl) {
  myurl = parse_url(inurl);
  document.writeln("<pre>");
  document.writeln("  URL: " + myurl.url);
  document.writeln(" page: " + myurl.page);
  document.writeln("  dir: " + myurl.dir);
  document.writeln("query: " + myurl.query);
  nq = myurl.queries.length
  if ( nq == 1 ) document.write("There is one query");
  else document.write("There are " + nq + " queries");
  if ( nq > 0 ) {
    document.writeln(":");
    for ( i=0; i<myurl.queries.length; ++i ) {
      document.writeln("       " + myurl.queries[i]);
    }
  } else {
    document.writeln(".");
  }
  document.writeln("</pre>");
}
//************************************************************************

// Class DocReader reads the document at a given URL.

// **** Private data.
//   ntry = # tries
//   tout = timeout in sec
//   dtout = timeout incrementin sec
//   dbg = debug level
//   err = error level
function DocReader() {
  // XMLhttpRequest or ActiveX.
  this.req = null;
  // Integer status of the last request.
  //   0 - success
  //   1 - request initiated
  //   2 - timeout
  //   3 - request not yet completed
  //   4 - read failed
  //   5 - read succeeded
  //   6 - not found (HTTP 404)
  //   7 - empty document
  this.stat = 0;
  // String describing the status of the last request.
  this.msg = "Unused";
// **** Public readonly data.
  // Text of the document.
  this.text = "";
  // URL for the last request.
  this.url = "";
// **** Public writeable data.
  // Timeout and timeout increment (sec)
  this.timeout = 1;
  this.dtimeout = 1;
  // Number of tries.
  this.ntry = 2;
  // Flag indicating level for debug messages.
  //   0 - none
  //   1 - all to document stream
  this.dbg = 0;
  // Flag indicating level for error messages.
  //   0 - none
  //   1 - brief to document stream
  //   2 - verbose to document stream
  //   3 - 2 + alert
  this.errlev = 0;
  // Flag indicating if read should be asynchronous;
  this.async = false;
 // **** Methods.
}

// Private method to process a read request.
DocReader.prototype._process_request = function () {
  // Check if request is "complete"
  if ( this.req.readyState == 4 ) {
    // only if "OK"
    if ( this.req.status == 200 ) {
      this.stat = 5;
      this.text = this.req.responseText;
    } else if ( this.req.status == 404 ) {
      this.stat = 6;
      this.msg = "Not found";
      this.text = "";
    } else {
      this.stat = 4;
      this.msg = "Read error";
      this.text = "";
    }
  } else {
    this.stat = 3;
    this.msg = "Not ready";
    this.text = "";
  }
}

// Private method to construct a read request.
DocReader.prototype._create_request = function () {
  prefix = "DocReader::_create_request: ";
  // Delete any earlier request.
  this.req = null;
  this.text = "";
  // branch for native XMLHttpRequest object
  if ( window.XMLHttpRequest ) {
    if ( this.dbg ) document.writeln(prefix + "Using XMLHttpRequest<br>");
    this.req = new XMLHttpRequest();
    if ( this.req != null ) {
      this.req.onreadystatechange = this._process_request;
      this.req.open("GET", this.url, this.async);
      this.req.send(null);
    } else {
      alert("Unable to create ActveX object!");
    }
  // branch for IE/Windows ActiveX version
  } else if ( window.ActiveXObject ) {
    if ( this.dbg ) document.writeln(prefix + "Using ActiveX<br>");
    this.req = new ActiveXObject("Microsoft.XMLHTTP");
    if ( req != null ) {
      this.req.onreadystatechange = this._process_request;
      this.req.open("GET", this.url, this.async);
      this.req.send();
    } else {
      alert("Unable to create ActveX object!");
    }
  }
}

// Private method to create and process a read request.
DocReader.prototype._create_and_process = function (tout) {
  this.msg = "Reading.";
  this.text = "";
  this._create_request();
  // If asynchonous, wait for the reponse.
  if ( this.async ) {
    now = new Date;
    starttime = now.getTime();
    stoptime = starttime + 1000*tout;
    done = 0;
    if ( this.dbg ) {
      document.writeln("Start: ");
      document.writeln(starttime);
      document.writeln("<br>");
      document.writeln("Stop: ");
      document.writeln(stoptime);
      document.writeln("<br>");
    }
    while ( ! done ) {
      if ( this.req.readyState == 4 ) {
        done = 1;
      }
      now = new Date;
      nowsec = now.getTime();
      if ( nowsec > stoptime ) {
        done = 1;
        this.stat = 2;
        this.msg = "Timeout.";
        if ( this.errlev ) {
          document.writeln("Timeout: ");
          document.writeln(nowsec);
          document.writeln("<br>");
        }
      }
    }
  } else {
    this._process_request();
  }
  if ( this.stat == 5 ) {
    this.stat = 0;
    this.msg = "Success";
  }
}

// Public method to read document.
DocReader.prototype.read = function (url) {
  this.stat = 1;
  this.url = url;
  this.text = "";
  mytout = this.tout;
  prefix = "DocReader::read: ";
  if ( this.dbg ) document.writeln(prefix + "Reading " + this.url + "<br>");
  for ( itry=0; itry<this.ntry; ++itry ) {
    if ( this.dbg ) document.writeln( prefix + "  Try " + itry + "<br>");
    this._create_and_process(url, mytout);
    if ( this.stat == 0 ) break;
    mytout += this.dtout;
  }
  if ( ! this.stat && ! this.text.length ) {
    this.stat = 7;
    this.msg = "Empty.";
  }
  if ( this.stat ) {
    if ( this.errlev > 0 ) {
      document.writeln("Read error: " + this.msg + "<br>");
      document.writeln("Doc: <a href=" + url + ">" + url + "</a><br><br>");
    }
    if ( this.errlev > 1 ) {
      document.writeln(url + "<br>");
      document.writeln("Ready state: ");
      document.writeln(this.req.readyState);
      document.writeln("<br>");
      document.writeln("Request status: ");
      document.writeln(this.req.status);
      document.writeln("<br>");
      document.writeln(this.req.status);
      document.writeln("<br>");
    }
    if ( this.errlev > 2 ) {
      alert("Read error: " + this.reqmsg + "   Doc: " + this.gurl);
    }
  }
  return this.text;
}

DocReader.prototype.toString = function() {
  var out = "DocReader";
  out += "<br>&nbsp;&nbsp;"
  out += "ntry = " + this.ntry + "\n";
  out += "<br>"
  return out;
}

// Function to fetch the AMI page describing a dataset.
//function ami_page(dsname) {
//  document.amiLinkForm.Command.value = document.amiLinkForm.Command.value+' -glite=\"SELECT logicalDatasetName WHERE logicalDatasetName=\''+dsname+'\'\"';
//  document.amiLinkForm.submit();
//}

