// $Id$
window.onerror = function(message, url, lineNum) {
    alert("Error: '" + message + "'. At " + url + ", Line " + lineNum);
};

// assume browser is NOT internet explorer
var brzr = 'other'; 
var ie = false;
GetXmlHttpObject(); // to determine boolean value of ie variable
function GetXmlHttpObject(){
//alert("0 In GetXmlHttpObject() function.");
  var xmlHttp = false;
  if (window.XMLHttpRequest && !(window.ActiveXObject)) {
    try {
      // Firefox, Opera 8.0+, Safari
      xmlHttp = new XMLHttpRequest();
      //DO NOT reference httpRequest.overrideMimeType) - it will cause an ERROR
      brzr = "other"; // not IE but firefox, netscape, opera, etc.
      ie = false;
    }
    catch(e) {
      xmlHttp = false;
    }
  } 
  else if(window.ActiveXObject) {
    //Internet Explorer
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      brzr = "ie";
      ie = true;
    }
    catch(e) {
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        brzr = "ie";
        ie = true;
      }
      catch(e) {
        xmlHttp = false;
      }
    }
  }
  return xmlHttp;
};

function newAcroTable() {
//alert("newAcroTable() 0");
  var x; var r; var t;
  t = document.createElement("table");
  t.className = "acronyms center";
  t.title = "Where acronyms are embedded in the definition, click on the embedded acronym.";
  t.summary = "3 columns: the acronym, a list of applicable categories, the acronym expansion possibly followed by an explanation.";
  return t;
};

function cleanup() { // clean up after a service
  if (!(type = document.getElementById('q'))) {
    return;
  }
  //type = document.getElementById('q');
  type.value = '';
  type.focus();
};

function createHeader(table) {
//alert("createHeader(table) 0");
  if (table.rows.length > 1) {
    r = document.table.insertRow(0);
  } 
  else {
    r = document.createElement("tr");
  }
    c = document.createElement("th");
    c.className ="colhdrx";
    c.innerHTML = 'X';
  r.appendChild(c);
    c = document.createElement("th");
    c.className ="colhdracro";
    c.innerHTML = 'ACRONYM';
  r.appendChild(c);
    c = document.createElement("th");
    c.className ="colhdrtags";
    c.innerHTML = 'CONTEXT';
  r.appendChild(c);
    c = document.createElement("th");
    c.className ="colhdrexp";
    c.innerHTML = 'EXPANSION';
  r.appendChild(c);
  if (ie) { 
    var h = table.createTHead();
    h.appendChild(r);
    table.appendChild(h);
    return h;
  } 
  else {
    table.appendChild(r);
    return r;
  }
};

function unqt(x) { // undo all &quot; codes
//alert("unqt() 0");
  while (x.match(/&quot;/) == '&quot;') {
    x = x.replace(/&quot;/,'\"'); 
  }
  return x;
};

function striptags( instr ) {
  outstr = instr.replace(/<[^>]+>/g,"");
  return outstr;
};

function anchFocusColor(element) {
  element.style.backgroundColor="#FFFF33"
};

function anchBlurColor(element) {
  element.style.backgroundColor="#99CCCC"
};

