var xml;
var xslText;

function doOnLoad() {
  lijst = document.getElementById("boekenlijst");
  if (lijst) {
    loadAndDisplay();
  }
}

function createRequest() {
  if (window.XMLHttpRequest) {
    _xhttp = new XMLHttpRequest();
  }
  else {
    _xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  return _xhttp;
}

function loadXMLDoc(dname, callback) {
  xhttp = createRequest();
  xhttp.onreadystatechange = function () {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      callback(xhttp.responseXML);
    }
  }
  xhttp.open("GET", dname, true);
  xhttp.send("");
}

function loadTextDoc(dname) {
  xhttp = createRequest();
  xhttp.open("GET", dname, false);
  xhttp.send("");
  return xhttp.responseText;
}

function loadDataAndDisplay() {
  loadXMLDoc("/bibliotheek/werk.xml", loadXsl);
}

function loadXsl(xmlDoc) {
  xml = xmlDoc;
  xslText = loadTextDoc("/bibliotheek/werk.xsl");
  displayResult();
}

function displayResult() {
  //setTimeout("displayResultAsync()", 1);
  displayResultAsync();
}

function displayResultAsync() {
  // code for IE
  if (window.ActiveXObject) {
    ex = xml.transformNode(processXsl(xslText));
    document.getElementById("boekenlijst").innerHTML = ex;
  }
  // code for Mozilla, Firefox, Opera, etc.
  else if (document.implementation && document.implementation.createDocument) {
    xsltProcessor = new XSLTProcessor();
    xsltProcessor.importStylesheet(processXsl(xslText));
    resultDocument = xsltProcessor.transformToFragment(xml, document);
    document.getElementById("boekenlijst").innerHTML = "";
    document.getElementById("boekenlijst").appendChild(resultDocument);
  }
}

function processXsl(txt) {
  var strSearchComponist = buildColumnSearch("filter_componist", "maker");
  var strSearchTitel = buildColumnSearch("filter_titel", "titel");
  var strSearchNummer = buildColumnSearch("filter_nummer", "nummer");
  var strSelect = "dataroot/Alle_x0020_werken[" + strSearchComponist + " and "+ strSearchTitel+ " and "+ strSearchNummer + "]";
  xslProcess = xslText.replace("_SELECT_", strSelect);
  xslProcess = xslProcess.replace("_SORT_", "maker");
  return stringToDom(xslProcess);
}

function buildColumnSearch(columnName, fieldName) {
  var strSearch = "contains(translate(" + fieldName + ", 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '_SEARCH_VALUE_')";
  return strSearch.replace("_SEARCH_VALUE_", document.getElementById(columnName).value.toLowerCase());
}

function stringToDom(text) {
  if (window.ActiveXObject) {
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = "false";
    xmlDoc.loadXML(text);
  }
  else // Internet Explorer
  {
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(text, "text/xml");
  }
  return xmlDoc;
}

function refilter() {
  displayResult();
}

function loadAndDisplay() {
  loadDataAndDisplay();
}