function displayRef(xmlHttp){ 
//alert("displayRef() 0:\n Server readyState: "+xmlHttp.readyState);
  try {
    if (xmlHttp.readyState == 4) {
      try {
        if (xmlHttp.status == 200) {
          var result = xmlHttp.responseText;
          result = unqt(result);
          n = result.indexOf("<b>");
          if( n >= 0 && n <= 10 ) {
            alert(striptags(result));
          } 
          else {
            var rowHTML = new Array();
            var theDiv = document.getElementById("theDiv");
            var theTable;
            if( theDiv.getElementsByTagName("table").length === 0 ) {
              theTable = newAcroTable();
              createHeader(theTable);
              theDiv.appendChild(theTable);
              cleanup();
            } 
            else {
              theTable = theDiv.getElementsByTagName("table")[0];
            }
            if (ie) {
              var h = document.createElement("tbody");
              theTable.appendChild(h);
            }
            rowHTML = result.split('\n');
            for (i = 0; i < rowHTML.length - 1; i++) { // decrement because \n ends rows
              n = rowHTML[i].indexOf("<b>");
              if ( n >= 0 && n <= 10 ) { // if there's a message from php, show it
                alert(striptags(result));
                continue;
              } 
              var datum = new Array();
              datum = rowHTML[i].split("\t");  // always 4 items
              if (item = document.getElementById(datum[1])) { // if the word is already in the list
                continue;
              } 
              var r = document.createElement("tr");
                var c = document.createElement("td");
                c.className = "tdacrymckbx";
                  var b = document.createElement("input");
                  b.type = "checkbox";
                  b.id = "x"+datum[1];  // word_id or href
                  b.value = "box";
                  b.className = "acrymckbx"; // syntax verfied for IE
                c.appendChild(b);
              r.appendChild(c); // checkbox
                c = document.createElement("td");
                c.className = "tdacro";
                  var a = document.createElement("a");
                  a.className = "acrymFind";
                  a.addEventListener('focus',function (e) {anchFocusColor(this);},false);
                  a.addEventListener('blur',function (e) 
                      {anchBlurColor(this);},false);
                  a.id = datum[1]; // word_id or href
                  a.innerHTML = datum[2]; // acronym
                c.appendChild(a);
              r.appendChild(c); // acronym
                c = document.createElement("td");
                c.className = "tdacro";
                c.innerHTML = datum[3];
              r.appendChild(c); // context
                c = document.createElement("td");
                c.className = "tdacro";
                c.innerHTML = datum[4];
              r.appendChild(c); // explanation - expansion
              if (ie) {
                h.appendChild(r);
              } 
              else {
                theTable.appendChild(r);
              }
            }
          }
          q = document.getElementById('q');
          q.value = '';
          if (a != null) {
            a.focus();
          }
          if (location.hostname == "www.kexsof.com") {
            _uacct = "UA-2492202-1";
            urchinTracker();
          }
        } 
        else {
          alert("In displayRef() function. xmlHttp.status != 200 or");
          alert("xmlHttp.status == "+xmlHttp.status);  
        }
      }
      catch(e) {
        alert('In displayRef function: Caught Exception in reference request: ' + e.number+"-"+e.name+"; "+e.description+"; "+e.message);
      }
    } 
    else {
      if (xmlHttp.readyState < 0 || xmlHttp.readyState > 4) {
        alert("Unidentified readyState from request: "+xmlHttp.readyState);
      }
    }
  }
  catch( e ) {
    alert('In displayRef function, Caught Exception number: ' + e.number+"\nname: "+e.name+"\ndescription: "+e.description+"\nmessage: "+e.message);
    //alert('Server Status: '+xmlHttp.statusText+' : '+xmlHttp.readyState);
  }
};

function acrymGet() {
  item = document.getElementById('q');
  var word = item.value;  // user inputs word to search for
//alert("acrymGet() 0:\n arg="+word);
  xmlHttp = GetXmlHttpObject();
  if (!xmlHttp) {
    alert ("Browser does not support (AJAX) HTTP Request");
    return false;
  }
  var url="acrymGet.php";
  args = "q="+word;
  //args += "&sid="+Math.random();
  xmlHttp.onreadystatechange = function () {displayRef(xmlHttp); };
  xmlHttp.open("POST",url,true);
  //xmlHttp.open("POST",url+'?'+args,true);
  xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
  xmlHttp.send(args);
  //xmlHttp.send(null);
  return false;
};

function acrymRef(id) { 
//alert("acrymRef() 0:\n arg="+id);
  if (item = document.getElementById(id)) {  // will this work?
    item.focus();
  } 
  else { // load the acronym
    xmlHttp = GetXmlHttpObject();
    if (!xmlHttp) {
      alert ("Browser does not support HTTP Request");
      return;
    }
    var url="acrymRef.php";
    var args = "q="+id;
    //args += "&sid="+Math.random();
    xmlHttp.onreadystatechange = function () {
      displayRef(xmlHttp); 
    };
    xmlHttp.open("POST",url+'?'+args,true);
    xmlHttp.send(null);
  }
};

function clearList() {
//alert("clearList() 0");
  var d = document.getElementById("theDiv");
  d.innerHTML = ''; // completely obliterates the table
  cleanup();
};

function listAll() { 
//alert("acrymRef() 0:\n arg="+id);
  clearList();
  xmlHttp = GetXmlHttpObject();
  if (!xmlHttp) {
    alert ("Browser does not support HTTP Request");
    return;
  }
  var url="acrymAll.php";
  //args += "&sid="+Math.random();
  xmlHttp.onreadystatechange = function () {
    displayRef(xmlHttp); 
  }
  xmlHttp.open("POST",url,true);
  xmlHttp.send(null);

};

function reLoad(){
  history.go(-1); 
  cleanup();
};

function removeChecked() {
//alert("removeChecked 0");
  var theDiv = document.getElementById("theDiv");
  var t = theDiv.getElementsByTagName("table")[0]; 
  var box = new Array();
  box = t.getElementsByTagName("input");
  var b; var x; var p;
  var num = box.length;
  var n = 0; 
  for (i = num-1; i >= 0; i--) {
    b = box[i];
    if (b.getAttribute("value") != "box") { 
      continue; 
    }
    if ( b.checked ) {
      x = b;
      // look for parent row
      while (x.tagName != "TR" && x.tagname != 'tr') {
        x = x.parentNode;
      }
      p = x.parentNode; // get the parent
      p.removeChild(x); // remove the row*/
      n++;
    }  
  }
  cleanup();
  if (n === 0) {
    alert("No rows were removed.");
  } 
  else if( n == 1 ) {
    alert("One row was removed.");
  } 
  else {
    alert(n+" rows were removed.");
  }
};

function countChecked() {
//alert("In countChecked");
  var theDiv = document.getElementById("theDiv");
  var t = theDiv.getElementsByTagName("table")[0];
  if (typeof t == "undefined") {
    return false;
  }
  var row = new Array();
  box = t.getElementsByTagName("input");
  var b; var n = 0; 
  for(i = 0; i < box.length; i++){
    b = box[i];
    if( b.getAttribute("value") != "box" ) { continue; }
    if( b.checked ) {
      n++;
    }
  }
  cleanup();
  if( n === 0 ){
    alert("No rows are checked.");
  } else if( n == 1 ) {
    alert("One row is checked.");
  } else{
    alert(n+" rows are checked.");
  }
  return true;
};

function sortList() {
//alert("sortList() 0");
  try {
    var oldRows = new Array();
    var newRows = new Array();
    var cell;
    var mark = new Array();
    var theDiv = document.getElementById("theDiv");
    var oldTable = theDiv.getElementsByTagName("table")[0]; // not part of DOM tree & true=>all subnodes
    oldRows = oldTable.getElementsByTagName("tr"); // remember: row[0] is the header
    var num = oldRows.length;
    var acro; var nxacro; var ref; var nxref; var x;
    // loops go from oldRows 1 to skip header oldRows (oldRows 0)
    for(var n=1; n<num; n++) { // initialize row marking: 1 means row is not sorted
      mark[n] = 1;
    }
    // CANNOT USE SORT VERB HERE BECAUSE IT SORTS THE HEADER 'THEAD'
    var newTable = newAcroTable();
    createHeader(newTable);
    var newTBody = document.createElement('tbody');
    newTable.appendChild(newTBody);
    for(n=1; n<num; n++) { 
      for(var i=1; i<num; i++) { 
        if( mark[i] === 0 ) { continue; }
        x = i;
        anchor = oldRows[i].getElementsByTagName("td")[1].getElementsByTagName("a")[0]; 
        acro = anchor.innerHTML;
        ref = anchor.id;
        for(var j=1; j<num; j++) {
          if( mark[j] === 0 || j == i ) { continue; }
          anchor = oldRows[j].getElementsByTagName("td")[1].getElementsByTagName("a")[0]; 
          nxacro = anchor.innerHTML;
          nxref = anchor.id;
          if( acro.toLowerCase() > nxacro.toLowerCase() || ( acro.toLowerCase() == nxacro.toLowerCase() && ref.toLowerCase() > nxref.toLowerCase() )){
            x = j;
            acro = nxacro;
            ref = nxref;    
          }
        }
        break;
      }
      newRows[n] = oldRows[x].cloneNode(true);
      newTBody.appendChild(newRows[n]);
      mark[x] = 0; // cross out original oldRows x
    }
    theDiv.innerHTML = '';
    theDiv.appendChild(newTable);
    theDiv = document.getElementById("theDiv");
    anchorList = theDiv.getElementsByTagName("a");
    for (i = 0; i < anchorList.length; i++) {
      anchor = anchorList[i];
      if (anchor.className == "acrymFind" ) {
        anchor.addEventListener('focus',function (e) {anchFocusColor(this);},false);
        anchor.addEventListener('blur',function (e) {anchBlurColor(this);},false);
      }
    }
    cleanup();
  }
  catch (e) {
    alert('In displayRef function, Caught Exception number: ' + e.number+"\nname: "+e.name+"\ndescription: "+e.description+"\nmessage: "+e.message);
    if( !confirm("Do you want the sort to complete?") ) {
      return;
    }
  }
};